SharedPreferences Null指针异常

时间:2015-06-12 20:40:15

标签: android nullpointerexception sharedpreferences

我正在尝试保存一个整数,该整数将存储用户使用SharedPreferences界面轻击ImageView的次数。但是,当我运行应用程序时,它会在我声明sharedPreferences的行上给出空指针异常:

SharedPreferences mSharedPreferences = this.getPreferences(Context.MODE_PRIVATE);

这是我第一次使用这个界面,对我来说有点困惑。我不知道为什么会这样。 这是日志:

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{koemdzhiev.com.eggyegg/koemdzhiev.com.eggyegg.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
        at android.app.ActivityThread.access$800(ActivityThread.java:151)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5254)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
        at android.content.ContextWrapper.getPackageName(ContextWrapper.java:132)
        at android.app.Activity.getLocalClassName(Activity.java:4987)
        at android.app.Activity.getPreferences(Activity.java:5021)
        at koemdzhiev.com.eggyegg.MainActivity.<init>(MainActivity.java:20)
        at java.lang.reflect.Constructor.newInstance(Native Method)
        at java.lang.Class.newInstance(Class.java:1606)
        at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
        at   

这是我在Application类中扩展的代码:

public class EggyEggApplication extends Application {

@Override
public void onCreate() {
    SharedPreferences mSharedPreferences = this.getSharedPreferences(getString(R.string.koemdzhiev_eggyegg_PREFERENCE_FILE_KEY), Context.MODE_PRIVATE);
    SharedPreferences.Editor mEditor = mSharedPreferences.edit();
    if(mSharedPreferences.contains(getString(R.string.koemdzhiev_eggyegg_PREFERENCE_FILE_KEY))== false) {
        mEditor.putInt(getString(R.string.koemdzhiev_eggyegg_PREFERENCE_FILE_KEY), 0).apply();
    }
}

这是我在主要活动中的代码:

public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private int defaultValue;
private int i;
ImageView tapImage;
SharedPreferences mSharedPreferences = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor mEditor = mSharedPreferences.edit();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    tapImage = (ImageView)findViewById(R.id.tapImage);
    tapImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            i++;
            mEditor.putInt(getString(R.string.koemdzhiev_eggyegg_PREFERENCE_FILE_KEY),i);
            mEditor.commit();
        }
    });
    defaultValue = getResources().getInteger(R.string.koemdzhiev_eggyegg_PREFERENCE_FILE_KEY);
    i = mSharedPreferences.getInt(getString(R.string.koemdzhiev_eggyegg_PREFERENCE_FILE_KEY),defaultValue);



    int defaultValue = getResources().getInteger(R.string.koemdzhiev_eggyegg_PREFERENCE_FILE_KEY);
    long lastTapNumber = mSharedPreferences.getInt(getString(R.string.koemdzhiev_eggyegg_PREFERENCE_FILE_KEY),defaultValue);
    i = (int) lastTapNumber;

}
private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager
            = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
@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, menu);
    return true;
}

4 个答案:

答案 0 :(得分:6)

问题在于您的MainActivity中的这一行:

SharedPreferences mSharedPreferences = this.getPreferences(Context.MODE_PRIVATE);

异常说,你得到一个nullpointer,

这个nullpointer发生是因为上下文为null, 发生这种情况是因为上述行是在活动完成创建之前执行的,

所以把这一行移到你的onCreate方法应该解决问题

答案 1 :(得分:2)

在活动中,移动

SharedPreferences mSharedPreferences = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor mEditor = mSharedPreferences.edit();

onCreate内。哟需要Context才能访问SharedPreferences。在getPreferences(Context.MODE_PRIVATE)内部,请致电getPackageName

修改

您应该避免使用本地化字符串作为SharedPreferences

的键

答案 2 :(得分:1)

嗯,你说你保存整数,所以他们关键词是

DECLARE @EmploymentLength TABLE
  (
   EmployeeID INT,
   Date DATE,
   DateFlag CHAR(1),
   RowNumber INT
  );

INSERT  INTO @EmploymentLength
        (
         EmployeeID,
         Date,
         DateFlag
        )
        SELECT  z.EmployeeID,
                z.Date,
                z.DateFlag
        FROM    (SELECT EmployeeId,
                        HireDate AS Date,
                        'H' AS DateFlag
                 FROM   dbo.Employment
                 WHERE  EmployeeId = 328195
                        AND HireDate IS NOT NULL
                 UNION
                 SELECT EmployeeId,
                        TerminationDate AS Date,
                        'T' AS DateFlag
                 FROM   dbo.Employment
                 WHERE  EmployeeId = 328195
                        AND TerminationDate IS NOT NULL) z;


SELECT  *
FROM    @EmploymentLength
ORDER BY Date;
编辑:我的坏!创建方法

可能有问题

答案 3 :(得分:0)

尝试 -

def form_valid(self):
    response = super(UserCreateView, self).form_valid()
    self.object.user_groups = self.form.cleaned_data['groups']
    return response