Unable to access SharedPreferences value from a class into an activity - android

I am working on a server baser application so whenever a user logs in i have to capture his unique userId and use it in different activities in my whole project.
So after getting the userId from JSONObject i am putting it in sharedPrederence and getting it in another activity but after entering into my main activity which is after successful login the shared preference shows me the default value of userId which is zero.
Here is my code in PostData.java class which will work in background of login activity:
private SharedPreferences userIdSharedPreferences;
private SharedPreferences.Editor userIdEditor;
try {
JSONObject obj = new JSONObject(response.toString());
//boolean requestStatus = obj.getBoolean("requestStatus");
JSONObject data = obj.getJSONObject("data");
userId = Integer.parseInt(data.getString("userId"));
userIdEditor = userIdSharedPreferences.edit();
userIdEditor.putInt("crrUserId", userId);
userIdEditor.apply();
userIdEditor.commit();
} catch (JSONException e) {
e.printStackTrace();
}
and here is how i am using that sharedPreference value in other acitivity:
userIdSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
crrUserId = userIdSharedPreferences.getInt("crrUserId", 0);
Toast.makeText(getApplicationContext(), "Your user id is: " + crrUserId, Toast.LENGTH_SHORT).show(); //This toast showing 0 which is default i set.
EDIT
for more clarification now i am passing my userId from my background class PostData.java to my LoginActivity using the below function:
Integer passUserId() {
return userId;
}
and from there i am passing userId using sharedPreference like this:
Intent loginSuccess = new Intent(getApplicationContext(), MainActivity.class);
Integer crrUserId = Login.passUserId(); //Login is name of variable which will accespassUserId function in PostData.java class
SharedPreferences userIdSharedPreferences = getApplicationContext().getSharedPreferences("userId", 0);
SharedPreferences.Editor userIdEditor;
userIdEditor = userIdSharedPreferences.edit();
userIdEditor.putInt("crrUserId", crrUserId);
userIdEditor.apply();
startActivity(loginSuccess);
finish();
and here is how i am using in my mainactivity:
public class MainActivity extends AppCompatActivity {
SharedPreferences userIdSharedPreferences;
SharedPreferences.Editor userIdEditor;
Integer crrUserId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userIdSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
crrUserId = userIdSharedPreferences.getInt("userId", 0);
Toast.makeText(getApplicationContext(), "Your user id is: " + crrUserId, Toast.LENGTH_SHORT).show();
}

Try this:
First you need to initialize userIdSharedPreferences object like below:
userIdSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
After getting object of SharedPreference do this:
userIdEditor = userIdSharedPreferences.edit();
After getting object of SharedPreferences.Editor do your task.

initialiase userIdSharedPreferences may be thats the problem
try {
JSONObject obj = new JSONObject(response.toString());
//boolean requestStatus = obj.getBoolean("requestStatus");
JSONObject data = obj.getJSONObject("data");
userId = Integer.parseInt(data.getString("userId"));
SharedPreferences userIdSharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
SharedPreferences.Editor userIdEditor = userIdSharedPreferences.edit();
userIdEditor.putInt("crrUserId", userId);
userIdEditor.apply(); //apply or commit not both
userIdEditor.commit();
} catch (JSONException e) {
e.printStackTrace();
}

Related

android studio save string shared preference, start activity and load the saved string

I'm trying to save a string to shared preferences and then start an activity and retrieve it but doesn't work. What am I doing wrong?
First I set the shared preference key then I start the activity:
SharedPreferences.Editor editor =
getSharedPreferences("PaymentStatus",MODE_PRIVATE).edit();
editor.putString("payment_status","success");
editor.apply();
Intent i = new Intent(getBaseContext(), ProfileActivity.class);
startActivity(i);
and on the ProfileActivity class I trying to retrieve the key:
SharedPreferences prefs = getSharedPreferences("PaymentStatus",
MODE_PRIVATE);
String payment_status = prefs.getString("payment_status", null);
if(payment_status == "success"){
Log.i("payment status", "success");
}
I can't see the payment status success in the logcat.
The issue with the code you have given is not with how you done it with shared preferences (you did that correctly btw)
Your issue is that you are comparing strings via == as this compares the string reference and not the string value. Use .equals() or .contains() instead.
if (payment_status.equals("success")) {
Log.i("payment status", "success");
}
This is my experience in used SharedPreferens.
Perhaps this approach will solve the problem:
public class UserData {
UserData(MainActivity mainActivity){this.mainActivity = mainActivity;}
private static UserData userData;
private final MainActivity mainActivity;
private SharedPreferences sPref;
private SharedPreferences.Editor editor;
final private String USER_ID = "user_id";
public static void create(MainActivity activity) {
if (userData == null) userData = new UserData(activity);
}
public static UserData getUserData() {
return userData;
}
void createUser() {
sPref = mainActivity.getSharedPreferences("UserData", Context.MODE_PRIVATE);
editor = sPref.edit();
// Если user id уже есть, выходим из метода
if(sPref.contains(USER_ID)) return;
editor.putString(USER_ID, createUserId());
editor.apply();
Toast.makeText(mainActivity,"UserId created", Toast.LENGTH_SHORT).show();
}
// id формируется на основе текущей даты и времени
private String createUserId() {
Date currentDate = new Date();
DateFormat dateFormat = new SimpleDateFormat("ddMMyyyyHHmmss", Locale.getDefault());
return dateFormat.format(currentDate);
}
public String getUserId() {
return sPref.getString(USER_ID, "");
}
}

how to get JSONArray from sharedpreferences into Adapter

In the first activity to load in my app I put my JSONArray into Sharedpreferences (as a String):
//put myJsonArray into shared preferences file as a String
//Convert back to Json later, in the adapter
SharedPreferences sharedPrefs = getSharedPreferences("MyData", Context.MODE_PRIVATE);
//we want to edit SharedPreferences
SharedPreferences.Editor editor = sharedPrefs.edit();
//put the string value into SharedPreferences, with the key "key_value"
editor.putString("key_value", myJsonArray.toString());
//commit the string
editor.commit();
I can get this string in another Activity and convert it back to a JSONArray easily with:
SharedPreferences sharedPrefs = getSharedPreferences("MyData", Context.MODE_PRIVATE);
String json_array = sharedPrefs.getString("key_value", "0");
try
{
JSONArray jsonArray = new JSONArray(json_array);
} catch (JSONException e) {
Log.e("MYAPP", "unexpected JSON exception", e);
}
But when I put the above code in the onBindViewHolder of my adapter, or anywhere else in my adapter, I am getting: NullPointerException and my app crashes.
Please tell me how I can solve this.
Where it crashes it says:
java.lang.NullPointerException at com.example.chris.tutorialspoint.SharedReviews.SharedPopulistoReviewsAdapter.onBindViewHolder(SharedPopulistoReviewsAdapter.java:130)
My onBindViewHolder code is:
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, final int position) {
SharedReview r = the_Shared_reviews.get(position);
SharedPreferences sharedPrefs = context.getSharedPreferences("MyData", Context.MODE_PRIVATE);
String json_array = sharedPrefs.getString("key_value", "0");
try
{
JSONArray jsonArray = new JSONArray(json_array);
System.out.println("SharedAdapter, the jsonarray is :" + jsonArray);
} catch (JSONException e) {
Log.e("MYAPP", "unexpected JSON exception", e);
}
((ReviewHolder) viewHolder).category.setText("Category: " + r.getCategory());
((ReviewHolder) viewHolder).name.setText("Name: " + r.getName());
((ReviewHolder) viewHolder).phone.setText("Phone: " + r.getPhone());
((ReviewHolder) viewHolder).comment.setText("Your Comment: " + r.getComment());
//set an onClick listener for the row, if it's clicked anywhere
((ReviewHolder) viewHolder).itemView.setOnClickListener(new View.OnClickListener() {
#Override
//When the review is clicked in PopulistoListView
//then show that review
public void onClick(View v) {
SharedReview sharedReview = (SharedReview) SharedPopulistoReviewsAdapter.getItem(position);
//we want to pass the review_id of the sharedReview being clicked
//to the ViewContact activity, and from there post it and get more
//info for that sharedReview - address, comments etc
Intent i = new Intent(v.getContext(), ViewContact.class);
//pass the review_id to ViewContact class
i.putExtra("review_id", sharedReview.getReviewid());
v.getContext().startActivity(i);
}
});
}
Line 130 is:
SharedPreferences sharedPrefs = context.getSharedPreferences("MyData", Context.MODE_PRIVATE);
This is happening because you have not initialized context. Either you must initialize context by passing context as a parameter when creating the object of the adapter or you can get the context from a view.
To get the context from a view change the line to:
SharedPreferences sharedPrefs = ((ReviewHolder) viewHolder).category.getContext().getSharedPreferences("MyData", Context.MODE_PRIVATE);

How to get value of SharedPreferences android

I'm trying to use SharedPreferences here is what i do
public void StoreToshared(Object userData){
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(userData);
Log.d("data", " Setup --> "+json);
prefsEditor.putString("userinfo", json);
prefsEditor.commit();
}
Log.d result is like this
Setup --> {"nameValuePairs":{"userData":{"nameValuePairs":{"phone":"089688xxxxxxx",
"username":"username of User","flag":1,"Email":"mymail#mail.com",
"tipe":"TP001","Deskripsi":"Ini tentang gua","user_id":"USER001",
"password":"c83e4046a7c5d3c4bf4c292e1e6ec681","fullname":My fullname"}},"status":"true"}}
then i'm trying to retrieve it, in other activity here is what i do
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = mPrefs.edit();
String data = mPrefs.getString("userinfo", null);
Log.i("Text", "Here is the retrieve");
Log.i("data", " retrieve --> "+data);
}
and here how i open my other activity
Intent intent = new Intent(Login.this, MainActivity.class);
startActivity(intent);
With my script above, the result from my logcat , i only see like Log.d above. So my question is, how can i retrieve it ?
Try to add a key on your SharedPreferences:
public void StoreToshared(Object userData){
SharedPreferences mPrefs = getSharedPreferences("your_sp_key", MODE_PRIVATE); //add key
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(userData);
Log.d("data", " Setup --> "+json);
prefsEditor.putString("userinfo", json);
prefsEditor.commit();
}
Retrieval:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences mPrefs = getSharedPreferences("your_sp_key", MODE_PRIVATE); //add key
SharedPreferences.Editor prefsEditor = mPrefs.edit();
String data = mPrefs.getString("userinfo", null);
Log.i("Text", "Here is the retrieve");
Log.i("data", " retrieve --> "+data);
}
You can create 2 method:
// put value
public static void putPref(String key, String value, Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(key, value);
editor.commit();
}
and
// get value
public static String getPref(String key, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(key, null);
}
then you can put value
putPref("userinfo", "/** user data json */", getApplicationContext());
and get value
String data = getPref("userinfo", getApplicationContext());
I hope it can help your problem!
You need to convert the string data from SharedPreferences back to a PoJo using Gson. Simply do this:
Object userData = new Gson().fromJson(data, Object.class);
I guess that should solve it.
The api: getPreferences will use the activity name to create an xml file if not exists. For example, assume StoreToshared method is put in activity: LoginActivity.java, it will create a file: LoginActivity.xml to store your pref data. Hence, when you go into other activity, let say its name is: MainActivity.java, getPreferences will look into file "MainActivity.xml" instead of "LoginActivity.xml", that is why you cannot retrieve your data.
The solution is to use: getSharedPreferences.
Hence your code can be modified as follow:
public void StoreToshared(Object userData) {
SharedPreferences mPrefs = getSharedPreferences("FILE_NAME",MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(userData);
Log.d("data", " Setup --> "+json);
prefsEditor.putString("userinfo", json);
prefsEditor.commit();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences mPrefs = getSharedPreferences("FILE_NAME",MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = mPrefs.edit();
String data = mPrefs.getString("userinfo", null);
Log.i("Text", "Here is the retrieve");
Log.i("data", " retrieve --> "+data);
}
Hope this help.
In year 2020,
Google has been released new data storage that is repleced of Shared Preference...
It' is developed with "Kotlin"
Source

How to use a value across all activities?

For example: I have a String value "A". and I have activities : activity_a, activity_b, activity_C.
Can I use value "A" across all activities? If yes how to achieve this?
And not through Intent or send data to another activity.
I am sorry that I am not fluent in English.
I moved a token value in login activity to main activity.
I used Intent and move token login activity. this is my login activity code.
StringRequest stringRequest = new StringRequest(Request.Method.POST, serverURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONArray jsonArray = new JSONArray(response);
JSONObject json_code = jsonArray.getJSONObject(0);
JSONObject json_token = jsonArray.getJSONObject(1);
String code = json_code.getString("code");
String token = json_token.getString("token");
Intent myIntent = new Intent(loginActivity.this, mainActivity.class);
myIntent.putExtra("token", token);
startActivity(myIntent);
finish();
overridePendingTransition(R.xml.madefadein, R.xml.splashfadeout);
}catch(JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
switch(error.networkResponse.statusCode)
{
case 409:
Toast.makeText(loginActivity.this, error.networkResponse.toString(), Toast.LENGTH_SHORT).show();
break;
}
}
but in main Activity, I tried to declare static like this.
Intent i = new Intent(getIntent());
public static final String token = i.getStringExtra("token");
but it doesn't work.
1.just declare your String as public static String strTmp="A"; in your activity than you can use any where in your project
like this
String strTmp = yourActivity.str;
2. create a new class like this
public class ServiceClass {
public static String strTmp="Data";
}
now you can access this string anywhere in your project like this
String mystr= ServiceClass.strTmp;
3.if you want use hard String than store your string in res/values/string.xml like this
<resources>
<string name="app_name">PatternView</string>
</resources>
than you can use like this
String str = getResources().getString(R.string.app_name);
4. save it in SharedPreferences like this
code for save data in SharedPreferences like this
SharedPreferences myPref;
SharedPreferences.Editor prefEditor;
myPref = getSharedPreferences("TOKENNAME", MODE_PRIVATE);
prefEditor = myPref.edit();
prefEditor.putString("TOKEN", "your token");
prefEditor.apply();
code for retrieve data from SharedPreferences
SharedPreferences myPref;
myPref = getSharedPreferences("TOKENNAME",
MODE_PRIVATE);
String name = myPref.getString("TOKEN", "");

Android SharedPreferences not loading and saving properly

I've been getting null returns from getting strings from my saved preferences. I'm not sure how savedpreferences worked but my understanding was that when call a sharedpreferences, it creates the keypair file on the phone so you can come back to it later.
My program is essentially a string creation application. When you press a button, it creates a string to send as an sms. My settings activity page has four edittexts that save whatever is inside them with a buttonclick and returns to the main activity. The final button creates a String by getting the value from the keyvalue pair and constructs the message. However, I've always gotten null for each of the values.
Heres the code for the settings page and then the main page. Please ask if I could add more, I didn't add ALL of the code, just the sharedpreferences portions.
public SharedPreferences sp;
public Editor e;
public void savethethings(){ //run this when enter is pressed/savew
EditText smsintro_hint = (EditText) findViewById(R.id.settings_smsintro_hint);
EditText smsbody_hint = (EditText) findViewById(R.id.settings_smsbody_hint);
EditText checkboxbody_hint = (EditText) findViewById(R.id.settings_checkboxbody_hint);
EditText checkboxbody_description_hint = (EditText) findViewById(R.id.settings_checkboxbody_description_hint);
String introstring = smsintro_hint.getText().toString();
String bodystring = smsbody_hint.getText().toString();
String checkboxbodystring = checkboxbody_hint.getText().toString();
String checkboxdescriptionstring = checkboxbody_description_hint.getText().toString();
e.putString("intro", introstring);
e.commit(); // you forgot to commit
if(!bodystring.isEmpty())
{
e.putString("body", bodystring);
e.commit();
}
if(!checkboxbodystring.isEmpty())
{
e.putString("checkbody", checkboxbodystring);
e.commit();
}
if(!checkboxdescriptionstring.isEmpty())
{
e.putString("checkboxdescr", checkboxdescriptionstring);
e.commit();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.settingmenu);
//SP
sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); // forget about
// named preferences - get the default ones and finish with it
e = sp.edit();
Button tt = (Button)findViewById(R.id.savebutton);
tt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
public void save(View view)
{
//THINGS HAPPEN HERE WITH SHARED PREFERENCES :(
savethethings();
this.finish();
return;
}
public String finishedtext(String userstring)
{
smsintroduction = (sp.getString("intro", ""));
smsbody = (sp.getString("body", ""));
checkboxtext = (sp.getString("checkbody", ""));
checkboxmessage = (sp.getString("checkboxdescr", ""));
if(smsintroduction.isEmpty())
{
if(smsbody.isEmpty())
{
if(checkboxtext.isEmpty())
{
if(checkboxmessage.isEmpty()) //topkek for most AND statements Ive ever put in in if/then form
{
//Essentially the DEFAULT if they're ALL null
smsbody = "Hi "+ userstring +"! This is coming from jake's phone and it wants to send a text so we can talk or whatever. ";
}
}
}
}
Toast.makeText( this, "Creating text, then press send!", Toast.LENGTH_LONG).show();
String thetext = "";
thetext = smsintroduction + " " + smsbody + " " + checkboxtext;
return thetext;
}
public void savethethings(){ //run this when enter is pressed/savew
EditText smsintro_hint = (EditText) findViewById(R.id.settings_smsintro_hint);
EditText smsbody_hint = (EditText) findViewById(R.id.settings_smsbody_hint);
EditText checkboxbody_hint = (EditText) findViewById(R.id.settings_checkboxbody_hint);
EditText checkboxbody_description_hint = (EditText) findViewById(R.id.settings_checkboxbody_description_hint);
String introstring = smsintro_hint.getText().toString();
String bodystring = smsbody_hint.getText().toString();
String checkboxbodystring = checkboxbody_hint.getText().toString();
String checkboxdescriptionstring = checkboxbody_description_hint.getText().toString();
// if(!introstring.isEmpty()) //if the fields are NOT empty, they should get saved.
// {
e.putString("intro", introstring);
e.commit(); // you forgot to commit
if(!bodystring.isEmpty())
{
e.putString("body", bodystring);
e.commit();
}
if(!checkboxbodystring.isEmpty())
{
e.putString("checkbody", checkboxbodystring);
e.commit();
}
if(!checkboxdescriptionstring.isEmpty())
{
e.putString("checkboxdescr", checkboxdescriptionstring);
e.commit();
}
}
Create java class named SessionManger and put all your methods for setting and getting SharedPreferences values. When you want to save value use the object of this class and set and get the values.
Sample code given below.
public class SessionManager {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
int PRIVATE_MODE = 0;
public SessionManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences("name_that_you_use", PRIVATE_MODE);
editor = pref.edit();
editor.apply();
}
public void setIntroMessage(String data) {
editor.putString("intro", data);
editor.commit();
}
public String getIntroMessage() {
return pref.getString("intro", null);
}
}

Categories

Resources