what should I do[Shared Preferences] - android

I want to save 2 variable when application stopped and I want to use these variables when application restarted.I'm using sharedpreferences but I couldnt solve.
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
for(int k=0;k<=secili.length;k++){
if(secili[k]!=0)
cevapdizisi[k]=secili[k];
}
for(int m=100;m>=0;m--){
if(m!=0){
sonsoru=m;
break;
}
in onStop there isnt problem
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
setContentView(R.layout.answerpage);
txtquestion.setText(questions[sonsoru]);
rdiogroup.check(secili[sonsoru]);
}
in onRestart can't accessing txtquestion and rdiogroup.I'm created them on OnCreate.What should I do.I cant created them again onRestart.it will absurd.there must be another way.I need a help

To store values in shared preferences you may use following code:
public class MainActivity extends Activity{
SharedPreferences prefs;
EditText edTextName,edTextPassword,edTextServer;
protected void onCreate(Bundle arg0) {
.
.
//do your stuff...
.
prefs= this.getSharedPreferences("UserInfo", MODE_PRIVATE);
String hostname = prefs.getString("HostName", null);
String name = prefs.getString("UserName", null);
String password = prefs.getString("Password", null);
}
protected void onStop() {
.
//do your stuff...
.
SharedPreferences.Editor editor = prefs.edit();
editor.putString("HostName", edTextName.getText().toString());
editor.putString("UserName", edTextPassword.getText().toString());
editor.putString("Password", edTextServer.getText().toString());
editor.commit();
}
}

Related

Instance state to keep button visibility

How do I keep button Visibility when returning from another activity?
My Code:
#Override
protected void onStop() {
super.onStop();
SharedPreferences btVis = getSharedPreferences(BUTT_VIS,0);
SharedPreferences.Editor edit = btVis.edit();
edit.putString("btS1",btSub1.getVisibility()+"");
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences btVis = getSharedPreferences(BUTT_VIS,0);
int btS1 = Integer.parseInt("View." +btVis.getString("btS1",""));
btSub1.setVisibility(btS1);
}
I get an error cause setVisibility needs to be in format View.(VISIBILITY) for example. But I parsed btS1 as an int in the format View.(VISIBILITY) so I dont know why it doesn't work. How do I fix this?
You forgot to call editor.commit(); which means your int was never actually saved.
#Override
protected void onStop() {
super.onStop();
SharedPreferences btVis = getSharedPreferences(BUTT_VIS,0);
SharedPreferences.Editor edit = btVis.edit();
edit.putString("btS1",btSub1.getVisibility()+"");
editor.commit();
}
Edit:
I see you also did something wrong
int btS1 = Integer.parseInt("View." +btVis.getString("btS1",""));
While you do get the id via the class View, you don't need to get it from your shared prefs that way. You already just stored the Integer that is referred to in View.GONE and View.Visisble.
To make this work you just need:
int btS1 = Integer.parseInt(btVis.getString("btS1",""));
But I don't see why you would parse it to a String and then parse it back to an int. Also I would do the saving on OnPause instead of OnStop. So completely reworked you should do this:
#Override
protected void onPause() {
super.onPause();
SharedPreferences btVis = getSharedPreferences(BUTT_VIS, 0);
SharedPreferences.Editor edit = btVis.edit();
edit.putInt("btS1", btSub1.getVisibility());
edit.commit();
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences btVis = getSharedPreferences(BUTT_VIS, 0);
int btS1 = btVis.getInt("btS1", 0);
btSub1.setVisibility(btS1);
}
try this one in onResume() method.
#Override
protected void onResume() {
super.onResume();
SharedPreferences btVis = getSharedPreferences(BUTT_VIS,0);
int visibility = Integer.parseInt(btVis.getString("btS1",""));
switch(visibility){
case View.VISIBLE: //make button visible
break;
case View.INVISIBLE: //make button invisible
break;
}
}
Make sure to commit editor at the end of onStop() method

EditTextPreference validate data before saving

I have a method to validate a EditTextPreference. My method is executed after the confirmation of data by implementing the onSharedPreferenceChanged class.
However, only occurs after you confirm the information. I would perform the check without closing the dialog box. And if ok then close or keep open for user to enter the data correctly.
If it's not possible, I would reopen the dialog box if the validation is false.
SettingsActivity.java
class SettingsActivity extends PreferenceActivity implements
OnSharedPreferenceChangeListener {
protected static final String TAG = "SettingsActivity";
private SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
// TODO Auto-generated method stub
SharedPreferences.Editor prefEditor = prefs.edit();
if(key.equals("pref_Url")){
String url = prefs.getString(key, "");
boolean response = (!new ConnectUtils().isConnected(this, url));
if(!response){
prefEditor.putString(key, Config.SERVER_URL_DEF_VALUE);
prefEditor.commit();
reload();
Toast.makeText(this,R.string.msgToast_server_url_invalid,Toast.LENGTH_SHORT).show();
}
}else if (key.equals("pref_Id")){
String url = Config.SERVER_URL_ID;
boolean reponse = (!new ConnectUtils().isConnected(this,url));
if(!reponse){
prefEditor.putString(key,Config.ID_DEF_VALUE);
prefEditor.commit();
reload();
Toast.makeText(Config.getContext(), R.string.msgToast_Id_invalid, Toast.LENGTH_SHORT).show();
}
}
}
private void reload(){
startActivity(getIntent());
finish();
}
}
'onPreferenceChangeListener' is a listener that is executed every time a preference is changed by the user. You can return true if data complains validation or false otherwise.
For example:
public class Preferences extends PreferenceActivity implements OnSharedPreferenceChangeListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
findPreference("pre_mail").setOnPreferenceChangeListener(
new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
return Pattern.matches(Constants.MAILPATTERN, (String) newValue);
}
});
}
}
Hope this help!

Getting shared preferences data of another class

Im trying to make a favorites list. I have this class called Animal and another called Favorites. The favorites arraylist is created in the class Favorites. I can access the favorites arraylist from Animal with
public static Favorites addfavorite = new Favorites();
and add items to the favorits list.
As the items that are added from the Animal class to the favorites list i need this arraylist to be saved. I tried to do this with SharedPreferences. It almost works. After adding items and completely closing and reopening the app i get the following problem.
Problem:
If i open the app and go to the Animal class, without opening the Favorites class first and seeing the previously added items (So the OnCreate() method for Favorites hasn't been called yet), and if i add or dont add a new item to favorites list (it doesn't matter) while I'm in Animal class, when i open the 'Favorites' class the previously added items are deleted and replaced by the newly added ones if new items are added, if not the list becomes empty. (I dont want this i need to have both the old and new items) But if i first open the Favorites class and see the previously added items(thus having the 'OnCreate()' method be called for 'Favorites') and then go to the Animal class and add new items both the new and old items are listed in 'Favorites'. (This is what I'm trying to achieve)
How do i fix this problem?
EDIT: Some code from Animal
#Override
protected void onPause() {
// TODO Auto-generated method stub
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putStringSet(PREFS_NAME,
new HashSet<String>(addfavorite.getFavorites()));
editor.commit();
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
favoritesanimal = new ArrayList<String>(prefs.getStringSet(PREFS_NAME,
new HashSet<String>()));
super.onResume();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
outState.putStringArrayList(PREFS_NAME, addfavorite.getFavorites());
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState != null
&& savedInstanceState.containsKey(PREFS_NAME)) {
favoritesanimal = savedInstanceState.getStringArrayList(PREFS_NAME);
}
}
favoritesanimal is an arbitrary arraylist i created. It isnt related to the Favorite class or the favoriteslist Its actually useless. So the onPause() and onResume methodes do nothing at the moment.
And here is code from Favorites (notice i am using the same sharedpreferences attributes in both classes)
#Override
public void onCreate(Bundle savedInstanceState) {
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
favorites = new ArrayList<String>(prefs.getStringSet(PREFS_NAME,
new HashSet<String>()));
super.onCreate(savedInstanceState);
//As you can see i added SharedPreferences to OnCreate
//more code..
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putStringSet(PREFS_NAME, new HashSet<String>(favorites));
editor.commit();
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
favorites = new ArrayList<String>(prefs.getStringSet(PREFS_NAME,
new HashSet<String>()));
super.onResume();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
outState.putStringArrayList(PREFS_NAME, favorites);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState != null
&& savedInstanceState.containsKey(PREFS_NAME)) {
favorites = savedInstanceState.getStringArrayList(PREFS_NAME);
}
}
I think that, when you use addfavorite.getFavorites(), this method returns empty list. And when you goes to Favorites class, onPause() method in Animals class is called and rewrote your preferences.

savedpreferences not working on reboot on an android board

From last one week I am facing a strange problem with saved preferences.
I am working on a board which is android compatable.
The actual problem i am facing is,
I have 4 buttons and on the button click I am changing the background images of the button
Onfirstclick -> change the background image of the button to highlited -> second click ->change to normal background image and on first run I am keeping the normal background button image
but on reboot the button background images are not getting saved in my working board though I am using shared preferences.
I have a power button for on and off with which I am rebooting my board.
whatever Image(normal/highlited) I have in onclick that image I should get after rebooting the board
The good thing is that
the code is working perfectly in android mobile but not in my board
this is my code.
Any help is always appreciated.
public class SharedprefsActivity extends Activity {
protected static final String TAG = "HvacActivity";
/** Called when the activity is first created. */
private Button seatdirnbtn;
private SharedPreferences prefs;
private String prefName = "MyPref";
private SharedPreferences.Editor editor;
private boolean isclick;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
seatdirnbtn = (Button) findViewById(R.id.seatdirnbtn);
seatdirnbtn.setOnClickListener(listner1);
}
public void onResume() {
super.onResume();
getPrefAndButtonState();
}
public void onPause() {
super.onPause();
setPrefAndButtonState();
}
#Override
public void onRestart() {
super.onRestart();
getPrefAndButtonState();
}
#Override
public void onStop() {
super.onStop();
setPrefAndButtonState();
}
public void getPrefAndButtonState(){
prefs = this.getSharedPreferences(prefName, MODE_PRIVATE);
isclick = prefs.getBoolean("prefName", false);
System.out.println("bool? " + isclick);
if (isclick) {
seatdirnbtn.setBackgroundResource(R.drawable.icon4hlt);
} else if (!isclick) {
seatdirnbtn.setBackgroundResource(R.drawable.icon4);
}
}
public void setPrefAndButtonState(){
editor = prefs.edit();
editor.putBoolean("prefName", isclick);
editor.commit();
getPrefAndButtonState();
}
private View.OnClickListener listner1 = new View.OnClickListener() {
public void onClick(View v) {
if (isclick) {
isclick = false;
setPrefAndButtonState();
} else if (!isclick) {
isclick = true;
setPrefAndButtonState();
}
}
};
}
try using getApplicationContext() instead of this as:
in setPrefAndButtonState method :
public void setPrefAndButtonState(){
prefs = getApplicationContext().
getSharedPreferences(prefName, MODE_PRIVATE); <<missing this line
editor = prefs.edit();
editor.putBoolean("prefName", isclick);
editor.commit();
getPrefAndButtonState();
}
and in getPrefAndButtonState method
public void getPrefAndButtonState(){
prefs = getApplicationContext().getSharedPreferences(prefName, MODE_PRIVATE);
isclick = prefs.getBoolean("prefName", false);
System.out.println("bool? " + isclick);
if (isclick) {
seatdirnbtn.setBackgroundResource(R.drawable.icon4hlt);
} else if (!isclick) {
seatdirnbtn.setBackgroundResource(R.drawable.icon4);
}
}

SharedPreferences troublesome nullpointerexception

(REMOVED THE OLD CONTENT OF THE POST)
EDIT #2: Okay, so now I am crystal clear that it is the editor trying to reach the preference that causes the nullpointerexception. Any help here on how to fix it?
Here is the updated activity:
public SharedPreferences sharedPreferences;
Editor editor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// requesting to turn the title OFF
requestWindowFeature(Window.FEATURE_NO_TITLE);
// making it full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
// set our MainGamePanel as the View
setContentView(new MainGamePanel(this));
// Restore preferences
this.sharedPreferences = getPreferences(MODE_PRIVATE);
this.editor = sharedPreferences.edit();
try {
int wins = GetPreferences("wins");
int fails = GetPreferences("fails");
gamePanel.winn = wins;
gamePanel.failn = fails;
} catch (NullPointerException npe) {
Log.d(TAG, "Nothing to load");
}
//INIT SOUND
mSoundManager.initSounds(getBaseContext());
//SOUNDS
mSoundManager.addSound(1, R.raw.draw);
mSoundManager.addSound(2, R.raw.cheer);
mSoundManager.addSound(3, R.raw.boo);
}
#SuppressWarnings("deprecation")
#Override
public void onBackPressed()
{
super.onBackPressed();
if (gamePanel.gamei==true) {
gamePanel.back();
} else if (gamePanel.menui==true) {
finish();
System.runFinalizersOnExit(true);
System.exit(0);
}
}
public void onPause()
{
super.onPause();
//KILL ALL
finish();
System.runFinalizersOnExit(true);
System.exit(0);
}
#Override
protected void onStop(){
super.onStop();
//KILL ALL
finish();
System.runFinalizersOnExit(true);
System.exit(0);
}
public int GetPreferences(String key) {
return sharedPreferences.getInt(key, 0);
}
public void SavePreferences(String key, int value) {
editor.putInt(key, value);
editor.apply();
}
public void writeWin () {
SavePreferences("wins", gamePanel.winn);
}
public void writeFail () {
SavePreferences("fails", gamePanel.failn);
}
The editor is what is causing the nullpointerexception: this.editor = sharedPreferences.edit();. EDIT: It's the sharedPreferences that is causing the nullpointerexception, not the editor.
It seems like the editor cannot reach the Preference: this.sharedPreferences = getPreferences(MODE_PRIVATE);.
Any idea on how to fix this?
It look like the declaration
Editor editor;
should be
SharedPreferences.Editor editor;
I finally got it fixed by using a listener! It apparantely was the gamePanel that was null inside of the activity. Go here for more information:
nullpointerexception when trying to reach activity

Categories

Resources