i am trying to use SharedPreferences
to login or register
SharedPreferences sp=getSharedPreferences("Login", MODE_PRIVATE);
SharedPreferences.Editor Ed=sp.edit();
Log.d("my id",jsonObject.getString("id"));
Ed.putString("userid",jsonObject.getString("id"));
Ed.commit();//or Ed.apply();
and in the other code while trying to get it
SharedPreferences sharedpreferences= getSharedPreferences("login", MODE_PRIVATE);
String id= sharedpreferences.getString("userid",null);
if(id==null)//sharedpreferences.contains("userid")==false)
{
Log.d("pref","No Id");
}
and it's always printing No Id
A SharedPreferences
object points to a file containing key-value pairs
and provides simple methods to read and write them. Each SharedPreferences file is managed by the framework and can be private or shared.
Your KEY
must be same. Read official guideline about getSharedPreferences
.
SharedPreferences sharedpreferences = getSharedPreferences("Login", MODE_PRIVATE);
And
SharedPreferences sp = getSharedPreferences("Login", MODE_PRIVATE);
Please set the same key while set and get data. You've set Login while set data and using login while get data. Both keys should be same.
You are setting it in Login
and getting it from login
. They should be the same.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.