繁体   English   中英

android Sharedpreferences 非活动 class

[英]android Sharedpreferences non-activity class

private static String geturl() {
        Context applicationContext = configActivity.getContextOfApplication();
//        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(applicationContext);

        SharedPreferences prefs =applicationContext.getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
        String url = prefs.getString("url", "No name defined");
        return url;
    }

This method is in a non-activity class i tried to have my string from a non-activity class i tried to do like someone say there: Android - How to use SharedPreferences in non-Activity class?

但我有这个错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference

问题出在第一行代码中,getContextOfApplication() 方法返回 null 值:

上下文 applicationContext =configActivity.getContextOfApplication();

由于 Context 可能已经到了其生命周期的尽头,因此通常建议不要将 Context 或 Activity 对象存储为 static 变量,因为这可能会导致 memory 泄漏。 相反,您应该将 Context 或 Activity 包装在 WeakReference 中,并在需要时检查展开后上下文是否不是 null。

在下面的示例中,活动被存储为 WeakReference,并在需要时使用 postExecute() 方法中的 get() 解包。 由于活动可能在 AsyncTask 结束之前结束,这确保没有 memory 泄漏和 NullPointer 异常。

private class MyAsyncTask extends AsyncTask<String, Void, Void> {

    private WeakReference<Activity> mActivity;

    public MyAsyncTask(Activity activity) {
        mActivity = new WeakReference<Activity>(activity);
    }

    @Override
    protected void onPreExecute() {
        final Activity activity = mActivity.get();
        if (activity != null) {
            ....
        }
    }

    @Override
    protected Void doInBackground(String... params) {
        //Do something
        String param1 = params[0];
        String param2 = params[1];
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        final Activity activity = mActivity.get();
        if (activity != null) {
            activity.updateUI();
        }
    }
} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM