从SharedPreferences访问对象后,为什么会出现NullPointerException?

时间:2017-02-19 09:19:43

标签: java android nullpointerexception gson

我使用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()));
    }
}

3 个答案:

答案 0 :(得分:0)

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

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

在Account类中,您已使用Context参数创建构造函数?

答案 1 :(得分:0)

您正在使用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);
} 

希望你喜欢这个。 :)

答案 2 :(得分:0)

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

getPreferences(int mode)

返回当前Activity的SharedPreferences对象,因此String&#34; newAccount&#34;保存在CreateAccount活动中的内容未在MainScreen活动中检索。

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

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

抱歉我的英文。 我希望能有所帮助。