How to save textfield response without clearing - java

I am trying to create a simple to do list style app. I have successfully saved the string using SharedPreferences, as I am able to refer to it in the Logs, but I would like to make it so that the string stays attached to the textfield instead of being cleared every time app is reopened (until changed or deleted by the user). Any other suggestions would be appreciated.
(MainActivity)
public void go(View view) {
Intent intent1 = new Intent(SecondActivity.this, myPreferences.class);
String passGoal1 = goal1.getText().toString();
intent1.putExtra("goal1", passGoal1);
startActivity(intent1);
}
Also implemented myPreferences class as referenced in the first answer.
public class myPreferences {
private SharedPreferences pref;
private SharedPreferences.Editor editor;
private Context context;
int PRIVATE_MODE = 0;
private static final String PREF_NAME = "MyPreferencesName";
public final static String KEY_NAME = "key_value";
public myPreferences(Context context) {
this.context = context;
pref = context.getSharedPreferences(PREF_NAME,PRIVATE_MODE);
editor = pref.edit();
}
public void setFunction(String data) {
editor.putString(KEY_NAME, data);
}
}

In your shared preferences make a get function that fetch the stored data and view it every time in textfield
public class MyPreferences {
private SharedPreferences pref;
// Editor for Shared preferences
private SharedPreferences.Editor editor;
// Context
private Context context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "MyPreferencesName";
public final static String KEY_NAME = "key_value";
public MyPreferences(Context context) {
this.context = context;
pref = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void setFunction(String data) {
editor.putString(KEY_NAME, data);
editor.commit();
}
public String getFunction() {
return pref.getString(KEY_NAME, "");
}
}
And in your activity initialize SharedPreferences and do the following:
private MyPreferences myPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myPreferences = new MyPreferences(this);
//To set EditText data from SavedPreferences
textField.setText(myPreferences.getFunction());
}
//To save the latest data from EditText.
#Override
protected void onStop() {
Log.d("LifeCycle", "onStop: ");
super.onStop();
myPreferences.setFunction(editText.getText().toString());
}

Related

How to use sharedPrefrence putString?

I want to use sharedprefrence string form another activity but the value is not being passed it always passes the default value?
Creation of variable toast Shows inp value but value is not being passed
name_next = (Button) findViewById(R.id.name_next);
sp= getSharedPreferences("name_pref",Context.MODE_PRIVATE);
name_next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
inp = nameInput.getText().toString();
SharedPreferences.Editor editor= sp.edit();
editor.putString(inp,nameInput);
editor.commit();
Toast.makeText(com.calmo.name.this,"welcome "+inp,Toast.LENGTH_LONG).show();
Intent intent = new Intent(name.this,MainActivity.class);
startActivity(intent);
}
});```
**Calling **
**The Value is always returned as error that is default**
``` SharedPreferences sp=getApplicationContext().getSharedPreferences("name_pref",Context.MODE_PRIVATE);
String name_in =sp.getString("inp","Error");
name.setText(name_in);
public class AppSharedPreferences {
public static final String TAG = "AppSharedPreferences";
private static SharedPreferences sharedPref;
private String demo_string = "demo string's key"
public AppSharedPreferences() {
}
public static void init(Context context)
{
if(sharedPref == null)
sharedPref = context.getSharedPreferences(
context.getPackageName(), Activity.MODE_PRIVATE);
}
public static void setDemoString(String demoString) {
Editor prefs = sharedPref.edit();
prefs.putString(demo_string, demoString);
prefs.apply();
}
public static String getDemoString() {
return sharedPref.getString(demo_string, "");
}}
Put this wherever u want to use shared prefs:
AppSharedPreferences.init(this);
You can exchange this for activity or context, depending on where you use the code.
To set value in preference, use this code:
AppSharedPreferences.setDemoString("Some Text");
To get the value from preference:
String text = AppSharedPreferences.getDemoString();
Remove
inp = nameInput.getText().toString();
under onclick
and change
editor.putString(inp,nameInput);
to
editor.putString("inp",nameInput.getText().toString());

How to save a model with SharedPreferences?

I've got class to add some variables inside it.
I've created an object from it.
Then i've added some value to it.
The problem now is, i don't know how to add it inside.
SharedPreferences
i want to edit the code so i can add it without problems.
// class : MainActivity
public class MainActivity extends AppCompatActivity {
Times times;
public static Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.context = context;
times = new Times(5,30);
// setInt(times);
}
public final static String PREFS_NAME = "appname_prefs";
public static void setInt(String key, int value) {
SharedPreferences sharedPref = context.getSharedPreferences(PREFS_NAME ,0);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(key, value);
editor.apply();
}
public static int getInt(String key) {
SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, context.MODE_PRIVATE);
return prefs.getInt(key , 0);
}
}
// class Times:
public class Times{
int Houre;
int Minute;
public Times(int houre, int minute){
Houre = houre;
Minute = minute;
}
public void setHoure(int houre){
Houre = houre;
}
public void setMinute(int minute){
Minute = minute;
}
public int getHoure(){
return Houre;
}
public int getMinute(){
return Minute;
}
}
Just add editor.commit(); delete editor.apply();
you can read explanation on shared prefs here
https://www.tutorialspoint.com/android/android_shared_preferences.htm
Ohad is correct. SharedPreferences only store primitive types like Int and String. In this case you would have to store each value as its own SharedPreference.
If your data is more complex than what SharedPreferences can handle, consider storing it in a Room database.

how to save changes using SharedPreferences?

I'm working on an application and I have to save changes made by the user ... the user going to click on an image, it's going to change the color. And I want to save that change.
I'm not sure how to do that actually. Here is where I want to make the change.
All I know is I need to use SharedPreferences .
private ImageView bookmark;
bookmark = (ImageView) findViewById(R.id.imageView_bookmark_readIt);
bookmark.setOnClickListener(new View.OnClickListener(){
private boolean bookmarking = true;
public void onClick(View v){
if(bookmarking){
bookmark.setImageResource(R.drawable.ic_bookmarked_blue);
bookmarking=false;
}
else{
bookmarking=true;
bookmark.setImageResource(R.drawable.ic_bookmark);
//Toast.makeText(getApplicationContext(), "Changed", Toast.LENGTH_LONG).show();
}
});
So does anybody have an idea of how to save changes made to the above code?
Note : I'm not using database
In shared preferences data is stored in the “key-value” format. As far as I understand, you need to save two fields and it will be something like this:
“booking: true”
“bookmarkImageResource: 15670341274”
Here is a convenient way to do it:
Step one – create a new class SharedPrefs:
public class SharedPrefs {
private static final String SHARED_PREFERENCES_NAME = "user_prefs";
private static final String BOOKING_INFO = "booking";
private static final String BOOKMARK_IMAGE_RESOURCE_INFO = "bookmarkImageResource";
private final SharedPreferences prefs;
public SharedPrefs(Context context) {
prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
}
public boolean saveBookingInfo(String bookingInfo, String bookmarkImageResource) {
return prefs.edit()
.putString(BOOKING_INFO, bookingInfo)
.putString(BOOKMARK_IMAGE_RESOURCE_INFO, bookmarkImageResource)
.commit();
}
public Pair<String, String> getBookingInfo() {
return new Pair<String, String>(
prefs.getString(BOOKING_INFO, ""),
prefs.getString(BOOKMARK_IMAGE_RESOURCE_INFO, ""));
}
public void clearAll() {
prefs.edit().clear().apply();
}
}
Step two - use your class wherever you need to save, get or clear data!
In you case:
SharedPrefs prefs = new SharedPrefs(this); // or getActivity() instead of this if we are in a fragment
if(bookmarking){
bookmark.setImageResource(R.drawable.ic_bookmarked_blue);
bookmarking=false;
}
else{
bookmarking=true;
bookmark.setImageResource(R.drawable.ic_bookmark);
}
prefs.saveBookingInfo(String.valueOf(bookmarking), String.valueOf(bookmark));
Hope this will help you =)
Have a good day & happy coding!
/**
* Get a shared preferences file named Const.SHARED_PREFERENCES_FILE_NAME, keys added to it must be unique
*
* #param ctx
* #return the shared preferences
*/
public static SharedPreferences getSharedPreferences(Context ctx) {
return ctx.getSharedPreferences(Const.SHARED_PREFERENCES_FILE_NAME, Context.MODE_PRIVATE);
}
public static void cacheBoolean(Context ctx, String k, Boolean v) {
SharedPreferences prefs = getSharedPreferences(ctx);
prefs.edit().putBoolean(k, v).apply();
}
public static Boolean getCachedBoolean(Context ctx, String k, Boolean defaultValue) {
SharedPreferences prefs = getSharedPreferences(ctx);
return prefs.getBoolean(k, defaultValue);
}
public static void cacheString(Context ctx, String k, String v) {
SharedPreferences prefs = getSharedPreferences(ctx);
prefs.edit().putString(k, v).apply();
}
public static String getCachedString(Context ctx, String k, String defaultValue) {
SharedPreferences prefs = getSharedPreferences(ctx);
return prefs.getString(k, defaultValue);
}
public static void cacheInt(Context ctx, String k, int v) {
SharedPreferences prefs = getSharedPreferences(ctx);
prefs.edit().putInt(k, v).apply();
}
public static int getCachedInt(Context ctx, String k, int defaultValue) {
SharedPreferences prefs = getSharedPreferences(ctx);
return prefs.getInt(k, defaultValue);
}
public static void clearCachedKey(Context context, String key) {
getSharedPreferences(context).edit().remove(key).apply();
}
Using SharedPreferences is very easy. You need to define a key which you will use to retrieve the data later. You can store Strings, ints, floats, booleans... You need to provide the context.
Context context = getApplicationContext();
To write data, use this code.
SharedPreferences mPrefs = context.getSharedPreferences("YourApp", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("color", "blue");
editor.apply();
To retrieve data, use this
SharedPreferences mPrefs = context.getSharedPreferences("YourApp", Context.MODE_PRIVATE);
String color = mPrefs.getString("color", "defaultValue");
You can easily change the type from String to other types that might best suit your needs.
Hope it helps.
Hope its help you
SharedPreferences sharedPrefs = getSharedPreferences("SharedPreferences_Name", Context.MODE_PRIVATE);
private ImageView bookmark;
bookmark = (ImageView) findViewById(R.id.imageView_bookmark_readIt);
private boolean bookmarking = sharedPrefs.getBoolean("bookmarking",true);//To get value that saved in SharedPreferences
if(bookmarking){
bookmark.setImageResource(R.drawable.ic_bookmarked_blue);
}
else{
bookmark.setImageResource(R.drawable.ic_bookmark);
//Toast.makeText(getApplicationContext(), "Changed", Toast.LENGTH_LONG).show();
}
bookmark.setOnClickListener(new View.OnClickListener(){
// private boolean bookmarking = true;
public void onClick(View v){
if(bookmarking){
bookmark.setImageResource(R.drawable.ic_bookmarked_blue);
bookmarking=false;
SharedPreferences.Editor editor = getSharedPreferences("SharedPreferences_Name", 0).edit();
editor.putBoolean("bookmarking", bookmarking);
editor.apply();
}
else{
bookmarking=true;
bookmark.setImageResource(R.drawable.ic_bookmark);
//Toast.makeText(getApplicationContext(), "Changed", Toast.LENGTH_LONG).show();
SharedPreferences.Editor editor = getSharedPreferences("SharedPreferences_Name", 0).edit();
editor.putBoolean("bookmarking", bookmarking);
editor.apply();
}
});

sharedpreferences why doesn't return any values

I using sharedPrefrence in my app but it's not return any value
this is code :
public class SharedPrefManager {
public final String MY_PREFS_NAME = "name";
private Context context;
SharedPreferences sp;
public SharedPrefManager(Context context){
this.context = context;
sp = context.getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
Log.d(TAG, "database is created");
}
public void saveInfoUser(String username ,int numRow){
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
editor.putString("username", username);
editor.putInt("numberRow",numRow);
editor.commit();
}
public String getUsename(){
String username = sp.getString("username","");
return username;
}
public void logout(){
sp.edit().clear().commit();
}
}
but when call method getUsename() return "" and not return values
this is place of called method :
enter image description here
Make sure you are using the same shared preference for saving as you are retrieving.
Your read is using private shared pref by key MY_PREFS_NAME
but your write is using default shared pref with no key.
The critical part of the code is this:
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
That line of code should be this:
SharedPreferences.Editor editor = sp.edit();
Once you obtain the SharedPreferences object in your class constructor you should use it to create the editor.
public class SharedPrefManager {
public final String MY_PREFS_NAME = "name";
private final String MY_PREFS_USERNAME = "username";
private final String MY_PREFS_NUMBER_ROW = "numberRow";
SharedPreferences sp;
public SharedPrefManager(Context context){
sp = context.getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
Log.d(TAG, "database is created");
}
public void saveInfoUser(String username ,int numRow){
SharedPreferences.Editor editor = sp.edit();
editor.putString(MY_PREFS_USERNAME , username);
editor.putInt(MY_PREFS_NUMBER_ROW ,numRow);
editor.commit();
}
public String getUsename(){
String username = sp.getString(MY_PREFS_USERNAME ,"");
return username;
}
public void logout(){
sp.edit().clear().commit();
}
}

set text on multiple edit text box if the text is null

I have created some editText box in my activity it's like an Update form and all I am trying to do now is to set random value to all the check box whichever is left blank while hitting the submit button. what I am getting is... getting value in only ETname edittext box and if I am clicking on submit button again my app is crashing and even if I am giving any value by myself to ETname and submitting it my app is crashing. please help.
public class User_Profile extends AppCompatActivity implements View.OnClickListener {
private Button Update;
private Context aContext;
private EditText ETname, ETsurname, ETadd, ETpin, ETmail, ETph;
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_userprofile);
ETname = (EditText)findViewById(R.id.edit_name);
ETsurname = (EditText)findViewById(R.id.edit_sur);
ETadd = (EditText)findViewById(R.id.edit_add);
ETpin = (EditText)findViewById(R.id.edit_pn);
ETmail = (EditText)findViewById(R.id.edit_mail);
ETph = (EditText)findViewById(R.id.edit_ph);
Update = (Button)findViewById(R.id.update_btn);
progressDialog = new ProgressDialog(this);
Update.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.update_btn:
proUpdate();
break;
}
}
private void proUpdate(){
if (ETname.getText().toString().trim().equals("")){
ETname.setText(SharedPrefManager.getInstance(this).getName());
}
if (ETsurname.getText().toString().trim().equals("")){
ETsurname.setText(SharedPrefManager.getInstance(this).getSurname());
}
if (ETadd.getText().toString().trim().equals("")){
ETadd.setText(SharedPrefManager.getInstance(this).getAddress());
}
if (ETpin.getText().toString().trim().equals("")){
String pin = String.valueOf(SharedPrefManager.getInstance(this).getpin());
ETpin.setText(pin);
}
if (ETmail.getText().toString().trim().equals("")){
ETmail.setText(SharedPrefManager.getInstance(this).getUserEmail());
}
if (ETph.getText().toString().equals("")){
ETph.setText(SharedPrefManager.getInstance(this).getUserPhone());
}
String reg_name = ETname.getText().toString().trim();
String reg_surname = ETsurname.getText().toString().trim();
String reg_address = ETadd.getText().toString().trim();
String reg_pin = ETpin.getText().toString().trim();
String reg_mail = ETmail.getText().toString().trim();
String reg_phone = ETph.getText().toString().trim();
String old_mail = (SharedPrefManager.getInstance(this).getUserEmail());
int reg_id = (SharedPrefManager.getInstance(this).getid());
}
}
My SharedPrefManager
public class SharedPrefManager {
private static SharedPrefManager mInstance;
private static Context mCtx;
private static final String SHARED_PREF_NAME = "mysharedpref12";
private static final String KEY_USERNAME = "username";
private static final String KEY_USER_MAIL = "usermail";
private static final String KEY_USER_ID = "userid";
private static final String KEY_PHONE = "userphone";
private static final String KEY_NAME = "usename";
private static final String KEY_PIN = "pin";
private static final String KEY_SUR = "surname";
private static final String KEY_ADD = "address";
private SharedPrefManager(Context context) {
mCtx = context;
}
public static synchronized SharedPrefManager getInstance(Context context) {
if (mInstance == null) {
mInstance = new SharedPrefManager(context);
}
return mInstance;
}
public boolean userLogin(int id, int pin, String phone, String username, String mail, String name, String surname, String address/**, String catagory*/){
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(KEY_USER_ID, id);
editor.putInt(KEY_PIN, pin);
editor.putString(KEY_PHONE, phone);
editor.putString(KEY_USERNAME, username);
editor.putString(KEY_USER_MAIL, mail);
editor.putString(KEY_NAME, name);
editor.putString(KEY_SUR, surname);
editor.putString(KEY_ADD, address);
//editor.putString(KEY_CATA, catagory);
editor.apply();
return true;
}
public boolean isLoggedIn(){
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
if (sharedPreferences.getString(KEY_USERNAME, null) != null){
return true;
}
return false;
}
public boolean logOut(){
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
return true;
}
public int getid(){
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getInt(KEY_USER_ID, Integer.parseInt(null));
}
public int getpin(){
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getInt(KEY_PIN, Integer.parseInt(null));
}
public String getUsername(){
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(KEY_USERNAME, null);
}
public String getUserEmail(){
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(KEY_USER_MAIL, null);
}
public String getUserPhone(){
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(KEY_PHONE, null);
}
public String getName() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(KEY_NAME, null);
}
public String getSurname() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(KEY_SUR, null);
}
public String getAddress() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(KEY_ADD, null);
}
/**public String getcatagory() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(KEY_CATA, null);
}*/
}
Here's the code sample of what I was telling you.
private void proUpdate(){
...
else if (ETpin.getText().toString().equals("")){
string pin = String.valueOf(SharedPrefManager.getInstance(this).getpin());
ETpin.setText(pin);
}
...
}
For checking and placing text in all edittext at once:
private void proUpdate(){
if (ETname.getText().toString().trim().equals("")){
ETname.setText(SharedPrefManager.getInstance(this).getName());
}
if (ETsurname.getText().toString().trim().equals("")){
ETsurname.setText(SharedPrefManager.getInstance(this).getSurname());
}
if (ETadd.getText().toString().trim().equals("")){
ETadd.setText(SharedPrefManager.getInstance(this).getAddress());
}
if (ETph.getText().toString().equals("")){
ETph.setText(SharedPrefManager.getInstance(this).getUserPhone());
}
if (ETmail.getText().toString().trim().equals("")){
ETmail.setText(SharedPrefManager.getInstance(this).getUserEmail());
}
if (ETpin.getText().toString().equals("")){
string pin = String.valueOf(SharedPrefManager.getInstance(this).getpin());
ETpin.setText(pin);
}
updateMethodCall(); // your method call
}
This updateMethod will only be called when all the ediitexts are filled and you need not click submit button again.
Change following methods a bit like this.
public int getid(){
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getInt(KEY_USER_ID, 0);
}
public int getpin(){
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getInt(KEY_PIN,0);
}

Categories