【问题标题】:Why am I Getting a NullPointerException After Accessing an Object From SharedPreferences? [duplicate]为什么从 SharedPreferences 访问对象后会出现 NullPointerException? [复制]
【发布时间】:2017-02-19 09:19:43
【问题描述】:

我使用 gson 在 SharedPreferences 中保存了一个对象 (Account),但在新 Activity 中访问该对象后,该对象的实例 (newAccount) 导致我使用 newAccount.returnName() 时给出 NullPointerException。错误是:原因:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“java.lang.String com.cashtrack.kennethlee.cashtrack.Account.returnName()” .我了解 NullPointer 错误是什么,但我不明白为什么我可能会得到它,因为我是 Android Studio 的新手。第一个活动的代码是:

package com.cashtrack.kennethlee.cashtrack;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

public class CreateAccount extends AppCompatActivity {

    SharedPreferences accountsPref;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_account);
        setTitle("Create New Account");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        accountsPref = getPreferences(MODE_PRIVATE);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_create_account, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            //back button
            case android.R.id.home:
                // app icon in action bar clicked; go home
                Intent intent = new Intent(this, MainScreen.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                return true;

            //save button
            case R.id.action_menu_save:

                // get EditText by id
                EditText inputTxt1 = (EditText) findViewById(R.id.AccountName);
                // Store EditText in Variable
                String name = inputTxt1.getText().toString();

                EditText inputTxt2 = (EditText) findViewById(R.id.StartingBalance);
                double balance = Double.parseDouble(inputTxt2.getText().toString());

                Account newAccount = new Account(name, balance);

                SharedPreferences.Editor editor = accountsPref.edit();
                Gson gson = new Gson();
                String json = gson.toJson(newAccount);
                editor.putString("newAccount", json);
                editor.commit();

                Intent intent2 = new Intent(this, MainScreen.class);
                intent2.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent2);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}

正在访问对象并导致错误的活动的代码是:

package com.cashtrack.kennethlee.cashtrack;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

import com.google.gson.Gson;

import java.io.FileInputStream;
import java.io.StringWriter;
import java.util.ArrayList;

public class MainScreen extends AppCompatActivity {
    //array list of accounts
    ArrayList<Account> accounts = new ArrayList<>();

    SharedPreferences accountsPref;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_screen);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(MainScreen.this, CreateAccount.class));
            }
        });
        accountsPref = getPreferences(MODE_PRIVATE);

        //  PRINT TO A TEXT BOX
        //setContentView(R.layout.activity_main_screen);
        //TextView textView = (TextView) findViewById(R.id.textView4);
        //textView.setText(hello.returnName());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main_screen, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onResume() {
        super.onResume();

        Gson gson = new Gson();
        String json = accountsPref.getString("newAccount", "");
        Account newAccount = gson.fromJson(json, Account.class);
        accounts.add(newAccount);


        setContentView(R.layout.activity_main_screen);
        TextView textView1 = (TextView) findViewById(R.id.textView5);
        textView1.setText(accounts.get(0).returnName());

        TextView textView2 = (TextView) findViewById(R.id.textView6);
        textView2.setText(Double.toString(accounts.get(0).returnAvailableBalance()));
    }
}

【问题讨论】:

    标签: java android nullpointerexception gson


    【解决方案1】:

    您正在使用 MODE_PRIVATE 指定用于存储值的文件名。推荐的方式是使用默认模式,不指定文件名。像这样:

    看跌值:

    accountPref = PreferenceManager.getDefaultSharedPreferences(this);
    Gson gson = new Gson();
    String json = gson.toJson(Account);
    accountPref.edit().putString("newAccount", json).apply();
    

    获取价值:

    SharedPreferences accountsPref = PreferenceManager.getDefaultSharedPreferences(this);
    if (accountsPref.contains("newAccount")) {
        Gson gson = new Gson();
        String json = accountsPref.getString("newAccount", "");
        Account newAccount = gson.fromJson(json, Account.class);
        accounts.add(newAccount);
    } 
    

    希望你喜欢这个。 :)

    【讨论】:

    • 获取字符串json后(get value中的第三行),如何获取对象本身?
    • 哪个对象?你没有得到你在 CreateAccount 活动中输入的字符串值吗?您要从该特定 SharedPreference 中添加新值还是删除值?
    • 我希望能够使用来自 CreateAccount 的名为 newAccount 的类 Account 的实例。我在 MainScreen 中有一个 Account 数组列表,我想将 CreateAccount 中的新帐户添加到该数组列表中。
    • 请查看编辑后的答案。
    • 非常感谢!!现在可以使用了。
    【解决方案2】:

    我认为您必须在 onCreate() 中初始化您的 Account 类。

    没有初始化会导致空指针异常。

    您在 Account 类中创建了带有 Context 参数的构造函数?

    【讨论】:

    • 我在案例中进行了初始化,因为我在其中获得了对象的名称和余额变量,因此我必须在获得这两个变量后进行初始化。我在帐户类构造函数中也没有上下文参数。这样做的目的是什么?
    【解决方案3】:

    我认为你有这个问题是因为

    getPreferences(int mode)
    

    为当前的Activity返回一个SharedPreferences对象,这样保存在CreateAccount Activity中的String“newAccount”在MainScreen Activity中不会被检索到。

    所以当你使用Account newAccount = gson.fromJson(json, Account.class); 时,newAccount 为空,因为json 是一个空字符串。

    您可以考虑使用getSharedPreferences(String sharedPreferenceName, int mode) 而不是getPreferences(int mode),在您的活动中调用该方法时使用相同的sharedPreferenceName

    对不起我的英语。 希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-26
      • 2016-09-06
      • 2018-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-17
      相关资源
      最近更新 更多