Reputation: 53
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()
Upvotes: 0
Views: 56
Reputation: 132992
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());
Upvotes: 1