I am using the Scrollable tabs + Swipe Navigation for my project. I used Shared Preferences to store data of a form.
My onClick function for the save button of the page.
public void onClick(View v) {
SharedPreferences.Editor editor3 = settings3.edit();
editor3.putString("address", personal_info_address.getText().toString());
editor3.putString("age", personal_info_age.getText().toString());
editor3.putString("name", personal_info_name.getText().toString());
editor3.putString("diseases", personal_info_diseases.getText().toString());
editor3.commit();
}
I am unable to restore data after I reopen the application.
I am able to save my form details in a normal app with the same code, do I need to do something else as I am using the Scrollable tabs + Swipe Navigation.
EDIT:
I implemented the clickListener in the Fragment Class, here is my code:
public class SettingsFragment extends Fragment {
public static EditText txtMessage;
public static EditText emergencyno;
Button button;
Context context;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
context = getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.services, container, false);
emergencyno = (EditText) root.findViewById(R.id.settings_number);
txtMessage = (EditText) root.findViewById(R.id.settings_msg);
button = (Button) root.findViewById(R.id.save);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String msg = txtMessage.getText().toString();
String no = emergencyno.getText().toString();
Log.d("HELLO : ", "data1");
SharedPreferences sharedpreferences = context
.getSharedPreferences("MyData", Context.MODE_PRIVATE);
Log.d("HELLO : ", "data2" + context);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("message", msg);
editor.putString("number", no);
editor.commit();
Log.d("HELLO : ", "data3" + msg + no);
String message = sharedpreferences.getString("message",
"defValue");
String phone_no = sharedpreferences.getString("number",
"defValue");
txtMessage.setText(message);
emergencyno.setText(phone_no);
Log.d("HELLO : ", "data4" + message + phone_no);
}
});
return root;
}
}
The log gives the correct values which I require. But on restarting the app the data isnt stored. I need to know how to get the Context.
I was able to solve the problem. The getActivity() in this fragment returned the Main Page of my app where I created the fragments so I defined my sharedpreferences function in the Main Page of the app(i.e. in the activity of this Fragment) as follows:
public static void putPref(String key, String value, Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(key, value);
editor.commit();
}
public static void putPref(String key, Boolean value, Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(key, value);
editor.commit();
}
public static String getPref(String key, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(key, null);
}
public static boolean getPrefBool(String key, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getBoolean(key, true);
}
And used the putPref function on clicking the button and getPref function on activity created.
Related
How can I store already existing string value in SharedPreferences on button click? I have a TextView and a button: the TextView contains certain string and I want to store that in SharedPreferences on button click.
To write it:
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("Yourkey", textView.getText()+"");
editor.commit();
}
});
And to read it:
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
String string = sharedPref.getString("Yourkey","default");
Here are methods which I use everytime to store data in shared-preferences:
private SharedPreferences app_prefs;
private final String DEVICE_TOKEN = "device_token";
public PreferenceHelper(Context context) {
app_prefs = context.getSharedPreferences(AndyConstants.PREF_NAME,
Context.MODE_PRIVATE);
this.context = context;
}
public void putDeviceToken(String deviceToken) {
Editor edit = app_prefs.edit();
edit.putString(DEVICE_TOKEN, deviceToken);
edit.commit();
}
public String getDeviceToken() {
return app_prefs.getString(DEVICE_TOKEN, null);
}
In the first method I create the shared-preferances object, in the second method I use it to put data and in third method to get data any where you need.
public class LoginActivity extends BaseActivity{
private SharedPreferences pref;
private SharedPreferences.Editor editor;
private EditText accountEdit;
private EditText passwordEdit;
private Button login;
private CheckBox rememberPass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
accountEdit =(EditText)findViewById(R.id.account);
passwordEdit = (EditText)findViewById(R.id.password);
rememberPass=(CheckBox)findViewById(R.id.remember_pass);
login = (Button)findViewById(R.id.login);
editor.putBoolean("remember_password",false);
boolean isRemember = pref.getBoolean("remember_password",false);
if(isRemember){
String account = pref.getString("account", "");
String password =pref.getString("password", "");
accountEdit.setText(account);
passwordEdit.setText(password);
rememberPass.setChecked(true);
}
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String account =accountEdit.getText().toString();
String password = passwordEdit.getText().toString();
if (account.equals("admin")&& password.equals("123456"))
{ editor = pref.edit();
if(rememberPass.isChecked())
{
editor.putBoolean("remember_password",true);
editor.putString("account",account);
editor.putString("password",password);
}
else
{
editor.clear();
}
editor.commit();
Intent intent = new Intent(LoginActivity.this,MainActivity.class);
startActivity(intent);
finish();
}
else
{
Toast.makeText(LoginActivity.this,"account for password is invalid",
Toast.LENGTH_LONG).show();
}
}
});
}
}
I use Eclipse to code android.I got an error in LogCat,which is NullPointerException cause by "boolean isRemember = pref.getBoolean("remember_password",false);"
I don't know why.How to use getBoolean correctly?
Thanks in advance.
Because pref=null at
boolean isRemember = pref.getBoolean("remember_password",false);
initialized it before used
SharedPreferences pref= PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);
You have to create the object of the Shared preference than you can use it in yours code
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
than use
boolean isRemember = pref.getBoolean("remember_password",false);
Use this simple way to use prefrences
private SharedPreferences getPrefs;
//in OnCreate
getPrefs = PreferenceManager.getDefaultSharedPreferences(Activity_Name.this);
//At insertion value
getPrefs.edit().putBoolean("Key_Name", false).commit();
//At fetching Values
boolean a = getPrefs.getBoolean("Key_Name", false);
I have created an activity that should be displayed only once. In this Activity, I added a button, and click its close and will not reopen anymore when the application is started again. I thought of using SharedPreferences, but I do not get the desired result.
I memorize a data in Shared:
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
SharedPreferences userDetails = getSharedPreferences("entrato", MODE_PRIVATE);
Editor edit = userDetails.edit();
edit.clear();
edit.putString( "entrato", "entra" );
edit.commit();
this.finish();
break;
}
}
then, in OnCreate() of the previous activity call the Shared and if the data is present do not open the activity:
//remember click
SharedPreferences userDetails = getSharedPreferences("entrato", MODE_PRIVATE);
String valore = userDetails.getString("entrato", "");
if (valore.equals("entra")){
return;
}else{
Intent intent = null;
intent = new Intent(this, Benvenuto.class);
startActivity(intent);
create share preference class like this:
public class MyPreference {
private static final String APP_SHARED_PREFS = "myPref";
private SharedPreferences appSharedPrefs;
private Editor prefsEditor;
public MyPreference(Context context) {
this.appSharedPrefs = context.getSharedPreferences(APP_SHARED_PREFS, Activity.MODE_PRIVATE);
this.prefsEditor = appSharedPrefs.edit();
}
public boolean loadServices(String servicName) {
return appSharedPrefs.getBoolean(servicName, false);
}
public void saveServices(String servicName, boolean isActivated) {
prefsEditor.putBoolean(servicName, isActivated);
prefsEditor.commit();
}
}
then On Oncreate activity check if service exist so wont show and exit.
public static MyPreference myPref = new MyPreference(this);
if(myPref.loadService("this is not first time")){
thisActivity.finish();
}else {
// so it's first time and you can do what ever you want to do
}
and go on you click events and save service like this.
public static MyPreference myPref = new MyPreference(this);
myPref.saveService("this is not first time");
Try this code instead
// save string
static public boolean setPreference(Context c, String value, String key) {
SharedPreferences settings = c.getSharedPreferences(PREFS_NAME, 0);
settings = c.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, value);
return editor.commit();
}
// retrieve String
static public String getPreference(Context c, String key) {
SharedPreferences settings = c.getSharedPreferences(PREFS_NAME, 0);
settings = c.getSharedPreferences(PREFS_NAME, 0);
String value = settings.getString(key, "");
return value;
}
I have Four activities
Splash
Have 2 Buttons And 1 CheckBox ( Remember Me)
3 & 4. Another Activity
If I check the remember me option using checkbox, then I have to remember the button I have clicked and then start the 3rd or 4th activity directly whenever next start.
I'm trying to store some strings in a shared preference file and then retrieve them in another activity, except it doesn't seem to be working. Any guidance as to where im going wrong would be much appreciated. Many thanks.
public void save(View view) {
SavePreferences("name", nameS);
SavePreferences("current", currentS);
SavePreferences("goal", goalS);
SavePreferences("CurrentBmi", cBmiS);
SavePreferences("goalBmi", gBmiS);
Toast.makeText(this, "profile Saved", Toast.LENGTH_SHORT).show();
startActivity(new Intent(this, MainActivity.class));
}
private void SavePreferences(String key, String value) {
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
public class Progress extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_progress);
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
String test = sharedPreferences.getString("name", "");
String test2 = sharedPreferences.getString("current", "");
TextView testy = (TextView) findViewById(R.id.textView1);
testy.setText(test);
TextView testz = (TextView) findViewById(R.id.test2);
testz.setText(test2);
}
With the code you have you are limiting the access of sharedpreferences to activity(context) level.
Values saved in activity Activity MainActivity will not be available in activity Progress since you are using getPreferences(MODE_PRIVATE);
Change this to
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
or
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
getPreferences:
public SharedPreferences getPreferences (int mode)
Retrieve a SharedPreferences object for accessing preferences that are private to this activity.
I'm creating a Quiz App, I ask some questions and give options in the form of radio buttons, now I want to store value of of answer (plus on right answer and minus on wrong one) in SharedPreferences and show that result in other activity. I have searched and found this answer here
I used that but still I'm unable to get my desired results
My code Looks Like :
Main Activity which saves some value in SharedPreferences:
public class MainActivity extends Activity {
private SharedPreferences saveScore;
private SharedPreferences.Editor editor;
RadioGroup group;
RadioButton radioButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
group = (RadioGroup) findViewById(R.id.radioGroup1);
radioButton = (RadioButton) group.findViewById(group.getCheckedRadioButtonId());
saveScore = getPreferences(MODE_PRIVATE);
}
public void gotoNextAndSaveScore(View view) {
if(group.getCheckedRadioButtonId() != R.id.radio3){
editor = saveScore.edit();
editor.putInt("score", -1);
editor.commit();
}else{
editor = saveScore.edit();
editor.putInt("score", 1);
editor.commit();
}
Intent intent = new Intent (MainActivity.this, NextActivity.class);
startActivity(intent);
}}
this is the Next Activity which tries to get values from SharedPreferences:
public class NextActivity extends Activity{
private SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
preferences = this.getSharedPreferences("score", MODE_WORLD_WRITEABLE);
int value = preferences.getInt("score", 0);
String score = "Your Score is : " + value;
UIHelper.displayScore(this, R.id.tvScore, score );
}}
does any one know how to that?
You should change the line
saveScore = getPreferences(MODE_PRIVATE);
To
saveScore = getSharedPreferences("score",Context.MODE_PRIVATE);
Store the value when navigating to nextActivity during onPause() as below:
#Override
protected void onPause()
{
super.onPause();
// Store values between instances here
SharedPreferences preferences = getSharedPreferences("sharedPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("YourStringKeyValue", "StringValue"); // value to store
// Commit to storage
editor.commit();
}
and get the data with that key in next Activity's onCreate as below:
SharedPreferences preferences = getSharedPreferences("sharedPrefs", 0);
String name= preferences.getString("YourStringKeyValue","");
try this,
public class DataStorage {
private static String KEY;
public static SharedPreferences savedSession;
public void saveID(Context context, String msessionid) {
// TODO Auto-generated method stub
Editor editor = context
.getSharedPreferences(KEY, Activity.MODE_PRIVATE).edit();
editor.putString("SESSION_UID", msessionid);
editor.commit();
}
public String getID(Context context) {
savedSession = context.getSharedPreferences(KEY, Activity.MODE_PRIVATE);
return savedSession.getString("SESSION_UID", "");
}
}
Edit:
DataStorage mdata = new DataStorage();
public void gotoNextAndSaveScore(View view) {
if(group.getCheckedRadioButtonId() != R.id.radio3){
mdata.saveId(Mainactivity.this,1);
}else{
mdata.saveId(Mainactivity.this,-1);
}
And then get value from NextActivity.
DataStorage mdata = new DataStorage();
mdata.getId(NextActivity.this);
You're using the wrong preference file, the getPreference function on Activity returns a file private to that Activity. You need to use the named file version- getSharedPreferences(name, mode)