Retrieving shared prefrences values in another activity - android

Can anyone tell where i am wrong because its just a simple process but how its not retrieving the values i cant understand and do conditional check over the string variable...
Activity A:-
EditText e = (EditText) findViewById(R.id.editText1);
EditText e1 = (EditText) findViewById(R.id.editText2);
EditText e2 = (EditText) findViewById(R.id.editText3);
EditText e3 = (EditText) findViewById(R.id.editText4);
EditText e4 = (EditText) findViewById(R.id.editText5);
EditText e5 = (EditText) findViewById(R.id.editText6);
EditText e6 = (EditText) findViewById(R.id.editText7);
SharedPreferences myPrefs = getSharedPreferences("myPrefs", Context.MODE_WORLD_READABLE);
SharedPreferences.Editor editor = myPrefs.edit();
editor.putString("text", e.getText().toString());
SharedPreferences myPrefs1 = getSharedPreferences("myPrefs1", Context.MODE_WORLD_READABLE);
SharedPreferences.Editor editor1 = myPrefs1.edit();
editor1.putString("text1", e1.getText().toString());
SharedPreferences myPrefs2 = getSharedPreferences("myPrefs2", Context.MODE_WORLD_READABLE);
SharedPreferences.Editor editor2 = myPrefs.edit();
editor2.putString("text2", e2.getText().toString());
SharedPreferences myPrefs3 = getSharedPreferences("myPrefs3", Context.MODE_WORLD_READABLE);
SharedPreferences.Editor editor3 = myPrefs3.edit();
editor3.putString("text3", e3.getText().toString());
SharedPreferences myPrefs4 = getSharedPreferences("myPrefs4", Context.MODE_WORLD_READABLE);
SharedPreferences.Editor editor4 = myPrefs4.edit();
editor4.putString("text4", e4.getText().toString());
SharedPreferences myPrefs5 = getSharedPreferences("myPrefs5", Context.MODE_WORLD_READABLE);
SharedPreferences.Editor editor5 = myPrefs5.edit();
editor5.putString("text5", e5.getText().toString());
SharedPreferences myPrefs6 = getSharedPreferences("myPrefs6", Context.MODE_WORLD_READABLE);
SharedPreferences.Editor editor6 = myPrefs6.edit();
editor6.putString("text6", e6.getText().toString());
Activity B:-In this activity i am accessing the values and doing the conditional check but only else condition is getting executed on both cases
public class CheckActivity extends Activity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences myPrefs = getSharedPreferences("myPrefs",Context.MODE_PRIVATE);
String restoredText = myPrefs.getString("text", "");
SharedPreferences myPrefs1 = getSharedPreferences("myPrefs1",Context.MODE_PRIVATE);
String restoredText1 = myPrefs1.getString("text1", "");
SharedPreferences myPrefs2 = getSharedPreferences("myPrefs2",Context.MODE_PRIVATE);
String restoredText2 =myPrefs2.getString("text2", "");
SharedPreferences myPrefs3 = getSharedPreferences("myPrefs3",Context.MODE_PRIVATE);
String restoredText3 =myPrefs3.getString("text3", "");
SharedPreferences myPrefs4 = getSharedPreferences("myPrefs4",Context.MODE_PRIVATE);
String restoredText4 = myPrefs4.getString("text4", "");
SharedPreferences myPrefs5 = getSharedPreferences("myPrefs5",Context.MODE_PRIVATE);
String restoredText5 = myPrefs5.getString("text5", "");
SharedPreferences myPrefs6 = getSharedPreferences("myPrefs6",Context.MODE_PRIVATE);
String restoredText6 = myPrefs6.getString("text6", "");
Intent i1 = new Intent();
if((restoredText.length()>1)&&(restoredText1.length()>1)&&(restoredText2.length()>1)&&(restoredText3.length()>1)&&(restoredText4.length()>1)&&(restoredText5.length()>1)&&(restoredText6.length()>1))
{
i1.setClass(this,ShpoonkleActivity.class);
}
//if((restoredText.length()==0)||(restoredText1.length()==0)||(restoredText2.length()==0)||(restoredText3.length()==0)||(restoredText4.length()==0)||(restoredText5.length()==0)||(restoredText6.length()==0))
else
{
i1.setClass(this,Test.class);
}
startActivity(i1);
finish();
}
}

you should commit your data with editor.commit();
NB: in your case , there is no need to use a lot of instances of SharedPreferences , you need just one instance, and then put all your Strings into it , and commit

you should use
editor.commit();
for your changes to be preserved. and also, you need not use different files to store various strings, you can store all the strings in the same shared preferences file.

actually saving edittext's text was creating ambiguity and hence was not executing well so i did this as shown below:-
Activity B:-
protected void onPause() {
EditText ed = (EditText)findViewById(R.id.editText1);
EditText ed1 = (EditText)findViewById(R.id.editText2);
EditText ed2 = (EditText)findViewById(R.id.editText3);
EditText ed3 = (EditText)findViewById(R.id.editText4);
EditText ed4 = (EditText)findViewById(R.id.editText5);
EditText ed5 = (EditText)findViewById(R.id.editText6);
EditText ed6 = (EditText)findViewById(R.id.editText7);
super.onPause();
SharedPreferences myPrefs = getSharedPreferences("myPrefs", Context.MODE_WORLD_READABLE);
SharedPreferences.Editor editor = myPrefs.edit();
editor.putString("text", ed.getText().toString());
editor.putString("text1", ed1.getText().toString());
editor.putString("text2", ed2.getText().toString());
editor.putString("text3", ed3.getText().toString());
editor.putString("text4", ed4.getText().toString());
editor.putString("text5", ed5.getText().toString());
editor.putString("text6", ed6.getText().toString());
editor.commit();
}
Activity A:-
public class CheckActivity extends Activity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences myPrefs = getSharedPreferences("myPrefs",Context.MODE_PRIVATE);
String restoredText = myPrefs.getString("text", "");
String restoredText1 = myPrefs.getString("text1", "");
String restoredText2 =myPrefs.getString("text2", "");
String restoredText3 =myPrefs.getString("text3", "");
String restoredText4 = myPrefs.getString("text4", "");
String restoredText5 = myPrefs.getString("text5", "");
String restoredText6 = myPrefs.getString("text6", "");
Intent i1 = new Intent();
if((restoredText.length()>0)&&(restoredText1.length()>0)&&(restoredText2.length()>0)&&(restoredText3.length()>0)&&(restoredText4.length()>0)&&(restoredText5.length()>0)&&(restoredText6.length()>0))
{
i1.setClass(this,ShpoonkleActivity.class);
}
//if((restoredText.length()==0)||(restoredText1.length()==0)||(restoredText2.length()==0)||(restoredText3.length()==0)||(restoredText4.length()==0)||(restoredText5.length()==0)||(restoredText6.length()==0))
else
{
i1.setClass(this,Test.class);
}
startActivity(i1);
finish();
}
}
And it works awesome ...thnx..

Related

Save user input to SharedPrefernces and set Value to EdiText

I want to save user input to SharedPreferences when i click a button so that when a user launches the activity again the user input is set to the EditText and TextView. I already have a sharedPreferences File created that i save some text to in a previous activity.
I want update the SharedPreferences File with another details from this new activity that i created.
This is code for creating and saving to SharedPreferences
private SharedPreferences prefs;
public static final String PREF_FILE_NAME = "AuthUser";
prefs = this.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
txtDate = (TextView) findViewById(R.id.txtDate);
addIdButton = (Button) findViewById(R.id.btnAddId);
addIdButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
expiryDate = txtDate.getText().toString();
edtIdNumber = (EditText) findViewById(R.id.edtIdNumber);
idNumber = edtIdNumber.getText().toString();
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("idType", idType);
editor.putString("idNumber", idNumber);
editor.putString("expiryDate", expiryDate);
editor.apply();
}
});
This is my code to set the value from shared preferences to EditText and TextView
#Override
public void onStart(){
super.onStart();
File f = new File(PREF_FILE_NAME);
if (f.exists()){
idType = prefs.getInt("idType", 0);
idNumber = prefs.getString("idNumber", "");
expiryDate = prefs.getString("expiryDate", "");
edtIdNumber = (EditText) findViewById(R.id.edtIdNumber);
txtDate = (TextView) findViewById(R.id.txtDate);
txtDate.setText(expiryDate);
edtIdNumber.setText(idNumber);
edtIdNumber.setText(idNumber);
txtDate.setText(expiryDate);
}
}
File f = new File(PREF_FILE_NAME); just has the name of the preference so
f.exists() will always returns false
Solution : Remove
File f = new File(PREF_FILE_NAME);
if (f.exists()){
because if you don't have any value then simply use the default value
#Override
public void onStart(){
super.onStart();
//File f = new File(PREF_FILE_NAME); // not a right path
//if (f.exists()){ // false
idType = prefs.getInt("idType", 0);
idNumber = prefs.getString("idNumber", "");
expiryDate = prefs.getString("expiryDate", "");
edtIdNumber = (EditText) findViewById(R.id.edtIdNumber);
txtDate = (TextView) findViewById(R.id.txtDate);
txtDate.setText(expiryDate);
edtIdNumber.setText(idNumber);
edtIdNumber.setText(idNumber);
txtDate.setText(expiryDate);
//}
}
Alternatively you can use contains
To Achive your work:
First of all try to understand difference between onCreate() and onStart() method of Activity in android, follow following url: https://developer.android.com/guide/components/activities/activity-lifecycle.html
-: use onCreate() method instead of onStart() for setting ui variables;
secondly change in your code like:
public void onClick(View view) {
expiryDate = txtDate.getText().toString();
edtIdNumber = (EditText) findViewById(R.id.edtIdNumber);
idNumber = edtIdNumber.getText().toString();
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("idType", idType);
editor.putString("idNumber", idNumber);
editor.putString("expiryDate", expiryDate);
editor.commit();
}
just remove if (f.exists()) condition from Onstart() because File f = new File(PREF_FILE_NAME); just has the name of the preference so f.exists() will always returns false
like below code
#Override
public void onStart(){
super.onStart();
/* File f = new File(PREF_FILE_NAME);
if (f.exists()){*/
idType = prefs.getInt("idType", 0);
idNumber = prefs.getString("idNumber", "");
expiryDate = prefs.getString("expiryDate", "");
edtIdNumber = (EditText) findViewById(R.id.edtIdNumber);
txtDate = (TextView) findViewById(R.id.txtDate);
txtDate.setText(expiryDate);
edtIdNumber.setText(idNumber);
txtDate.setText(expiryDate);
}

How to change value of a string?

String stored contains "1.0" in it. and I want to increase its value by 0.5, every time I press the button. But instead, my output becomes "1.00.5". How do I fix this?
String stored = userspeed.getText().toString();
String speedplus = stored + 0.5;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("user_speed", speedplus.toString());
editor.apply();
UPDATE
public class ProgramActivity extends AppCompatActivity {
EditText userspeed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_program);
userspeed = (EditText) findViewById(R.id.userspeed);
//load values
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
String stored = preferences.getString("user_speed", "1.0");//default
userspeed.setText(stored, TextView.BufferType.EDITABLE);
}
public void adduserspeed(View view) {
String stored = userspeed.getText().toString();
double storedValue = Double.parseDouble(stored);
String speedplus = String.valueOf(storedValue +0.5f);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("user_speed", speedplus);
editor.apply();
}
}
First, you need to convert your string value to a float value, then perfom the add operation and finally convert the result to a string so you can store as a string in shared preferences.
final String stored = userspeed.getText().toString();
final float storedValue = Float.parseFloat(stored);
final String speedplus = String.valueOf(storedValue + 0.5f);
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor editor = preferences.edit();
editor.putString("user_speed", speedplus);
editor.apply();
If you want to use a double value, simply replace first lines as the follows:
final String stored = "1.0";
final double storedValue = Double.parseDouble(stored);
final String speedplus = String.valueOf(storedValue + 0.5d);
UPDATE
Your problem is that within adduserspeed(View view) method your are not retrieving the stored value from preferences, your are retrieving from the EditText, and you are not updating that EditText value, so every time you execute adduserspeed(View view) method, the value you are storing on preferences is 1.0 + 0.5, because you EditText value is 1.0 until you re-open your app. When you re-open your app your EditText value is 1.5 and so on...
I have improved your code and now works well, anyway, do not just copy my code, try to understand it so you can learn.
public class MainActivity extends AppCompatActivity {
private EditText userSpeed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.userSpeed = (EditText) findViewById(R.id.userspeed);
setUserSpeedText();
}
public void adduserspeed(View view) {
final String stored = getUserSpeedValue();
final double storedValue = Double.parseDouble(stored);
final String speedPlus = String.valueOf(storedValue + 0.5f);
setUserSpeedValue(speedPlus);
setUserSpeedText();
}
private String getUserSpeedValue() {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
return preferences.getString("user_speed", "1.0");
}
private void setUserSpeedValue(final String newSpeedValue) {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor editor = preferences.edit();
editor.putString("user_speed", newSpeedValue);
editor.apply();
}
private void setUserSpeedText() {
if (null != this.userSpeed) {
this.userSpeed.setText(getUserSpeedValue());
}
}
}
You can also use double like:
String speedplus = (Double.parseDouble(stored)+0.5).toString();
Try parsing stored i.e. 1.0 as Double and then add 0.5d
String speedplus = String.valueOf((Double.parseDouble(stored) + 0.5d));
Final code
String stored = userspeed.getText().toString();
String speedplus = String.valueOf((Double.parseDouble(stored) + 0.5d));
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("user_speed", speedplus.toString());
editor.apply();
String stored = userspeed.getText().toString();
float speedplus = Float.parseFloat(stored) + 0.5;
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putFloat("user_speed", speedplus);
editor.apply();
Parse the string value to int and then do mathematical operation. Otherwise string concatenation will happen.
The quickest hack would be:
String speedplus = String.valueOf(Float.parseFloat(stored) + 0.5F);
However, your next question will no doubt be "Why is my result 1.499999999?", which is answered here in detail.

Android: How to store array of strings in SharedPreferences for android

I'm building an app which searches the web using search engine. I have one edittext in my app from which user will search the web. I want to save the search keywords just like browser history does. I'm able to save and display it with the last keyword but I can't increase the number of searches result. I want to display the last 5 searhes. Here is my code :
public class MainActivity extends Activity implements OnClickListener {
Button insert;
EditText edt;
TextView txt1, txt2, txt3, txt4, txt5;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edt = (EditText) findViewById(R.id.search_word);
txt1 = (TextView) findViewById(R.id.txt1);
txt1.setOnClickListener(this);
insert = (Button) findViewById(R.id.insert);
insert.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if ((edt.getText().toString().equals(""))) {
Toast.makeText(
getBaseContext(),
"Whoa! You haven't entered anything in the search box.",
Toast.LENGTH_SHORT).show();
} else {
SharedPreferences app_preferences = PreferenceManager
.getDefaultSharedPreferences(MainActivity.this);
SharedPreferences.Editor editor = app_preferences.edit();
String text = edt.getText().toString();
editor.putString("key", text);
editor.commit();
Toast.makeText(getBaseContext(), text, Toast.LENGTH_LONG)
.show();
}
}
});
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
SharedPreferences app_preferences = PreferenceManager
.getDefaultSharedPreferences(this);
String text = app_preferences.getString("key", "null");
txt1.setText(text);
}
public void onClick(View v) {
String text = txt1.getText().toString();
Toast.makeText(getBaseContext(), text, Toast.LENGTH_SHORT).show();
}
}
Please help me in overcoming this problem.
SAVE ARRAY
public boolean saveArray(String[] array, String arrayName, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(arrayName +"_size", array.length);
for(int i=0;i<array.length;i++)
editor.putString(arrayName + "_" + i, array[i]);
return editor.commit();
}
LOAD ARRAY
public String[] loadArray(String arrayName, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
int size = prefs.getInt(arrayName + "_size", 0);
String array[] = new String[size];
for(int i=0;i<size;i++)
array[i] = prefs.getString(arrayName + "_" + i, null);
return array;
}
Convert your array or object to Json with Gson library and store your data as String in json format.
Save;
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Editor editor = sharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(arrayList);
editor.putString(TAG, json);
editor.commit();
Read;
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Gson gson = new Gson();
String json = sharedPrefs.getString(TAG, null);
Type type = new TypeToken<ArrayList<ArrayObject>>() {}.getType();
ArrayList<ArrayObject> arrayList = gson.fromJson(json, type);
Original answer: Storing Array List Object in SharedPreferences

Shared Preference Android Storing data

I am having trouble storing data using shared preference.
If I have the following code and try to run it, it crashes. I don't know why though.
public class Favorites extends Activity{
private static final String TAG_NAME = "title";
private static final String TAG_URL = "href";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favorites);
Intent in = getIntent();
TextView favName = (TextView) findViewById(R.id.textView1);
String FILENAME = "settings";
String string = "hello world!";
SharedPreferences pref = getSharedPreferences("Preference",
MODE_WORLD_READABLE);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("keyBoolean", true);
editor.putFloat("keyFloat", 1.0f);
editor.putInt("keyInt", 1);
editor.putLong("keyLong", 1000000L);
editor.putString("keyString", "Hello Android");
editor.commit();
boolean dataFromPrefBool = pref.getBoolean("keyBoolean", false);
float dataFromPrefflaot = pref.getFloat("keyFloat", 0.0f);
int dataFromPrefInt = pref.getInt("keyInt", 0);
long dataFromPrefLong = pref.getLong("keyLong", 0);
String dataFromPrefString = pref.getString("keyString", null);
favName.setText(dataFromPrefInt);
}
Why is nothing happening? These are just dummy values but still nothing happens
change
SharedPreferences pref = getSharedPreferences("Preference",
MODE_WORLD_READABLE);
to
SharedPreferences pref = getSharedPreferences("Preference",
MODE_WORLD_WRITABLE);
Try this, maybe it is due to null pointer exception.I am not sure.
public class Favorites extends Activity{
private static final String TAG_NAME = "title";
private static final String TAG_URL = "href";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favorites);
Intent in = getIntent();
TextView favName = (TextView) findViewById(R.id.textView1);
String FILENAME = "settings";
String string = "hello world!";
SharedPreferences pref = getSharedPreferences("Preference",
MODE_WORLD_READABLE);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("keyBoolean", true);
editor.putFloat("keyFloat", 1.0f);
editor.putInt("keyInt", 1);
editor.putLong("keyLong", 1000000L);
editor.putString("keyString", "Hello Android");
editor.commit();
boolean dataFromPrefBool = pref.getBoolean("keyBoolean", null);
float dataFromPrefflaot = pref.getFloat("keyFloat", null);
int dataFromPrefInt = pref.getInt("keyInt", null);
long dataFromPrefLong = pref.getLong("keyLong", null);
String dataFromPrefString = pref.getString("keyString", null);
if(dataFromPrefInt==null)
{
favName.setText("");
}
else
{
favName.setText(dataFromPrefInt);
}
}
}

Show the highscore with shared preferences?

So I'm trying to save the highest score with sharedPreferences but I am running into trouble. I don't know how I would set it up to only take the highest score and display it.
What I have now will only display the current score that the player recieves. Here is what I have so far that doesnt work:
public class GameOptions extends Activity {
int theScore;
TextView highScore;
public static String filename = "MyHighScore";
SharedPreferences spHighScore;
int dataReturned;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.in_game_menu);
TextView tvTheScore = (TextView) findViewById(R.id.textView2);
TextView highScore = (TextView) findViewById(R.id.high_score);
Bundle gotScore = getIntent().getExtras();
theScore = gotScore.getInt("scoreKey");
//String thisIsTheScoreToDisplay = theScore.toString();
tvTheScore.setText("SCORE: "+theScore);
spHighScore = getSharedPreferences(filename, 0);
SharedPreferences.Editor editor = spHighScore.edit();
editor.putInt("highScoreKey", theScore);
editor.commit();
int dataReturned = spHighScore.getInt("highScoreKey", 0);
highScore.setText("" + dataReturned);
by this you can save your score
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString(MY_SCORE_KEY, HIGHEST_SCORE);
prefsEditor.commit();
and get like this
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
String highestScore = myPrefs.getString(MY_SCORE_KEY, "nothing");
I hope this will help you..
Just before Saving the high score, Fetch the current high score which is saved in the preferences and check whether it is less than the highscore or not. if it is less then save the new one in to Shared preferences or else just leave the past one as highest.

Categories

Resources