Java 尝试从全局变量获取值时获取空指针异常
这是存储全局变量的类Java 尝试从全局变量获取值时获取空指针异常,java,Java,这是存储全局变量的类 public class GlobalVariables extends Application { private String userToken; private String userId; private String userName; public String getUserName() { return userName; } public String getUserId() { return userId; } public St
public class GlobalVariables extends Application {
private String userToken;
private String userId;
private String userName;
public String getUserName() {
return userName;
}
public String getUserId() {
return userId;
}
public String getUserToken() {
return userToken;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setUserId(String userId) {
this.userId = userId;
}
public void setUserToken(String userToken) {
this.userToken = userToken;
}
}
现在我正在登录类中设置值
GlobalVariables newObj = new GlobalVariables();
newObj.setUserId(user_values.getString("id"));
newObj.setUserName(user_values.getString("name"));
System.out.println(newObj.getUserId());
我在systemout中获取该值,,,但当我尝试从另一个类获取该值时,得到的是空指针异常
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.timetable);
TextView test = (TextView) findViewById(R.id.testing);
GlobalVariables newObj = new GlobalVariables();
System.out.println( newObj.getUserId());
}
而不是使用
`GlobalVariables newObj = new GlobalVariables();
System.out.println( newObj.getUserId());`
使用
System.out.println((全局变量)getApplication()).getUserId())代码>您正在安装课程:
GlobalVariables newObj = new GlobalVariables();
因此,在下一行中执行以下操作时,出现空指针异常是正常的:
System.out.println( newObj.getUserId());
我建议您使用单例模式或静态类来存储全局变量。您试图获取应用程序类变量,因此,请更改此设置
GlobalVariables newObj = new GlobalVariables();
System.out.println( newObj.getUserId());
到
我看不到newObj.UseId属性的初始化。
无论如何,如果希望避免Nullpointer异常,请尝试以下操作:
public String getUserId() {
return userId==null?String.Empty:userId;
}数据的初始化在哪里,请放置构造函数
public GlobalVariables() {
super();
userToken = "";
userId = "";
userName = "";
}
这里您关心的是创建一个ne对象
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.timetable);
TextView test = (TextView) findViewById(R.id.testing);
GlobalVariables newObj = new GlobalVariables();//do not initilize
System.out.println( newObj.getUserId());//must get null pointer exception
}
所以,如果您有字段,请始终放置构造函数。为什么要使用new
关键字??它会清除你所有的数据。。试试这个<代码>全局变量newObj;System.out.println(newObj.getUserId())代码>看一看,我试过,,,它给出了相同的错误,,,在存储时也应该这样做
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.timetable);
TextView test = (TextView) findViewById(R.id.testing);
GlobalVariables newObj = new GlobalVariables();//do not initilize
System.out.println( newObj.getUserId());//must get null pointer exception
}