// I declared myPrefs globally in the lass
SharedPreferences myPrefs = null;
// this is called in my do draw function
public void doDraw() {
myPrefs = this.getSharedPreferences("myPrefs", Context.MODE_WORLD_READABLE);
SharedPreferences.Editor editor = myPrefs.edit();
editor.putInt("MYHIGHSCORE", score);
editor.commit();
}
Whenever I call SharedPreferences.Editor editor = myPrefs.edit();, my program crashes. What I'm doing wrong? I'm trying to store an int for a high score system. And SharedPreferences was suggested a lot for a mini high score system like mine.
Edit:
package com.example.logindemo;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
public class LoginPage extends Activity {
EditText name = null, pwd = null;
SharedPreferences login_pref = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_page);
name = (EditText) findViewById(R.id.name_edt);
pwd = (EditText) findViewById(R.id.pwd_edt);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_login_page, menu);
return true;
}
public void loginMethod(View v) {
login_pref = this.getSharedPreferences("login_pref",
MODE_WORLD_READABLE);
SharedPreferences.Editor login_pref_editor = login_pref.edit();
login_pref_editor.putString("Name", name.getText().toString());
login_pref_editor.commit();
startActivity(new Intent(this, WelcomeScreen.class));
}
}
Try this. I think your shared pref object was not fetched properly.
Note: Edited post to add whole class's code.
If you intend to have only one preference file, try to use this code to retrieve the SharedPreference.
myPrefs = PreferenceManager.getDefaultSharedPreferences(this);
I guess the problem is not at edit() but when u apply() your changes. Look at the solution here
Related
I am new in Android programing. I want to make an application. The button text increase whenever the user click on it. My counter is reseted when the application is closed. How can I store the last counter value and call it again when the application is reopened?
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
private int c;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = (Button) findViewById(R.id.buttonClick);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
c++;
button.setText(Integer.toString(c));
}
});
}
}
EDIT:
I try to use this Shared Preferences but I got eror about "setSilent" and "mSilentMode". Help please
My new code
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
private int c;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
final Button button = (Button) findViewById(R.id.buttonClick);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
c++;
button.setText(Integer.toString(c));
}
});
}
#Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}
}
It depends, are you asking how to preserve a variable across an app's lifespan or between different lifespans?
If it's across different lifespans, you can write it to disk and then read it onCreate.
If you need to do it across one lifespan, it depends on your use case, but generally putting it in a global, static variable would do the trick!
If this is unclear and you'd like some sample code, please, don't be afraid to ask! : )
You can save your c value in the Preference when your activity is going to be closed, and when you rise up your activity you set your c variabile to the previous value
Use this snippet out of your onClickListener: To get the int if there is any
SharedPreferences hhii = getSharedPreferences("c_value", MODE_PRIVATE);
int ca = hhii.getInt("c_value2", 0);
button.setText(ca+"");
Use this in your onClickListener: To save the int as the user clicks the button-much better than saving it in onBackPressed or OnDestroy or whatever
c++;
button.setText(Integer.toString(c));
SharedPreferences hhii = getSharedPreferences("c_value", MODE_PRIVATE);
hhii.edit().putInt("c_value2",c).commit();
Regards from Iran,
Gabriel
I am doing an android app which would save the password for the next time the user wants to use this app. when I try to run my application, the password is entered,but there is a pop-up said the application has stopped?
package com.wheresmyphone;
import android.os.Bundle;
import android.app.Activity;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class Check extends Activity {
String StringPreference;
SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check);
Button b = (Button)findViewById(R.id.Button01);
final EditText preferences = (EditText)findViewById(R.id.txt12345);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
EditText sharedPreferences = (EditText)findViewById(R.id.txt12345);
String StringPreference = preferences.getText().toString();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.check, menu);
return true;
}
/**
* Method used to get Shared Preferences */
public SharedPreferences getPreferences()
{
return getSharedPreferences(null, 0);
}
/**
* Method used to save Preferences */
public void savePreferences(String key, String value)
{
SharedPreferences sharedPreferences = getPreferences();
SharedPreferences.Editor editor = preferences.edit();
String StringPreference = sharedPreferences.toString();
editor.putString("sharedString", StringPreference);
editor.commit();
}
/**
* Method used to load Preferences */
public String loadPreferences(String key)
{
try {
SharedPreferences sharedPreferences = getPreferences();
String strSavedMemo = sharedPreferences.getString(key, "");
return strSavedMemo;
} catch (NullPointerException nullPointerException)
{
Log.e("Error caused at TelaSketchUtin loadPreferences method",
">======>" + nullPointerException);
return null;
}
}
/**
* Method used to delete Preferences */
public boolean deletePreferences(String key)
{
SharedPreferences.Editor editor=getPreferences().edit();
editor.remove(key).commit();
return false;
}
{
}
}
I'm not sure, but i think you missed something at this point:
return getSharedPreferences(null, 0);
Look here:
http://developer.android.com/reference/android/content/Context.html#getSharedPreferences%28java.lang.String,%20int%29
Parameters
name
Desired preferences file. If a preferences file by this name does not exist, it will be created when you retrieve an editor (SharedPreferences.edit()) and then commit changes (Editor.commit()).
If you set "name" to null, he cant create a file.
Might be the solution, add this on top
private final String KEY_SHAREDPREFS = "tmpsharedprefs";
and then use it
return getSharedPreferences(KEY_SHAREDPREFS, 0);
See your are trying to get string from preference, first you have to get password from edittext like this code
EditText passwordText = (EditText)findViewById(R.id.txt12345);
String password = passwordText.getText().toString();
and then store this password in shared preferences
Use SharedPreferences as,
To Save:
SharedPreferences settings;
SharedPreferences.Editor editor;
public static final String PREFS_NAME = "app_pref";
public static final String KEY_p_id = "KEY_test";
settings = getSharedPreferences(PREFS_NAME, 0);
editor = settings.edit();
editor.putString(Login_screen.KEY_test, values.get(0));
editor.commit();
To Remove:
editor.remove("KEY_test").commit();
To Get:
settings = getSharedPreferences(PREFS_NAME, 0);
String TestId = settings.getString("KEY_test", null);
A simple task remainder application.
I have to save and retrieve the three edit text values in this app using shared preferences.
Which storage option is best for this app,
1.shared preferences
2.internal storage
Storing
EditText Task = (EditText)findViewById(R.id.ettask);
EditText date = (EditText)findViewById(R.id.etdate);
EditText time = (EditText)findViewById(R.id.ettime);
String taskstr = Task.getText().toString();
String datestr= date .getText().toString();
String timestr= time .getText().toString();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit = preferences.edit();
edit.putString("pref_task", taskstr);
edit.putString("pref_date", datestr);
edit.putString("pref_date", timestr);
edit.commit();
Retrieving
pref_task = preferences.getString("pref_task", "n/a");
pref_date = preferences.getString("pref_date","n/a");
pref_time = preferences.getString("pref_date","n/a");
Complete example:
package com.example.logindemo;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
public class LoginPage extends Activity {
EditText name = null, pwd = null;
SharedPreferences login_pref = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_page);
name = (EditText) findViewById(R.id.name_edt);
pwd = (EditText) findViewById(R.id.pwd_edt);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_login_page, menu);
return true;
}
public void loginMethod(View v) {
login_pref = this.getSharedPreferences("login_pref",
MODE_WORLD_READABLE);
SharedPreferences.Editor login_pref_editor = login_pref.edit();
login_pref_editor.putString("Name", name.getText().toString());
login_pref_editor.commit();
startActivity(new Intent(this, WelcomeScreen.class));
}
}
Hope it helps. I feel Shared preference will be a better way
Use below code to Store data into SharedPreferences.
SharedPreferences myPrefs = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = myPrefs.edit();
editor.putString("Date", mEdttxtDate.getText().toString());
editor.commit();
For Retrive data from SharedPreferences.
SharedPreferences myPrefs = PreferenceManager.getDefaultSharedPreferences(this);
String mDate = myPrefs.getString("Date","nothing");
it will solve your problem.
for inserting
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit = preferences.edit();
edit.putString("pref_empId", _empid);
edit.putString("pref_userType", _usertype);
edit.commit();
for getting shared preferences
pref_empId = preferences.getString("pref_empId","n/a");
pref_userType = preferences.getString("pref_userType","n/a");
I want to save the value of a string at exit of my application(process kill) in last activity , so that when I start that application again I can retrieve that value in first activity.
I tried the sharedpreferences but that does not solve my problem. Here is the code snippet.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Intent int1 = getIntent();
String pth = prefs.getString("pathreturned", "true");
to retrieve in the first activity.
and this one to save it in the previous activity:
SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_PRIVATE);
SharedPreferences.Editor e = myPrefs.edit();
e.putString("pathreturned", path);
e.commit();
In your previous Activity, use the same code as the one you used before...
Instead of
SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_PRIVATE);
use
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Here is a complete Example of Saving Strings Via SharedPreferences
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class SharedPrefs extends Activity implements OnClickListener{
private EditText dataInput;
private TextView dataView;
private SharedPreferences sharedString;
public static final String myFile = "MySharedDataFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sharedprefs);
setUpVariables();
sharedString = getSharedPreferences(myFile, 0);
}
public void setUpVariables(){
dataInput = (EditText) findViewById(R.id.dataToUse);
dataView = (TextView) findViewById(R.id.showDataView);
Button save = (Button) findViewById(R.id.savedataButton);
Button load = (Button) findViewById(R.id.loadDataButton);
save.setOnClickListener(this);
load.setOnClickListener(this);
}
public void onClick(View arg0) {
switch(arg0.getId()){
case R.id.savedataButton:
String dataToSave = dataInput.getText().toString();
Editor storeData = sharedString.edit();
storeData.putString("key", dataToSave);
storeData.commit();
break;
case R.id.loadDataButton:
sharedString = getSharedPreferences(myFile, 0);
String savedData = sharedString.getString("key", "No data Found");
dataView.setText(savedData);
break;
}
}
}
Unless you know which Activity is going to be "last" you should save your value at the close of each activity. Override the onStop method and save it there.
i have a problem, i want to run an activity which handles a preference dialog
Intent i= new Intent(getBaseContext(), PreferencesActivity.class);
startActivity(i);
when i run the app i only get an nullpointerexcepltion when the activity should start. what is wrong?
PreferencesActivity looks this way:
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.Preference.OnPreferenceClickListener;
import android.widget.Toast;
public class PreferencesActivity extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.layout.preferences);
// Get the custom preference
Preference customPref = (Preference) findPreference("customPref");
customPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
Toast.makeText(getBaseContext(),
"The custom preference has been clicked",
Toast.LENGTH_LONG).show();
SharedPreferences customSharedPreference = getSharedPreferences(
"myCustomSharedPrefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = customSharedPreference.edit();
editor.putString("myCustomPref","The preference has been clicked");
editor.commit();
return true;
}
});
}
}
Maybe problem is in the getBaseContext(). If you use this method, you should set the context by the constructor or by "setBaseContext" method. You can try to use "getApplicationContext", or just "this"
Try the following...
public boolean onPreferenceClick(Preference preference) {
// Use PreferencesActivity.this for the Context used in the Toast below...
Toast.makeText(PreferencesActivity.this,
"The custom preference has been clicked",
Toast.LENGTH_LONG).show();
// Use Context.MODE_PRIVATE instead of Activity.MODE_PRIVATE
SharedPreferences customSharedPreference = getSharedPreferences(
"myCustomSharedPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = customSharedPreference.edit();
editor.putString("myCustomPref","The preference has been clicked");
editor.commit();
return true;
}