Reputation: 101
I'm trying to make app with something like UserKeyID, which is random number generated on first app boot and it should be saved in phone memory using SharedPreferences. Everything is working fine untill number is being saved in SharedPrefs, because it's not happening. I know that phone is generating number, it's even sending it to my database using the same variable I want to save in SharedPrefs.
My code looks like that
SplashScreen (Place where number is generated, sent to databse and should be saved in SPrefs) :
@Override
protected void onCreate(Bundle savedInstanceState) { ...
context = getApplicationContext();
sharedPref = context.getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
if (sharedPref.getBoolean("firstrun", true)) {
new GetAllUsers().execute();
}
<...> AsyncTask
do {
KeyID = rand.nextInt(999999 - 99999) + 99999;
Log.d("KeyID : ", KeyID + "");
isUnique = true;
for(int i = 0; i < Ids.length; i++) {
if((KeyID + "").contains(Ids[i]))
isUnique = false;
}
} while(isUnique == false);
return null;
}
protected void onPostExecute(String file_url) {
sharedPref.edit().putString("KeyID", KeyID + "").commit();
new AddNewUser().execute();
sharedPref.edit().putBoolean("firstrun", false).commit();
Intent i = new Intent(SplashScreen.this, FragmentsActivity.class);
startActivity(i);
finish();
}
Like I said, number KeyID is sent to database as it should be, but I cannot access it from other activities like that :
sharedPref = SplashScreen.context.getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
if(commentUsers[position].equals(sharedPref.getString("UserKeyID", "")) != true) {
deleteComment.setVisibility(View.GONE);
}
Upvotes: 0
Views: 42
Reputation: 8598
That's because you're using 2 different keys. Saving under:
"KeyID"
and retrieving using
"UserKeyID"
This is the exact reason why constants should be used for keys, eg.
public static final KEY_USER_ID = "user_id";
and then, instead of hardcoded strings, just use the constant. Never will you have a situation when you misspell/use the wrong key etc, in your case:
sharedPref.edit().putString(KEY_USER_ID, KeyID + "").commit();
and later:
if(commentUsers[position].equals(sharedPref.getString(KEY_USER_ID, "")) != true) {
deleteComment.setVisibility(View.GONE);
}
Upvotes: 3