How i will get multiple data from shared preference? - android

I have saved multiple data using shared preference. I want to read multiple data from shared preference. I have tried but can not success. I can read one data but unable to read multiple data.Thanks.
//Save multiple data
private static int incrementedValue = 0;
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences faves = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String id = idEditText.getText().toString();
String name = nameEditText.getText().toString();
SharedPreferences.Editor editor = faves.edit();
editor.putString("favourite" + incrementedValue, id + "::" + name + ",");
editor.commit();
Toast toast = Toast.makeText(MainActivity.this, "saved!", Toast.LENGTH_SHORT);
toast.show();
incrementedValue++;
}
})
Here is read data from shared preference code.
//Show multiple data
showBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences faves = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String id = faves.getString("favourite", "");
String name = faves.getString("favourite","");
textShow.setText(id+" "+name);
Toast.makeText(MainActivity.this,"Show!",Toast.LENGTH_LONG).show();
}
});

You have made the key as "favourite" + incrementedValue and accessing the value with the key "favourite" which are not the same, and it looks like you have saved both the values id and name in a single String which is again inappropriate, so change your code like this,
SharedPreferences.Editor editor = faves.edit();
editor.putString("favourite id" + incrementedValue, id);
editor.putString("favourite name" + incrementedValue, name);
editor.commit();
and access data like this,
SharedPreferences faves = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String id = faves.getString("favourite id"+INCREMENT_VALUE_COUNT, "");
String name = faves.getString("favourite name"+INCREMENT_VALUE_COUNT,"");
You have to replace INCREMENT_VALUE_COUNT with the position number you want to get data of.

You can add multiple data in SharedPreferences
SharedPreferences.Editor editor = faves.edit();
editor.putString("id", id);
editor.putString("name", name);
editor.commit()
You could get the value by
String id = (faves.getString("id", "0"));
String name = (faves.getString("name", ""));
As Here you are adding value separated by :: and ,.
You should get
String favourite = faves.getString("favourite", "");
And split favourite by , and get separated values and after that split by ::

Related

shared preferences First Time Empty When i restart the app with out logout Code works Fine

Problem is i have stored Facebook username email id and profile picture and retrieving data in next activity but the problem is when i log in the data is null when i restart the App code working fine.
Storing Data
String email = object.getString("email");
String id = object.getString("id");`
sessionManager.setfacebookid(object.getString("email").toString());
String imageurl = "https://graph.facebook.com/" + id + "/picture?type=large";
sessionManager.setfacebookimage("https://graph.facebook.com/" + id + "/picture?type=large".toString());
Retrieving Data
sessionManager.isUserLogin();
navHeader = navigationView.getHeaderView(0);
String facebookname = sessionManager.getfacebookname();
tvvwelcome2 = (TextView) navHeader.findViewById(R.id.tvwelcome2);
tvvwelcome2.setText(facebookname);
Log.e("facebooknamein text....", "" + facebookname);
String facebookid = sessionManager.getfacebookid();
tvemail2 = (TextView) navHeader.findViewById(R.id.headeremail2);
tvemail2.setText(facebookid);
Log.e("emailfbinnavigation", "" + facebookid);
String facedp = sessionManager.getfacebookdp();
imgbtn2 = (ImageView) navHeader.findViewById(R.id.profileheader2);
Picasso.with(this).load(facedp).into(imgbtn2);
Log.e("imageview in image", "" + facedp);
Thanks In Advance
Try using SharedPreferences like below mentioned,
To save data:
SharedPreferences prefs = getSharedPreferences("my_prefs", MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putString("name", "Sahil");
editor.commit();
To retrieve data:
SharedPreferences prefs = getSharedPreferences("my_prefs", MODE_PRIVATE);
String name= prefs.getString("name");

Retrieving SharedPreferences Values not working. Any ideas what I'm doing wrong?

Here's where I store values into SharedPreferences in one activity:
sharedPref = context.getSharedPreferences("sharedPref", Context.MODE_PRIVATE);
String firstPlace = new String("1");
String secondPlace = new String("2");
String thirdPlace = new String("3");
editor = sharedPref.edit();
editor.putString("first", firstPlace);
editor.putString("second", secondPlace);
editor.putString("third", thirdPlace);
editor.commit();
And try to retrieve them in another activity. However, the retrieve doesn't seem to be getting the values I put in and is just using the defaults (so "1st Place: " "2nd Place: " and "3rd Place: " end up with a 'no' next to them).
SharedPreferences sharedPref = getSharedPreferences("sharedPref", MODE_PRIVATE);
String firstPlace = sharedPref.getString("first", "no");
String secondPlace = sharedPref.getString("second", "no");
String thirdlace = sharedPref.getString("third", "no");
highScore1.setText("1st Place: " + firstPlace);
highScore2.setText("2nd Place: " + secondPlace);
highScore3.setText("3rd Place: " + thirdlace);
You can try to direct put value
editor = sharedPref.edit();
editor.putString("first", "1");
editor.putString("second", "2");
editor.putString("third", "3");
You have used separate contexts. To make your sharedpreference accesible to entire application you need default sharedpreference. Declare it as below
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
After this you can edit and fetch data as you did before.
please try this,
this.SharedPrefs = getSharedPreferences("MyPrefs", 0);
SharedPreferences.Editor localEditor = this.SharedPrefs.edit();
localEditor.putString("first", firstPlace);
localEditor.putString("second", secondPlace);
localEditor.putString("third", thirdPlace);
localEditor.commit();
finish();

how can i send information from one activity, receive it in a second activity and sent it to the the main activity?

i would like to send information from one page and receive it in a edit page, and after receiving it i want to save it and send it to the main activity (in android).
how can i do it?
this is the code from the first page:
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
int position1 = position;
// i am getting the title of the movie that was pressed
String search_title = list.get(position).getTitle().toString();
String search_url = list.get(position).getPhoto_url();
String search_description = list.get(position).getDescription();
Intent intent = new Intent(Search_A_Movie.this,Edit_A_Movie.class);
// i am sending the info of the movie to the edit_a_movie page
intent.putExtra("item_title", search_title);
intent.putExtra("item_url", search_url);
intent.putExtra("item_description", search_description);
startActivity(intent);
}
});
Use SharedPreference. Save in A1 and retrieve in A2 and vice-versa.
Initialization
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
Storing Data
editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "string value"); // Storing string
editor.putInt("key_name", "int value"); // Storing integer
editor.putFloat("key_name", "float value"); // Storing float
editor.putLong("key_name", "long value"); // Storing long
editor.commit(); // commit changes
Retrieving Data
// returns stored preference value
// If value is not present return second param value - In this case null
pref.getString("key_name", null); // getting String
pref.getInt("key_name", null); // getting Integer
pref.getFloat("key_name", null); // getting Float
pref.getLong("key_name", null); // getting Long
pref.getBoolean("key_name", null); // getting boolean
Deleting Data
editor.remove("name"); // will delete key name
editor.remove("email"); // will delete key email
editor.commit(); // commit changes
Clearing Storage
editor.clear();
editor.commit(); // commit changes
You just send the data from one activity
sending like this...
Intent intent = new Intent(Search_A_Movie.this,Edit_A_Movie.class);
// i am sending the info of the movie to the edit_a_movie page
intent.putExtra("item_title", search_title);
intent.putExtra("item_url", search_url);
intent.putExtra("item_description", search_description);
startActivity(intent);
get the values in the second activity like this.....
Intent intent = getIntent();
String name1 = intent.getStringExtra(SENTNAME1);
String name2 = intent.getStringExtra(SENTNAME2);//replace the above sent name what you have given in the first activity....
String name3 = intent.getStringExtra(SENTNAME3);
try this:
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("PASSWORD_KEY", mPassword);
editor.commit();
To get the saved string value from another activity
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
String s = sharedPreferences.getString("PASSWORD_KEY", "");
in the second activity
Bundle d = getIntent().getExtras();
String item_title = d.getString("item_title");
String item_url = d.getString("item_url");
String item_description = d.getString("item_description");

How to save value in SharedPeference in the actitvity and access it all other classes

I want to save totalBalance in this activity to SharedPreferances and the retrive it in another class.
so i want totalbalance to be displayed in another activities in same application...
if possible also edit it in other activites...
please help... thanks
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do something in response to button click
// Genrating random number Random number
Random rn = new Random();
randomNumber = (int) rn.nextInt(9) + 1;
// changes textView1 equals to random number
textView1.setText("Random Number is "
+ Integer.toString(randomNumber));
button1.setText("Play Again");
// Matching random number to ArrayList
if (positive_IDs.contains(randomNumber)) {
// if matched then changes textView2 to Matched Number
textView2.setText("Number: "
+ Integer.toString(randomNumber) + " Matched");
totalBalance = totalBalance + winingPrize;
textView5.setText("Total Balance = Rs: "
+ String.format("%.2f", totalBalance));
}
}
try this,
public void saveValue(String lock, Context context) {
Editor editor = context
.getSharedPreferences(KEY, Activity.MODE_PRIVATE).edit();
editor.putString("Value", lock);
editor.commit();
}
public String getValue(Context context) {
SharedPreferences savedvalue = context.getSharedPreferences(KEY,
Activity.MODE_PRIVATE);
return savedvalue.getString("Value", "");
}
Save Value as Following
int Value;
private void saveValues(){
SharedPreferences readSP = getSharedPreferences("String", MODE_PRIVATE);
SharedPreferences.Editor editor = readSP.edit();
editor.putString("String", Value);
editor.commit();
}
Retrive value in any of your Class As following
int value;
private void getSavedValue()
{
SharedPreferences settings = getSharedPreferences("String", MODE_PRIVATE);
value=settings.getString("String", "");
}
// try this
SharedPreferences sharedPreferences = getSharedPreferences("yourSharePreferenceName", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("balance", String.format("%.2f", totalBalance));
editor.commit();
SharedPreferences sharedPreferences = getSharedPreferences("yourSharePreferenceName", MODE_PRIVATE);
String total = sharedPreferences.getString("balance");
Use following code to retrive your value from SharedPreference,write this in other class where you want to retrive value of total balance
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(YourActivityName.this);
Editor edit1 = remembermepref.edit();
edit1.putInt("totalbalance_key",totalBalance);
edit1.commit();
and to store total balance into ShardPreference use in your activity:
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(YourActivityName.this);
int totalbalance = pref.getInt("totalbalance_key");
Now use totalbalance way you want.
Most important thing is to check whether you have used same key to restore as well as tostore the value in SharedPreference
Hope this helps..

Check if key exists in Shared Preferences

I'm creating Shared Preferences as follows
preferences = getSharedPreferences("text", 0);
final Editor editor = preferences.edit();
String s1 = serverIP.getText().toString();
String s2 = serverPort.getText().toString();
String s3 = syncPass.getText().toString();
String s4 = proxyServer.getText().toString();
String s5 = proxyPort.getText().toString();
editor.putString("SERVERIP", s1);
editor.putString("SERVERPORT", s2);
editor.putString("SYNCPASS", s3);
editor.putString("PROXYSERVER", s3);
editor.putString("PROXYPORT", s3);
and onCreate I want to display the values in a new set of TextViews, but the first time I don't have any values stored in the shared preferences and will get a NULL Pointer exception.
I want to know if there is any built-in method which can check if the SharedPreferences contains any value or not, so that I can check if the key exists and if not, then replace the new set of TextViews with the preferences value.
Try contains(String key) Accorting to the Javadocs,
Checks whether the preferences contains a preference. Returns true if
the preference exists in the preferences, otherwise false.
Every method for fetching values from SharedPreferences has default value which is returned in case the key does not exist
preferences = getSharedPreferences("text", 0);
String value = preferences.getString("unknown_key",null);
if (value == null) {
// the key does not exist
} else {
// handle the value
}
Try out
SharedPreferences shf = getSharedPreferences("NAME_SharedPref", MODE_WORLD_READABLE);
String strPref = shf.getString("SERVERIP", null);
if(strPref != null) {
// do some thing
}
I know this is a late answer but for those who want to know if a shared preference is either empty or zero size, you can check it two ways.
preferences = getSharedPreferences("text", 0);
Map<String, ?> entries = preferences.getAll();//get all entries from shared preference
Set<String> keys = entries.keySet();//set all key entries into an array of string type
//first option
if(keys.isEmpty()){
//do your staff here
}
//second option
if(keys.size()==0){
//this shows that it is empty as well
//do your staff here
}
//Below is extra
//If you want to get the names of each keys also, you can use
//For each loop as well
//Go through the set of keys
for (String key : keys) {
String keyName = key;//get each key name
}
LoadRuns();
if (loadedruns == 1) {
Toast.makeText(MainActivity.this, "First run", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(MainActivity.this, "No. runs: " + loadedruns,
Toast.LENGTH_SHORT).show();
}
loadedruns++;
SaveRuns("runs", loadedruns);
public void SaveRuns(String key, int value){
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.commit();
}
public void LoadRuns(){
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
loadedruns = sharedPreferences.getInt("runs", 1);
}

Categories

Resources