访问setter时的nullPointerExcepction(Android)

时间:2017-04-24 18:47:29

标签: android nullpointerexception

我有一个用户对象,其中一个成员是一个arraylist,我创建了一个这个用户的实例,并在尝试设置新的数组列表时,它一直在粉碎"尝试调用虚方法Classes.User.setUser_stocks_array(的java.util.ArrayList)'在null对象引用"

活动1:

private User localUser;
localUser = new User("", email);

String jsonString = new Gson().toJson(localUser);
Intent loginUserIntent = new Intent(getBaseContext(), StockListActivity.class);
                                    loginUserIntent.putExtra("EXTRA_USER_FROM_LOGIN", jsonString);
startActivity(loginUserIntent);

活动2:

    public User gsonReturnUser(String jsonInString){
        Gson gson = new Gson();
        User tmpUser = gson.fromJson(jsonInString, User.class);

        Stock s1 = new Stock("hsdsf", "aa", 15, 20, "yes 4");
        Stock s2 = new Stock("cvcx", "aa", 25, 50, "yes fgfd");
        Stock s3 = new Stock("asd", "aa", 45, 54, "yes fdg");
        Stock s4 = new Stock("uiudf", "aa", 75, 98, "yes cv");

        ArrayList<Stock> tmpList = new ArrayList<Stock>();
        tmpList.add(0, s1);
        tmpList.add(1, s2);
        tmpList.add(2, s3);
        tmpList.add(3, s4);

        tmpUser.setUser_stocks_array(tmpList);

        return tmpUser;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stock_list);
        String userFromLogin = getIntent().getStringExtra("EXTRA_USER_FROM_LOGIN");
        localUser = gsonReturnUser(userFromLogin);
        stockList =  localUser.getUser_stocks_array();
}

我的塞特:

public void setUser_stocks_array(ArrayList<Stock> user_stocks_array) {
    this.user_stocks_array = user_stocks_array;
}

为什么会这样? 谢谢!

更新 我的第一个活动未正确启动,这是nullPointerException的原因。

2 个答案:

答案 0 :(得分:1)

您的tmpUser对象可能从gson.fromJson()方法获得null响应。

答案 1 :(得分:0)

下次,我建议使用parcelable而不是json字符串来发送objec