I have done some codes with regards to SharedPreferences, with the extends of saving and loading data with 2 buttons, respectively save and load. both functions work well, but when i kill the application and go back, I press on the load button, it loads out my array saved previously and i load this array on to a listview, but when i click listview, it seemed that the strings in the array don't seem to be able to perform the activity i have.
Anyone has meet on this problem or similar?
final Button a = (Button) findViewById(R.id.save);
a.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
int mode= MODE_PRIVATE;
// get the sharedPreference of your context.
SharedPreferences mySharedPreferences ; mySharedPreferences=getSharedPreferences("shared",MODE_PRIVATE);
// retrieve an editor to modify the shared preferences
SharedPreferences.Editor editor= mySharedPreferences.edit();
/* now store your primitive type values. In this case it is true, 1f and Hello! World */
for (String s : global.ItemArray){
editor.putString("share", s);
}
//save the changes that you made
editor.commit();
Toast.makeText(getBaseContext(), "Favourites saved", Toast.LENGTH_SHORT)
.show();
}
});
final Button b = (Button) findViewById(R.id.load);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
global.ItemArray.clear();
int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences ;
mySharedPreferences=getSharedPreferences("shared", MODE_PRIVATE);
// Retrieve the saved values.
String mSstring = null;
mSstring= mySharedPreferences.getString("share", mSstring);
/*if (mSstring == "1"){
global.ItemArray.add("Introduction To BCLS");
}*/
global.ItemArray.add(mSstring);
Toast.makeText(getBaseContext(), "Favourites loaded", Toast.LENGTH_SHORT)
.show();
lv1.setAdapter(arrad);
}
}
);
Its because you need a unique name for each string you are sharing
try this while adding
for(int i =0; i < global.ItemArray.length; i ++){
editor.putString("share" + i, global.ItemArray.get(i));
}
and this while removing
for(int i =0; i < global.ItemArray.length; i ++){
global.ItemArray.add(i, editor.getString("share" + i);
}
these may not be syntactically correct so treat them as psuedo-code please
Related
I have multiple buttons i want to change color of button . that i know , but how to save those colors in shared preference ?? and how to delete them from shared preferences ??
private void ShowPunch() {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.fragment_edit_profile);
WS = (Button)dialog.findViewById(R.id.ws);
WE = (Button)dialog.findViewById(R.id.we);
LS = (Button)dialog.findViewById(R.id.lts);
LE = (Button)dialog.findViewById(R.id.lte);
PS = (Button)dialog.findViewById(R.id.pts);
PE = (Button)dialog.findViewById(R.id.pte);
MRMS = (Button)dialog.findViewById(R.id.mrms);
MRME = (Button)dialog.findViewById(R.id.mrme);
WS.setOnClickListener(this) ;
WE.setOnClickListener(this) ;
LS.setOnClickListener(this) ;
LE.setOnClickListener(this) ;
PS.setOnClickListener(this) ;
PE.setOnClickListener(this) ;
MRMS.setOnClickListener(this) ;
MRME.setOnClickListener(this) ;
dialog.show();
}
#SuppressLint("ResourceAsColor")
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.ws:
Punching();
WS.setBackgroundColor(R.color.feedpos);
Toast.makeText(context, "Your Work Time Start From Now..", Toast.LENGTH_SHORT).show();
break;
case R.id.we:
Punchingwe();
Toast.makeText(context, "Your Work Time End Here..", Toast.LENGTH_SHORT).show();
WE.setBackgroundColor(myIntValue);
break;
case R.id.pts:
Punchingpts();
Toast.makeText(context, "Your Prayer Time Start From Now..", Toast.LENGTH_SHORT).show();
PS.setBackgroundColor(myIntValue);
break;
case R.id.pte:
Punchingpte();
Toast.makeText(context, "Your Prayer Time End Here..", Toast.LENGTH_SHORT).show();
PE.setBackgroundColor(myIntValue);
break;
case R.id.lts:
Punchinglts();
Toast.makeText(context, "Your Lunch Time Start From Now..", Toast.LENGTH_SHORT).show();
LS.setBackgroundColor(myIntValue);
break;
case R.id.lte:
Punchinglte();
Toast.makeText(context, "Your Lunch Time End Here..", Toast.LENGTH_SHORT).show();
LE.setBackgroundColor(myIntValue);
break;
case R.id.mrms:
Punchingmrms();
Toast.makeText(context, "Your MRM Time Start From Now..", Toast.LENGTH_SHORT).show();
MRMS.setBackgroundColor(myIntValue);
break;
case R.id.mrme:
Punchingmrme();
Toast.makeText(context, "Your MRM Time End Here..", Toast.LENGTH_SHORT).show();
MRME.setBackgroundColor(myIntValue);
break;
default:
break;
}
}
Please see this video.
When doing the key-value pairs I would store integers and then translate them back into colors. For example, if I store "1" with the key "button1-color" then when using getString("button_color") translate this into a color, say
1 -> red
2 -> orange
3 -> yellow
4 -> green
5 -> blue
Create a SharedPreference instance
mSharedPreferences = getSharedPreferences("shared_pref_name", MODE_PRIVATE);
Add these methods in your Activity
private void saveViewColor(int viewId, int color) {
mSharedPreferences.edit().putInt(String.valueOf(viewId), color).apply();
}
private int getViewColor(int viewId) {
return mSharedPreferences.getInt(String.valueOf(viewId), Color.parseColor("#FFFFFF"));
}
private void removeViewColor(int viewId) {
mSharedPreferences.edit().remove(String.valueOf(viewId)).apply();
}
private void clearAll() {
mSharedPreferences.edit().clear();
}
Invoke method when view click
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int colorInt = Color.BLUE;
Drawable drawable = v.getBackground();
//get color from the view which being clicked
if (drawable instanceof ColorDrawable) {
colorInt = ((ColorDrawable) drawable).getColor();
}
int viewId = v.getId();
v.setBackgroundColor(colorInt);
//save color
saveViewColor(viewId, colorInt);
//get current view color
getViewColor(viewId);
//remove color for current view
removeViewColor(viewId);
//clear all SharedPreferences not only the color
clearAll();
}
});
The way I would do that is create a new Preferences class to store all of your colours, then create getters and setters for each.
public class Preferences extends Activity {
public static final String PREF_FILE = "MyPrefsFileKey";
public int setColour1() {
SharedPreferences prefs = getContext().getSharedPreferences(PREF_FILE, MODE_PRIVATE);
colour = prefs.getInt("colour1Key", 0); //0 being the default value.
return colour1;
}
public int getColour1(int colour1) {
SharedPreferences pref = getContext().getSharedPreferences(PREF_FILE, MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("colour1Key", colour1);
editor.apply();
return colour1;
}
}
Now to save your colour, simply add this under each case. However you will need to create more getters and setters for each.
preferences.getColour1(getContext(), myIntValue1);
Remember to add a new instance of your Preferences class in the class you're saving from like this
Preferences preferences = new Preferences();
Let me know if you have any trouble.
-- EDIT apparently I cannot edit until I have 50 reputation. In your code you had .setBackgroundColor (myIntValue)
myIntValue1 being the value of the first colour you're trying to save.
Here's the problem. In my second class, I'm trying to load the SharedPreferences. Below I'll also include my first class.
//set label for journal questions
public TextView journalQuestionLabel;
public int counter = 0;
SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_journal);
//TODO: Send saved preferences here
preferences = getSharedPreferences("grammarOption", MODE_PRIVATE);
int selection = preferences.getInt("grammarOption", -1);
Log.d("in onCreate", "preferences = " + selection);
}
When I test it, my debug log always prints -1. It won't load my shared preferences. What am I doing wrong?
I've tried the other answers on here and every tutorial, but they aren't working. Here is my code to set up and save my spinner preferences. I've checked this and it's working.
private void setupSpinner() {
// Create adapter for spinner. The list options are from the String array it will use
// the spinner will use the default layout
final ArrayAdapter grammarSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.array_grammar_options,
android.R.layout.simple_spinner_dropdown_item);
// Specify dropdown layout style - simple list view with 1 item per line
grammarSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
//Apply the adapter to the spinner
grammarChoiceSpinner.setAdapter(grammarSpinnerAdapter);
//Create shared preferences to store the spinner selection
SharedPreferences preferences = getApplicationContext().getSharedPreferences
("Selection", MODE_PRIVATE);
editor = preferences.edit();
// Create the intent to save the position
grammarChoiceSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//receive the string of the option and store it
int grammarOptionPosition = grammarChoiceSpinner.getSelectedItemPosition();
//put the string in the editor
editor.putInt("grammarOption", grammarOptionPosition);
editor.commit();
//make a toast so the user knows if it's not "select"
if (grammarOptionPosition != 0) {
Toast.makeText(getApplicationContext(), "Choice saved.",
Toast.LENGTH_SHORT).show();
}
}
// Because AdapterView is an abstract class, onNothingSelected must be defined
#Override
public void onNothingSelected(AdapterView<?> parent) {
mGrammar = 0;
}
});
}
Here it's called in onCreate()
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_opening);
//find the spinner to read user input
grammarChoiceSpinner = (Spinner) findViewById(R.id.spinner);
setupSpinner();
You are passing wrong String in getSharedPreferences(String, int).
preferences = getSharedPreferences("Selection", MODE_PRIVATE);
int selection = preferences.getInt("grammarOption", -1);
Log.d("in onCreate", "preferences = " + selection);
Give this a try.
I hope it helps.
Make sure your SharedPreference key is same in both the class or even throughout the whole App.
While saving do like -
SharedPreferences preferences = getSharedPreferences("MY_PREFS", MODE_PRIVATE);
preferences.edit().putInt("grammerOption", 1).apply();
While Getting data from prefs do like -
SharedPreferences preferences = getSharedPreferences("MY_PREFS", MODE_PRIVATE);
int option = preference.getInt("grammerOption", -1);
PS,
Key for preference(which is MY_PREFS here) must be the same.
I want to create a simple app to upload my location .I have two activities and in first activity the user can input parameters url for upload with editbox , a checkbox if user wish upload location save preferences button and start button for go to get location activity.I try this but no work...How i call my function start and save?Any help?I have errors when debug...after click button
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SharedPreferences preferences = getSharedPreferences("gpstracker" , MODE_PRIVATE);
String strValue = preferences.getString("Url",strValued);
edittxtUrl = (EditText)findViewById(R.id.txtUrl);
edittxtUrl.setText(strValue);
Button buttonStart = (Button)findViewById(R.id.buttonStart);
buttonStart.setOnClickListener(startListener);
Button buttonSave = (Button)findViewById(R.id.buttonSave);
buttonSave.setOnClickListener(saveListener);
}
private OnClickListener startListener = new OnClickListener() {
public void onClick(View v) {
Start();
}
};
private OnClickListener saveListener = new OnClickListener() {
public void onClick(View v) {
Save();
}
};
public void Save() {
SharedPreferences preferences = getSharedPreferences("gpstracker" , MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
edittxtUrl = (EditText)findViewById(R.id.txtUrl);
String strUrl = edittxtUrl.getText().toString();
CheckBox chkTandC = (CheckBox)findViewById(R.id.chkTandC);
boolean blnTandC = chkTandC.isChecked();
editor.putString("Url", strUrl); // value to store
editor.putBoolean("TandC", blnTandC); // value to store
// Commit to storage
editor.commit();
}
public void Start() {
startActivity(new Intent(this, LocTracker.class));
}
Without your log cat it is somewhat hard to tell what your problem is, but what I think is happening is that you are passing a null view to the start method, and this is a problem because you are then trying to get a context. Effectively what you have written is
null.getContext()
which doesn't work. You can fix this by replacing view.getContext() with getApplicationContext()
When I click on an option I want a check sign to appear to show it has been purchased. I am using SharedPreferences and have made all the links; however, when I click back or exit and then re-enter the application, the check is gone and any history of anything I did before is gone. How do I save the data so that it is kept even when the application is off or I'm at another page in the game. This is my code so far:
ImageView tick1;
int mYellCheck, mYellCheck1;
public static String sharedPrefs = "MyData";
SharedPreferences data;
SharedPreferences.Editor editor;
int mYellAlpha;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.upgrades);
update();
coins = Replay.totalCoins + Replay4.totalCoins + Replay5.totalCoins
+ Replay6.totalCoins;
data = getSharedPreferences(sharedPrefs, MODE_PRIVATE);
tick1.setAlpha(mYellCheck);
}
public void update() {
TextView coinScore = (TextView) findViewById(R.id.tvScore);
coinScore.setText("You have " + coins + " coins");
tick1 = (ImageView) findViewById(R.id.ivtick1);
ImageView moreYellow = (ImageView) findViewById(R.id.ivMoreYellow);
ImageView back = (ImageView) findViewById (R.id.ivBack);
back.setOnClickListener(this);
moreYellow.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.ivMoreYellow:
mYellAlpha = 255;
SharedPreferences.Editor editor = data.edit();
editor.putInt("MoreYellowUpgrade", mYellAlpha);
editor.commit();
data = getSharedPreferences(sharedPrefs, MODE_PRIVATE);
mYellCheck = data.getInt("MoreYellowUpgrade", 0);
tick1.setAlpha(mYellCheck);
break;
case R.id.ivBack:
Intent i = new Intent ("m.k.zaman.SpotActivity");
startActivity(i);
break;
}
}
EDIT
or Should i just use internal storage?
Try replacing your current onClick call to R.id.ivMoreYellow with this:
case R.id.ivMoreYellow:
mYellAlpha = 255;
mYellCheck = data.getInt("MoreYellowUpgrade", 0);
tick1.setAlpha(mYellCheck);
SharedPreferences.Editor editor = data.edit();
editor.putInt("MoreYellowUpgrade", mYellAlpha);
editor.commit();
break;
You were first overwriting all of the data in the SharedPreferences, and then calling to receive that data that you just overwrote, so I placed the getInt() call before the putInt(). Do you change mYellAplha to anything other than 255 though? If you don't you will never notice a change in SharedPreferences if you are always saving and getting 255.
I have two radio groups and each group has two radiobuttons.
the default value is true (i.e. checked ) for first radiobutton in each group.
When user cliks on any radiobutton and when user comeback from other activities the selections made on these radiogroups/radiobuttons are gone...
how can I save/restore radiogroup/radiobutton selection state ??
here is my java code..for one radiogroup..
final RadioButton radioOn = ( RadioButton )findViewById(
R.id.rbOn );
final RadioButton radioOff = ( RadioButton )findViewById(
R.id.rbOff );
radioOn.setChecked( true );
radioOn.setOnClickListener( auto_lock_on_listener );
radioOff.setOnClickListener( auto_lock_off_listener );
please help.
You need to override onSaveInstanceState(Bundle savedInstanceState) and write the application state values you want to change to the Bundle parameter like this:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putBoolean("MyBoolean", true);
savedInstanceState.putDouble("myDouble", 1.9);
savedInstanceState.putInt("MyInt", 1);
savedInstanceState.putString("MyString", "Welcome back to Android");
// etc.
super.onSaveInstanceState(savedInstanceState);
}
The Bundle is essentially a way of storing a NVP ("Name-Value Pair") map, and it will get passed in to onCreate and also onRestoreInstanceState where you'd extract the values like this:
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
double myDouble = savedInstanceState.getDouble("myDouble");
int myInt = savedInstanceState.getInt("MyInt");
String myString = savedInstanceState.getString("MyString");
}
You'd usually use this technique to store instance values for your application (selections, unsaved text, etc.).
Try to save your radio group state by using SharedPreferences
RadioGroup rG1 = (RadioGroup)findViewById(R.id.radioGroup1);
int rG1_CheckId = rG1.getCheckedRadioButtonId();
SharedPreferences rG1Prefs = getSharedPreferences("rG1Prefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = rG1Prefs.edit();
prefsEditor.putInt("rG1_CheckId", rG1_CheckId);
prefsEditor.commit();
and put this lines for get back the checked radio button id.
SharedPreferences rG1Prefs = this.getSharedPreferences("rG1Prefs", MODE_WORLD_READABLE);
rG1Prefs.getInt("rG1_CheckId", null);
and by using this id checked the radio button.
you can store into the SharedPreference
simple example
SharedPreferences settings = getSharedPreferences("on_off", 0);
boolean silent = settings.getBoolean("onoff", false);
////// to set the value use editor object from the SharedPreferences
Editor editor = settings.edit();
editor.putBoolean("onoff", true);
editor.commit(); // to save the value into the SharedPreference
Use this code -
mFillingGroup.check(whichFilling);
mAddMayoCheckbox.setChecked(addMayo);
mAddTomatoCheckbox.setChecked(addTomato);
/**
* We also want to record the new state when the user makes changes,
* so install simple observers that do this
*/
mFillingGroup.setOnCheckedChangeListener(
new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group,
int checkedId) {
// As with the checkbox listeners, rewrite the
// entire state file
Log.v(TAG, "New radio item selected: " + checkedId);
recordNewUIState();
}
});
CompoundButton.OnCheckedChangeListener checkListener
= new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// Whichever one is altered, we rewrite the entire UI state
Log.v(TAG, "Checkbox toggled: " + buttonView);
recordNewUIState();
}
};
mAddMayoCheckbox.setOnCheckedChangeListener(checkListener);
mAddTomatoCheckbox.setOnCheckedChangeListener(checkListener);
}
/**
* Handy helper routine to write the UI data to a file.
*/
void writeDataToFileLocked(RandomAccessFile file,
boolean addMayo, boolean addTomato, int whichFilling)
throws IOException {
file.setLength(0L);
file.writeInt(whichFilling);
file.writeBoolean(addMayo);
file.writeBoolean(addTomato);
Log.v(TAG, "NEW STATE: mayo=" + addMayo
+ " tomato=" + addTomato
+ " filling=" + whichFilling);
}
And, this can help you to do whatever you need.
Use Shared Preferences, To save your radio button's state, Or you can use Application Variables (Variable which is declared globally static in that activity and you can use it in any activity)
But I think Shared Preferences is good..
Look at Android - Shared Preferences
Look at this example How to save login info to Shared Preferences Android(remember details feature)
EDIT:
public class Test extends Activity {
private SharedPreferences prefs;
private String prefName = "MyPref";
private SharedPreferences.Editor editor;
private static final String CHECK_STATE = "checkBox_State";
private boolean check_state;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
//---getting the SharedPreferences object....
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
editor = prefs.edit();
radioOn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
check_state = true;
} else {
check_state = false;
}
}
});
// storing in shared preferences...
editor.putBoolean(CHECK_STATE, check_state );
editor.commit();
}
});
}