How to store and retrieve the date using shared preferences? - android

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");

Related

SharedPreferences never get key default value

This is my code:
package com.example.scheda_ais;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.io.File;
public class MainActivity extends AppCompatActivity {
EditText degustatore;
Button completa;
SharedPreferences sharedPref;
String generalita;
String appoggio;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPref = this.getSharedPreferences("il_sottoscritto",Context.MODE_PRIVATE);
degustatore = findViewById(R.id.degustatore);
completa = findViewById(R.id.completa);
completa.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
generalita = degustatore.getText().toString();
if(generalita != ""){
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("generalita", generalita);
editor.commit();
}
appoggio = sharedPref.getString("generalita", "vuoto");
Log.d("generalita", appoggio);
}
});
}
When I press the Button with an empty EditText (no input at all), nothing is printed by Log, while Log should print "generalita" + "vuoto".
Why String appoggio is empty?
If I input something in EditText, Log prints correctly "generalita" + appoggio.
Please someone help me. Thanks.
By using != to compare your string you are comparing "object instance" but "" and generalita string is not the same object so you are entering in the if and put "" to your preference so the preference is not null when you log it and the default value is not print.
that's what appens:
sharedPref = this.getSharedPreferences("il_sottoscritto",Context.MODE_PRIVATE);
degustatore = findViewById(R.id.degustatore);
completa = findViewById(R.id.completa);
completa.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
generalita = degustatore.getText().toString();
// generalita instance and "" intance are not equal so the trest will pass
if(generalita != ""){
SharedPreferences.Editor editor = sharedPref.edit();
// here you're putting "" to your preference
editor.putString("generalita", generalita);
editor.commit();
}
// sharedPref.getString("generalita", "vuoto") return ""
appoggio = sharedPref.getString("generalita", "vuoto");
Log.d("generalita", appoggio);
}
});
you should do like that
completa.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
generalita = degustatore.getText().toString();
if(!generalita.equals("")){
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("generalita", generalita);
editor.commit();
}
appoggio = sharedPref.getString("generalita", "vuoto");
Log.d("generalita", appoggio);
}
});
change this appoggio = sharedPref.getString("generalita", "vuoto");
to appoggio = sharedPref.getString("generalita", "");
There are two issues with what you wrote.
As #SebastienRieu said correctly
the first one , you can't do == for Strings in java.
You need to write:
if(!"".equals(generalita)){
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("generalita", generalita);
editor.commit();
}
And the 2nd one, you said you were expecting "generalita" + "vuoto"
However in this code:
appoggio = sharedPref.getString("generalita", "vuoto");
Log.d("generalita", appoggio);
in the Log the first word "generalita" is not text printed in the log, but rather a TAG that is filterable. If you want to see "generalita vuoto", then you'd have to put both on the right side.
Replace generalita != "", by !generalita.isEmpty() to check the length of your String.

why checkboxpreference is a null object preference

I have problem where received null object reference at uncheckAll() method inside HomeActivity class. But the problem is I already reference both object ( checkboxPreferenceEvent and checkBoxPreferenceQuote ) inside MyPreferenceActivity class. Hope you guys can help me solve this problem.
Thanks..
checkBoxPreferenceEvent = checkBoxPreferenceArrayList.get(0);
checkBoxPreferenceQuote = checkBoxPreferenceArrayList.get(1);
ERROR
E/InputEventReceiver: Exception dispatching input event.
E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback
E/MessageQueue-JNI: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.preference.CheckBoxPreference.setChecked(boolean)' on a null object reference
at com.example.user.uniselic.MyPreferencesActivity.uncheckAll(MyPreferencesActivity.java:51)
at com.example.user.uniselic.HomeActivity.onOptionsItemSelected(HomeActivity.java:193)
at android.app.Activity.onMenuItemSelected(Activity.java:2928)
at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:406)
at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:195)
at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:103)
MyPreferencesActivity.java
package com.example.user.uniselic;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceScreen;
import android.preference.TwoStatePreference;
import android.util.Log;
import android.widget.Toast;
import com.google.firebase.messaging.FirebaseMessaging;
import java.util.ArrayList;
/**
* Created by User on 11/1/2016.
*/
public class MyPreferencesActivity extends PreferenceActivity{
ArrayList<CheckBoxPreference> checkBoxPreferenceArrayList;
CheckBoxPreference checkBoxPreferenceQuote;
CheckBoxPreference checkBoxPreferenceEvent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyPreferenceFragment myPreferenceFragment = new MyPreferenceFragment();
getFragmentManager().beginTransaction().replace(android.R.id.content,myPreferenceFragment).commit();
checkBoxPreferenceArrayList = myPreferenceFragment.getCheckBoxPreferenceArrayListInner();
if(!checkBoxPreferenceArrayList.isEmpty()){
checkBoxPreferenceEvent = checkBoxPreferenceArrayList.get(0);
checkBoxPreferenceQuote = checkBoxPreferenceArrayList.get(1);
Toast.makeText(MyPreferencesActivity.this,"size arraylist:"+checkBoxPreferenceArrayList.size(),Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MyPreferencesActivity.this,"listview is empty",Toast.LENGTH_SHORT).show();
}
}
public void uncheckAll(){
Log.d("testing","calling uncheckAll method");
checkBoxPreferenceEvent.setChecked(false);
checkBoxPreferenceQuote.setChecked(false);
}
public class MyPreferenceFragment extends PreferenceFragment{
CheckBoxPreference checkBoxPreferenceEvent;
CheckBoxPreference checkBoxPreferenceQuote;
ArrayList<CheckBoxPreference> checkBoxPreferenceArrayListInner = new ArrayList<>();
public MyPreferenceFragment(){
checkBoxPreferenceArrayListInner.add(checkBoxPreferenceEvent);
checkBoxPreferenceArrayListInner.add(checkBoxPreferenceQuote);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
//initialize checkbox preferences.
checkBoxPreferenceEvent = (CheckBoxPreference) findPreference("applicationUpdatesEvent");
checkBoxPreferenceQuote = (CheckBoxPreference) findPreference("applicationUpdatesQuote");
//listener for checkbox event
checkBoxPreferenceEvent.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
PreferenceScreen preferenceScreen = getPreferenceScreen();
if(((CheckBoxPreference)preferenceScreen.findPreference("applicationUpdatesEvent")).isChecked()){
//initalize sharepreferences
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(ConfigBundle.SETTING, Context.MODE_PRIVATE);
//set value on shareprefenrence.
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(ConfigBundle.SETTING_NOTIFICATION_EVENT,true);
editor.commit();
FirebaseMessaging.getInstance().subscribeToTopic("event");
Toast.makeText(getActivity(),"Event Notification Enable",Toast.LENGTH_LONG).show();
return true;
}else{
//initalize sharepreferences
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(ConfigBundle.SETTING, Context.MODE_PRIVATE);
//set value on shareprefenrence.
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(ConfigBundle.SETTING_NOTIFICATION_EVENT,false);
editor.commit();
FirebaseMessaging.getInstance().unsubscribeFromTopic("event");
Toast.makeText(getActivity(),"Event Notification Disable",Toast.LENGTH_LONG).show();
return false;
}
}
});
//listener for checkbox quote
checkBoxPreferenceQuote.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
PreferenceScreen preferenceScreen = getPreferenceScreen();
if(((CheckBoxPreference)preferenceScreen.findPreference("applicationUpdatesQuote")).isChecked()){
//initalize sharepreferences
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(ConfigBundle.SETTING, Context.MODE_PRIVATE);
//set value on shareprefenrence.
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(ConfigBundle.SETTING_NOTIFICATION_QUOTE,true);
editor.commit();
FirebaseMessaging.getInstance().subscribeToTopic("quote");
Toast.makeText(getActivity(),"Quote Notification Enable",Toast.LENGTH_SHORT).show();
return true;
}else{
//initalize sharepreferences
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(ConfigBundle.SETTING, Context.MODE_PRIVATE);
//set value on shareprefenrence.
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(ConfigBundle.SETTING_NOTIFICATION_QUOTE,false);
editor.commit();
FirebaseMessaging.getInstance().unsubscribeFromTopic("quote");
Toast.makeText(getActivity(),"Quote Notification Disable",Toast.LENGTH_SHORT).show();
return false;
}
}
});
}
//get arraylist that contain checkboxpreference
public ArrayList<CheckBoxPreference> getCheckBoxPreferenceArrayListInner(){
return checkBoxPreferenceArrayListInner;
}
}
}
HomeActivity.java
/*To make our option menu active,ovveride this method
so that we can add function fo each option menu that been created */
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.menu_1:
Intent intent = new Intent(HomeActivity.this,ContactActivity.class);
startActivity(intent);
break;
case R.id.menu_2:
Intent intent2 = new Intent(HomeActivity.this,MyPreferencesActivity.class);
startActivity(intent2);
break;
case R.id.menu_3:
//remove all information user from sharepreference.
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(ConfigBundle.SETTING, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(ConfigBundle.SETTING_FIRST_TIME,true);
editor.putString(ConfigBundle.SETTING_ID,"");
editor.putString(ConfigBundle.SETTING_EMAIL,"");
editor.putString(ConfigBundle.SETTING_USERNAME,"");
editor.putBoolean(ConfigBundle.SETTING_NOTIFICATION_EVENT,false);
editor.putBoolean(ConfigBundle.SETTING_NOTIFICATION_QUOTE,false);
editor.commit();
MyPreferencesActivity myPreferencesActivity = new MyPreferencesActivity();
myPreferencesActivity.uncheckAll();
FirebaseMessaging.getInstance().unsubscribeFromTopic("event");
FirebaseMessaging.getInstance().unsubscribeFromTopic("quote");
FirebaseMessaging.getInstance().unsubscribeFromTopic("news");
//then go to main login activity content.
Intent intent3 = new Intent(HomeActivity.this,LoginActivity.class);
startActivity(intent3);
}
return super.onOptionsItemSelected(item);
}
Seems that your Activity does not have a ContentView to init.:
setContentView(R.layout.your_view);

How can I set save and load a password with sharedPreference?

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);

Declaring SharedPreferences.Editor crashes my app

// 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

Saving values at exit of an application

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.

Categories

Resources