在getter函数空指针异常 [英] Null Pointer exception in getter function
问题描述
我正在开发中,我从服务器获取数据的应用程序,我使用getter和setter函数来设置这些。
I am developing an application in which I am getting data from server and I am using getter and setter functions to set these.
下面是我的code ...
Here is my code...
JSONArray arr1 = new JSONArray(strServerResponse);
JSONObject jsonObj1 = arr.getJSONObject(0);
pojo = new Pojo();
empid = jsonObj1.optString("empid");
pojo.setId(empid);
和我使用的getter函数为
And I am using getter function as
Pojo pojo = new Pojo();
String id = pojo.getId();
下面是我的setter和getter函数
Here are my setter and getter functions
public class Pojo {
private String empid;
public void setId(String empid) {
this.empid = empid;
}
public String getId() {
return empid;
}
}
我得到的空指针异常是在哪里我使用的getter函数。
难道我做错了什么?任何人都可以请帮助我。
I am getting Null Pointer Exception at where I am using getter function. Am I doing anything wrong? Can anyone please help me.
推荐答案
如果您正在创建从 POJO
一旦一个对象,你不必创建一个又一个 GET
因此删除 POJO的POJO = POJO的新();
,只是把:
If you are creating an object from pojo
once, you don't have to create another one to get
so remove the Pojo pojo = new Pojo();
and just put :
String id=pojo.getId();
您code应该是这样的:
Your code should be like :
JSONArray arr1 = new JSONArray(strServerResponse);
JSONObject jsonObj1 = arr.getJSONObject(0);
pojo = new Pojo();
empid = jsonObj1.optString("empid");
pojo.setId(empid);
String id = pojo.getId();
然后在同一个对象你有你的ID。
这篇关于在getter函数空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!