Android Sharedpreferences doesn't work - java

I have problem with sharedpreferences, something goes wrong and I always get a default value.
My sharedpref class is:
public class IntolleranceData {
static SharedPreferences intolleranceData;
static SharedPreferences.Editor intolleranceEditor;
static final String FISH_KEY="00000";
}
I save value in Activity by:
intolleranceData = getApplicationContext().getSharedPreferences("intolleranceData", Context.MODE_PRIVATE);
intolleranceEditor = intolleranceData.edit();
intolleranceEditor.putString(FISH_KEY, "something").apply();
Toast.makeText(getApplicationContext(), "fish: " + intolleranceData.getString(FISH_KEY, "error"), Toast.LENGTH_LONG).show();
and this is great (toast shows correct string -"fish: something") but if I try to use sharedpreferences in fragment (in the same Activity and SharedPreferences, Activity and Fragment are in the same package) by:
intolleranceData = getActivity().getSharedPreferences("intolleranceData", Context.MODE_PRIVATE);
intolleranceEditor = intolleranceData.edit();
String myKey = intolleranceData.getString(FISH_KEY,"error");
Toast.makeText(getActivity(),"fish: "+myKey,Toast.LENGTH_LONG).show();
It shows "fish: 00000" so this is default value...
Is there any way to solve my problem?

Try checking to make sure that your GetActivity() isn't null before you reference it to return the SharedPreferences.
Also, you are using 'apply()' to add your changes to the SharedPreferences, which is a process which runs in the background. If you try and read from the data too early (e.g. simultaneously) then you can often get the default value. Alternatively, use .commit() to save your changes to the SharedPreferences.
Finally, if the problem is unrelated to either of these common issues, saving 'getActivity().getApplicationContext()' to a variable when the fragment is initialized, it should help with the problem of the context not linking correctly!
Best of Luck!

There is need to change your file like this, In the Place of
intolleranceData = getActivity().getSharedPreferences("intolleranceData", Context.MODE_PRIVATE);
intolleranceEditor = intolleranceData.edit();
String myKey = intolleranceData.getString(FISH_KEY,"error");
Toast.makeText(getActivity(),"fish: "+myKey,Toast.LENGTH_LONG).show();
You Must change Your code Like this, way,.... and also you just simply change your getActivity() with className.this
intolleranceData = MainActivity.this.getSharedPreferences("intolleranceData", Context.MODE_PRIVATE);
intolleranceEditor = intolleranceData.edit();
String myKey = intolleranceData.getString(FISH_KEY,"error");
introlleranceEditor.commit();
introllerenceEditor.apply();
Toast.makeText(getActivity(),"fish: "+myKey,Toast.LENGTH_LONG).show();

You don't need editor to read data.
When you send data use
intolleranceEditor.putString(FISH_KEY, "something");
intolleranceEditor.commit();

I got your Problem i will give you a Perfect answer for your problem simply check this code......
public class MainActivity extends AppCompatActivity {
static SharedPreferences intolleranceData;
static SharedPreferences.Editor intolleranceEditor;
static final String FISH_KEY="00000";
static final String File_Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intolleranceData = MainActivity.this.getSharedPreferences("File_Name", Context.MODE_PRIVATE);
String myKey = intolleranceData.getString(FISH_KEY,"");
Toast.makeText(getActivity(),"fish: "+myKey,Toast.LENGTH_LONG).show();
}
}
and in Shared Preferece or Inside button Click you can write this code
intolleranceData = MainActivity.this.getSharedPreferences("File_Name", Context.MODE_PRIVATE);
intolleranceEditor = intolleranceData.edit();
intolleranceEditor.putString(FISH_KEY, "something")
intolleranceEditor.commit();
intolleranceEditor.apply();
Toast.makeText(getApplicationContext(), "fish: " + intolleranceData.getString(FISH_KEY, "error"), Toast.LENGTH_LONG)..show();
If you Solve your problem give a simple response

I understand that you trying to use this code display a message in the Fragment kk, try this code.....
public class MainActivity extends AppCompatActivity {
static SharedPreferences intolleranceData;
static SharedPreferences.Editor intolleranceEditor;
static final String FISH_KEY="00000";
static final String File_Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intolleranceData = getActivity().getSharedPreferences("File_Name", Context.MODE_PRIVATE);
String myKey = intolleranceData.getString(FISH_KEY,"");
Toast.makeText(getActivity(),"fish: "+myKey,Toast.LENGTH_LONG).show();
}
}
and In Shared Prefereces
intolleranceData = getApplicationContext().getSharedPreferences("File_Name", Context.MODE_PRIVATE);
intolleranceEditor = intolleranceData.edit();
intolleranceEditor.putString(FISH_KEY, "something")
intolleranceEditor.commit();
intolleranceEditor.apply();
Toast.makeText(getApplicationContext(), "fish: " + intolleranceData.getString(FISH_KEY, "error"), Toast.LENGTH_LONG)..show();

You should commit after you add the string...
intolleranceEditor.putString(FISH_KEY, "something");
intolleranceEditor.commit();

Related

How to save textview when application is closed?

I'm trying to save textview from getIntent String. When I close the application, then open again, textview is null. I have used many methods like onSaveInstance, SharedPreference but all failed.
Code :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
jamShubuh = findViewById(R.id.jamShubuhTextView);
jamDzuhur = findViewById(R.id.jamDzuhurTextView);
jamAshar = findViewById(R.id.jamAsharTextView);
getShubuh = getIntent().getStringExtra("getShubuh");
getDzuhur = getIntent().getStringExtra("getDzuhur");
getAshar = getIntent().getStringExtra("getAshar");
jamShubuh.setText(getShubuh);
jamDzuhur.setText(getDzuhur);
jamAshar.setText(getAshar);
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("shubuh", getShubuh);
editor.putString("dzuhur", getDzuhur);
editor.putString("ashar", getAshar);
retriveData();
private void retriveData() {
SharedPreferences getData = getPreferences(Context.MODE_PRIVATE);
getData.getString("shubuh", null);
getData.getString("dzuhur", null);
getData.getString("ashar", null);
}
To use the shared preferences, I suggest you to make certain class to handle it. Maybe like this.
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
public class MyPrefManager {
SharedPreferences sp;
SharedPreferences.Editor editor;
public void setPref(Context context, String key, String value){
sp = PreferenceManager.getDefaultSharedPreferences(context);
editor = sp.edit();
editor.putString(key, value);
editor.commit();
}
public String getPref(Context context, String key){
sp = PreferenceManager.getDefaultSharedPreferences(context);
value = null;
String X = sp.getString(key, value);
return X;
}
}
Then use setPref method to set the value and getPref method to get the value. Assume now you are in MainActivity and you want to save values of getShubuh, getDzuhur, and getAshar to Preference Manager, you can do something like this :
MyPrefManager MPM = new MyPrefManager();
MPM.setPref(MainActivity.this,"keyShubuh",getShubuh);
MPM.setPref(MainActivity.this,"keyDzuhur",getDzuhur);
MPM.setPref(MainActivity.this,"keyAshar",getAshar);
And to get the value of keyShubuh, keyDzuhur, and keyAshar wherever you want, you can do something like this.
MyPrefManager MPM = new MyPrefManager();
MPM.getPref(AnyActivity.this,"keyShubuh");
MPM.getPref(AnyActivity.this,"keyDzuhur");
MPM.getPref(AnyActivity.this,"keyAshar");
Hope it can help.
To save text state
//Saving The Text Entered by User
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
editText = findViewById(R.id.editText);// getting the reference of editext from xml
CharSequence text = editText.getText();// getting text u entered in edittext
outState.putCharSequence("savedText", text);// saved that text in bundle object i.e. outState
}
and restore saved text
//Restoring the State
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
editText = findViewById(R.id.editText);// getting the reference of textview from xml
CharSequence savedText =
savedInstanceState.getCharSequence("savedText");// getting the text of editext
editText.setText(savedText);// set the text that is retrieved from bundle object
}
instead of EditText you can use TextView.

Generate random int and save it to SharedPreferences

I need to generate random int to give device id when my app run for the first time, then save it to SharedPreffs, show id on TextView, and when is turned on again show saved id from SharedPreffs on TextView.
public class MainActivity extends AppCompatActivity {
public static final String MyPREFERENCES = "MyPrefs";
public static final String KEY_DEVICE = "id";
SharedPreferences sharedpreferences;
String id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
deviceid = (TextView) findViewById(R.id.deviceid);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if (!sharedpreferences.contains(id)) {
SharedPreferences.Editor editor = sharedpreferences.edit();
id = String.valueOf(new Random().nextInt(900000) + 100000);
editor.putString(KEY_DEVICE, id);
editor.commit();
deviceid.setText(id);
}
deviceid.setText(id);
}
}
Above code generates random int and show it on TexView, but every time I hide or turn off the app, the device id changes
Could you explain me what i have to do to achive my goal.
There should be "id" or KEY_DEVICE
Replace
!sharedpreferences.contains(id)
to
!sharedpreferences.contains(KEY_DEVICE)
Also
deviceid.setText(id);
will show null in that case
So you have to add before setText
id = sharedpreferences.getString(KEY_DEVICE,"0");
Try this
String MyPREFERENCES = "MyPrefs";
String KEY_DEVICE = "device_id";
SharedPreferences sharedpreferences;
SharedPreferences.Editor editor;
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if (sharedpreferences.contains(KEY_DEVICE)) {
id = sharedpreferences.getString(KEY_DEVICE, "0");
deviceid.setText(id);
} else {
id = String.valueOf(new Random().nextInt(900000) + 100000);
editor = sharedpreferences.edit();
editor.putString(KEY_DEVICE, id);
editor.apply();
deviceid.setText(id);
}
This is because you are just checking if there is no shared preference value then select a random number and add it to device but you are not getting any value in the on create method i.e you are not getting any shared preference value that you stored before. Simply get your stored value and then check if the value is exist, if exists then set in textview otherwise call the condition check. Hope it Helps
Put a check for null before fetching the value from sharedPreferences.
If it is null : then save the id
else : fetch the older one only.
If this check : if(!sharedpreferences.contains(id)) is required then keep it nested under null check.

Permenantly storing a string, by a user?

On my main activity I'm looking into a variable, if the variable contains a string ("example string") then it will go to the home-screen. if the variable contains nothing ("") it will redirect them to a page where they can enter a value via an editText and then permanently store it. So the next time they open the app, it will have this permanent string (until the app is deleted) and therefore it will just go to the home-screen.
From research i understand that i may have to use Shared Preferences. I have tried this already and I think im not doing something right.
Please could someone illustrate with a code example of what needs to be done for the code i have posted.
MainActivity.class
//this class uses the string, to see if its blank or contains a string
public class MainActivity extends Activity {
public static final String Verified = ""; //Originally comes blank
private EditText NumberET; //editText for user to enter a string
//the string verified is used in the main activity to determine which xml file to open.
Verified.class
// this is the class used to enter the string and permanently store it
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.verified);
Button VerifyCompleteButton = (Button) findViewById(R.id.VerifyCompleteButton);
VerifyCompleteButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
String Verified;
String Number;
Bundle bundle = getIntent().getExtras();
Verified = bundle.getString("Verified");
NumberString = bundle.getString("NumberString")
Verified = NumberString.toString(); //set String Verified permenantly
}
});
You may use like this , Very much similar to above answer
For Saving String
SharedPreferences sharedPref = getSharedPreferences("App_Name_Prefs",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("Verified", Verified);
editor.commit();
For getting string
SharedPreferences shared = getSharedPreferences("App_Name_Prefs",
Context.MODE_PRIVATE);
String keyReturn = shared.getString(key, "");
Log.d("return value" , "Verified is " + verified);
Great example of using SharedPreference can be found on Google's Android developer website.
Saving data:
SharedPreferences sharedPref = context.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("KEY", "VALUE");
editor.commit();
Get data:
SharedPreferences sharedPref = context.getPreferences(Context.MODE_PRIVATE);
String savedValue = context.getString("KEY", "");
Things to look after:
Make sure your [key] is the same for saving and getting. The shared preferences is a basically a hashmap/dictionary.
When getting use the second parameter to set a default return value when setting isn't found or set yet.

Using SharedPreferences between Activity

I have a configuration page which has a form on it. When the button is pressed, I want to save that value to a SharedPreference. This SharedPreference value then needs to be accessed from elsewhere in my app.
I am trying to save the value like the below. I want to save the collectionID so I can use it elsewhere
public class ConfigPage extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
Button mButton;
EditText mEdit;
String collectionID;
String key = "GregKey";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.config);
getActionBar().hide();
mButton = (Button)findViewById(R.id.setCollection);
mEdit = (EditText)findViewById(R.id.collectionName);
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
collectionID = mEdit.getText().toString();
Log.d("EditText", collectionID);
SharedPreferences settings =
getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, collectionID);
editor.commit();
}
});
}
}
Once it has been saved, I then need to access it in another class, however I can't figure out how to do this. The example above crashes the application at the moment so something isn't quite right
I want to save the collectionID so I can use it elsewhere
Use mButton Button onClick event for saving EditText text in SharedPreferences as :
mButton.setOnClickListener( new View.OnClickListener()
{
public void onClick(View view)
{
collectionID = mEdit.getText().toString();
Log.d("EditText", collectionID);
// save value here in SharedPreferences
SharedPreferences settings =
ConfigPage.this.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(collectionID, collectionID);
editor.commit();
}
});
Your crash occurs because your value is null:
String savedID;
You need to add a value to the variable:
String savedID = "somevalue";
Also, your key is null as long as the Button is not pressed which will also lead to a crash.
The putString(String key, String value) method enables you to store a specific value with a specific key, that can later be used to reaccess the stored value.
Example:
String key = "somekey";
String value = "yourvaluetostore";
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, value); // store the value
editor.commit();
In another Activity:
String key = "somekey";
SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, 0);
// get the value "" is default
String value = sharedPreferences.getString(key, "");
All you need in the other Activity is the key you stored the value with. With this key, you can pull the correct stored value out of the SharedPreferences. --> The key is needed to identify the value.
Since you are using the part of code :
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(collectionID, savedID);
editor.commit();
Log.d("Saved as", savedID);
in the onCreate method, that translates to
...
editor.putString(null, null);
Log.d("Saved as", null);
Correct your code so that you fill those elements before. I guess you wanted to make the save in the OnClick part
Yes something its not quite right here because as i see you are saving nothing. on shared pref you should have a "key" which will be use to identify the saved value in your example it should be something like this
public class ConfigPage extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
public static final String COLLECTIONID_KEY = "COLLECTIONID_KEY";
Button mButton;
EditText mEdit;
String collectionID;
String savedID;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.config);
getActionBar().hide();
mButton = (Button)findViewById(R.id.setCollection);
mEdit = (EditText)findViewById(R.id.collectionName);
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
collectionID = mEdit.getText().toString();
Log.d("EditText", collectionID);
}
});
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(COLLECTIONID_KEY, collectionID);
editor.commit();
Log.d("Saved as", COLLECTIONID_KEY);
}
}
then to retrieve it :
SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, 0);
String mySavedCollectionID = sharedPreferences.getString(COLLECTIONID_KEY);
and make sure that its done on the Onclick event otherwise you might end up with crash again because after the on-click event in your code the lines below will run anyway and save null!

How to access a string value of a shared preference from a method of another class

The title is the question. I have saved a string value in the shared preference and i was able to access it in that class. Now i want to access it from a another method of another class. Tried some ways but didn't work.
The class that saves string inside shared preference:
http://pastie.org/4254511
Class trying to retrieve the username that was previously save in shared preference:
public class testSharedPrefernce extends Activity{
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.lo);
tv = (TextView)findViewById(R.id.textView1);
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
String name = myPrefs.getString("NAME", "YourName");
tv.setText(name);
}
}
Just make a constructor of that class which accepts the context.As example:
class Abc
{
Context contaxt;
public Abc(Context context)
{
this.context = context;
}
}
..........
..........
// now use this context to SharedPref..
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
Use below code for get preferences.
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
boolean cbvalue = myPrefs.getBoolean("CHECKBOX", false);
String name = myPrefs.getString("NAME", "YourName");
String paswrd =myPrefs.getString("PASSWORD", "123");
Use below code for save preferences.
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("NAME", "Dipak");
prefsEditor.putString("PASSWORD", "Dipak123");
prefsEditor.commit();

Categories

Resources