RuntimeException when trying to store value fetched from server to sharedpreferences using Asynctask

跟風遠走 提交于 2019-12-13 08:45:33

问题


i am using sharedpreferences to check the app is using for the first time or not.if the app is using for first time registration screen will show , and after that MainActivity will show if registration is completed succussfully or used later . Registration screen is showing when app is runnig for first time but the issue is there in Registering. while calling the shared preferences from MainActivity to insert value in it. and the issue is RuntimeException .this is what i am doing for that...

this is my MainActivity.java

 SharedPreferences sp;

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

this is first_time_check()

private boolean firtst_time_check(){
    sp = PreferenceManager.getDefaultSharedPreferences(this);
    String first = sp.getString("first", null);
    if (first == null){
        Intent i = new Intent(getBaseContext(), MainActivity.class);
        startActivity(i);
    }
    return false;
}

this is code from Registration screen where exception is throwing in this line MainActivity set = new MainActivity();

JSONArray a = o.optJSONArray("status");
JSONObject obj = a.optJSONObject(0);
String uid = obj.optString("RegistrationID");
MainActivity set = new MainActivity();
set.sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String value = set.sp.getString("RegistrationID", uid);
SharedPreferences.Editor editor = set.sp.edit();
editor.putString("first", value);
editor.commit();

this is what showing in logcat

lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

回答1:


No, need to use sp from MainActivity by creating object of Activity for saving value in SharedPreferences in Registration screen because PreferenceManager.getDefaultSharedPreferences also return SharedPreferences instance which we can use for saving and key-value in it. Change :

MainActivity set = new MainActivity();
set.sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

to

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(
                       getApplicationContext());


来源:https://stackoverflow.com/questions/35173611/runtimeexception-when-trying-to-store-value-fetched-from-server-to-sharedprefere

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!