在尝试从全局变量中获取值时获取Null Pointer Exception

时间:2014-05-31 10:47:46

标签: 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 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 ,,,但是当我尝试从另一个类获取值时,我得到Null指针异常

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());


    }

5 个答案:

答案 0 :(得分:0)

而不是使用

`GlobalVariables newObj = new GlobalVariables();
    System.out.println( newObj.getUserId());`

使用

System.out.println((GlobalVariables) getApplication()).getUserId());

答案 1 :(得分:0)

您正在设置课程:

GlobalVariables newObj = new GlobalVariables();

所以你在下一行中有空指针异常是正常的:

 System.out.println( newObj.getUserId());

我建议您使用Singleton Pattern或Static Class来存储全局变量。

答案 2 :(得分:0)

您正在尝试获取Application类变量,请更改此

 GlobalVariables newObj = new GlobalVariables();
        System.out.println( newObj.getUserId());

 GlobalVariables newObj = (GlobalVariables) getApplication();
        System.out.println(newObj.getUserId());

答案 3 :(得分:0)

我看不到newObj.UseId属性的初始化。 无论如何,如果你想避免Nullpointer异常,试试这个:

public String getUserId() {
return userId==null?String.Empty:userId;

}

答案 4 :(得分:0)

您的initialization数据位于何处,请加constructor

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
}

如果你有字段,那么总是把构造函数放在一边。