Why My SharedPreference create another file name DATA_Preferences? - android

I have a listview with choice mode, and it working. I want to save that checked item to shared preference, then use it in another activity. But, my SharedPreferences doesn'nt save my string correct, and save another file call DATA_Preferences that i never call in my code.
The result is my Next activity get wrong value..
Here is my code that i use to save my string and call it use by another activity:
public void onClick(View v) {
SparseBooleanArray checked = listView.getCheckedItemPositions();
ArrayList<DBLokasi> selectedItems = new ArrayList<DBLokasi>();
// Item position in adapter
SharedPreferences prefs = getSharedPreferences("DATA_COOR", Context.MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = prefs.edit();
for (int i = 0; i < checked.size(); i++) {
int position = checked.keyAt(i);
// Add slected if truee
if (checked.valueAt(i))
selectedItems.add(adapter.getItem(position));
prefsEditor.putFloat(POINT_LATITUDE_KEY + i, Float.parseFloat(values.get(position).getLat()));
prefsEditor.putFloat(POINT_LONGITUDE_KEY + i, Float.parseFloat(values.get(position).getLng()));
}
prefsEditor.commit();
String[] outputStrArr = new String[selectedItems.size()];
for (int i = 0; i < selectedItems.size(); i++) {
outputStrArr[i] = String.valueOf(selectedItems.get(i));
}
Bundle b = new Bundle();
Location location = new Location("POINT_LOCATION");
for (int i = 0; i < checked.size(); i++) {
location.setLatitude(prefs.getFloat(POINT_LATITUDE_KEY + i, 0));
location.setLongitude(prefs.getFloat(POINT_LONGITUDE_KEY + i, 0));
double latitude = prefs.getFloat(POINT_LATITUDE_KEY + i, 0);
double longitude = prefs.getFloat(POINT_LONGITUDE_KEY + i, 0);
prefsEditor.commit();
b.putDouble("Latitude" + i, latitude );
b.putDouble("Longitude" + i, longitude);
}
int banyakPilih = checked.size();
b.putInt("banyakPilih", banyakPilih);
Intent intent = new Intent(getApplicationContext(),
HasilPilihanActivity.class);
// Create a bundle object
b.putStringArray("selectedItems", outputStrArr);
// Add the bundle to the intent.
intent.putExtras(b);
// start the ResultActivity
startActivity(intent);
}
I save my Prefernces in DATA_COOR.xml file name, it save my string, but i got another file that save my preference with file name DATA_Preferences in my Explorer. Some body can give me solution? Thanks before..

Define private SharedPreferences mediaPrefs = null;
put this on your constructor mediaPrefs = this.getSharedPreferences("Testing", 1);
put below method to the source:
public void storeStateString(String prefsKeys, Float prefsValue) {
SharedPreferences.Editor prefEditor = mediaPrefs.edit();
prefEditor.putFloat(prefsKeys, prefsValue);
prefEditor.commit();
}
Use this method to store the state like:
storeStateString("POINT_LATITUDE_KEY"+i,Float.parseFloat(values.get(position).getLat()));
and now you can get this preference through:
Float finalValue = mediaPrefs.getFloat("POINT_LATITUDE_KEY1","2.0l");
where 2.0l is defalut value if mediaPrefs is null;
Let me know if any issues regarding that.

Related

Making a variable value constant in android studio

I'm very new to coding in android, so I barely know any of the syntaxes. I am defining a variable in MainActivity.java and assigning it a random 4 digit value. I want to assign this value only once, when the app is installed/updated, and not every time the user opens the app. Help me out if any of you know a fix for this. The following is my current code
Random r = new Random();
int i1 = r.nextInt(9999 - 1) + 1;
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString("key for value", somrRandonNumber);
editor.putBoolean("is first lunch", false);
editor.commit();
Then retrive it with
int number = sharedPref.getInt("key for value";
Sometimes you need to specify a default value like:
SharedPref.getBoolean("is first lunch",true);
Good luck
Use SharedPreference for saving value use this code
int i1=0;
if (getIntValue() == 0) {
Random r = new Random();
i1 = r.nextInt(9999 - 1) + 1;
saveIntValue(i1);
} else {
i1 = getIntValue();
}
here are two method
public void saveIntValue(int myIntValue) {
SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("your_int_key", myIntValue);
editor.commit();
}
public int getIntValue() {
SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
int myIntValue = sp.getInt("your_int_key", 0);
if (myIntValue == 0) {
return 0;
} else {
return myIntValue;
}
}
Store in Preference if value is 0 else get stored value
Random r = new Random();
int value= r.nextInt(9999 - 1) + 1;
if(getValue()==0)
PreferenceManager.getDefaultSharedPreferences(context).edit()
.putInt("uniqueInt", value).apply();
else {
int uniqueIntFromPref = getValue();
}
Retrieve from Preference
private int getValue() {
return PreferenceManager
.getDefaultSharedPreferences(context)
.getString("uniqueInt", 0);
}
Just copy and paste above code

Android - How to access Radio Button outside onCreateView?

I need access to Radio Button outside onCreateView()
public void loadArray(String arrayName, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
int size = prefs.getInt(arrayName + "_size", 0);
int array[] = new int[size];
for(int i=0;i<size;i++) {
array[i] = prefs.getInt(arrayName + "_" + i, 0);
}
for(int i=0; i<size; i++) {
RadioButton radio1 = (RadioButton) findViewById(array[i]);
}
}
Of course findViewById() is not resolved here, inside onCreateView(), I can easily do rootView.findViewById()

How to save string array in preference while iteration is going on

Is it possible to save string array in preference while iterating its values in loop? Say for example :
String[] arrayvalue = new String[5];
for (int i = 0; i <= number; i++) {
Log.d(TAG, "ArrayValue" == " + arrayvalue[i]);
String abcd = arrayvalue[i].toString();
prefs.setData(context, abcd);
Log.d("Prefs", "Saving in Preference");
}
There are actually 5 values, so while saving I will see "Log" is executed 5 times, but while retrieving I am only seeing the last 5th value in preference, why is that so ?
//Retrieving
String converteddata = prefs.getData(context);
Log.d("Prefs", "Retreiving from Preference : " + converteddata);
Save
public synchronized String getData(Context context) {
Log.d(TAG, "getData");
SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
return prefs.getString(DATA, DEFAULT_DATA);
}
//Retrieve
public synchronized void setData(Context context, String data) {
Log.d(TAG, "setData");
SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
prefs.edit().putString(DATA, data).commit();
}
You can create your own String representation of the array like this:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < playlists.length; i++) {
sb.append(playlists[i]).append(",");
//here you save the string each eteration
prefsEditor.putString(PLAYLISTS, sb.toString());
}
Then when you get the String from SharedPreferences simply parse it like this:
String[] playlists = playlist.split(",");
I hope its the answer you look for.

SharedPreferences not storing value

Hi guys I have got a String I am trying to store in to SharedPreferences:
here is the method I am using to store the string:
global vars:
private ArrayList<String> mListEmailAddresses;
method:
public void setEmailAddressList(String emailAddress){
emailAddress.replaceAll(",", "");
mListEmailAddresses.add(emailAddress);
SharedPreferences prefs = getSharedPreferences("invitefriends", 0);
StringBuilder str = new StringBuilder();
for (int i = 0; i < mListEmailAddresses.size(); i++) {
str.append(mListEmailAddresses.get(i).toString()).append(",");
}
LogUtils.log("emails: " + str.toString());
String theString = str.toString();
prefs.edit().putString("emails", theString);
prefs.edit().commit();
}
everytime this method is called the str.toString method is updated with a new email added to the list. for example "email1#gmail.com,email2#yahoo.co.uk,email3#hotmail.co.uk" would be the string that gets formed. the Log shows this string correctly. I then go to put theString under the key "emails" and whenever the view is restarted it is refreshed like so:
SharedPreferences prefs = getSharedPreferences("invitefriends", 0);
String savedString = prefs.getString("emails", "");
LogUtils.log("saved emails: " + savedString);
StringTokenizer st = new StringTokenizer(savedString, ",");
mListEmailAddresses = new ArrayList<String>();
for (int i = 0; i < st.countTokens(); i++) {
String strEmail = st.nextToken().toString();
mListEmailAddresses.add(strEmail);
}
The problem is that the Log here shows the saved emails is an empty string. What am I doing wrong? Thanks guys.
You are making the commit on an other instance of the editor. Try the following code
SharedPreferences.Editor editor = prefs.edit();
editor.putString("emails", theString);
editor.commit();

how to get value from sharedpreferences and save it arraylist

how to get value from shared preferences and save it array list
I want to get the string from shared preferences so that i want save that string to array list
SharedPreferences keyValues = context.getSharedPreferences("name_icons_list", context.MODE_PRIVATE);
if(keyValues.getString(""+str,"").equals("true"))
{
holder.tb1.setChecked(true);
onApps.add(str);
System.out.println("Block appp+++++"+onApps);
System.out.println("******************************************");
System.out.println("data retrive from database"+ position);
System.out.println("******************************************");
}
You may use this code to save preference in arraylist and vice versa
public String[] getApplicationList() { Log.i("test","prefrence getapplist");
return mApplicationList;
}
public void saveApplicationList(String[] applicationList) { Log.i("test","prefrence saveapplist");
mApplicationList = applicationList;
String combined = "";
for (int i=0; i<mApplicationList.length; i++){
combined = combined + mApplicationList[i] + ";";
}
mPref.edit().putString(PREF_APPLICATION_LIST, combined).commit();
}
I believe this should do the trick:
String savedString = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE)
.getString("name_icons_list", "");
StringTokenizer st = new StringTokenizer(savedString, ",");
int numberOfToken = st.countTokens();
ArrayList<String> arraylist = new ArrayList<String>();
for (int i = 0; i < numberOfToken; i++) {
arraylist.add(st.nextToken());
}

Categories

Resources