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);
}
Related
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();
}
});
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();
}
}
I need to load and save a website and its language in sharedpreferences. When I exit and then open the app, saved website and language load. I have used various ways, but cant achieve it. There is String and int not compatible with each other. My simple code like this:
private SharedPreferences prefs;
private static final String SELECTED_ITEM = "SelectedItem";
private SharedPreferences.Editor sharedPrefEditor;
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
else if (id == R.id.web)
final CharSequence[] items={"English","Arabic","Russian"};
AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setTitle("Choose Website");
builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {}
});
builder.setSingleChoiceItems(items, getSelectedItem(), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
webView = (WebView) findViewById(R.id.webView);
int website=current_page;
if("English".equals(items[which]))
{
webView.loadUrl("https://english.com");
website=("https://english.com");
}
else if("Arabic".equals(items[which]))
{
webView.loadUrl("https://arabic.com");
website=("https://arabic.com");
}
else if("Russian".equals(items[which]))
{
webView.loadUrl("https://russian.com");
website=("https://russian.com");
}
saveSelectedItem(website);
}
});
builder.show();
}
private int getSelectedItem() {
if (prefs == null) {
prefs = PreferenceManager
.getDefaultSharedPreferences(this);
}
return prefs.getInt(SELECTED_ITEM, -1);
}
private void saveSelectedItem(int which) {
if (prefs == null) {
prefs = PreferenceManager
.getDefaultSharedPreferences(this);
}
sharedPrefEditor = prefs.edit();
sharedPrefEditor.putInt(SELECTED_ITEM, which);
sharedPrefEditor.commit();
}
Why are you setting a String to an int variable (website)
You should probably save the language as a preference (String). and then when you load up the app, read the language preference and determine the website from there.
something like below.
public String getWebsite(){
SharedPreferences prefs;
if (prefs == null) {
prefs = PreferenceManager
.getDefaultSharedPreferences(this);
}
String language = prefs.getString("Language", "English");
String website = "";
switch(language){
case "Russian":
website = "russian.com";
break;
default:
website = "english.com";
}
return website;
}
private void saveSelectedItem(String language) {
if (prefs == null) {
prefs = PreferenceManager
.getDefaultSharedPreferences(this);
}
sharedPrefEditor = prefs.edit();
sharedPrefEditor.putInt("language", language);
sharedPrefEditor.commit();
}
when you call save selected item, just pass in items[which] instead of which
in saveSelectedItem(website);
You are passing a string and the method requires int
private void saveSelectedItem(int which) {
if (prefs == null) {
prefs = PreferenceManager
.getDefaultSharedPreferences(this);
}
sharedPrefEditor = prefs.edit();
sharedPrefEditor.putInt(SELECTED_ITEM, which);
sharedPrefEditor.commit();
For saving your data in shared preferences
i recommend to use GSON
i recommend to make a class for example
public class WebsiteData
{
#SerializedName("lang")
#Expose
private String lang ;
#SerializedName("website")
#Expose
private String website;
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang= lang;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website= website;
}
}
When user select language create new object and set the language with the chosen language and the set the website with its corresponding value
Then Turn object into String by Gson Like following :
Gson gson = new Gson();
String dataToSave = gson.toJson(WebsiteData);
String loadedString = getUserData(context);
WebsiteData loadedData = gson.fromJson(loadedString, WebsiteData.class);
to save and load data use the following methods :
public void saveUserData(Context context, String data) {
SharedPreferences sharedpreferences;
sharedpreferences = context.getSharedPreferences(PREF, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(DATA_KEY, data);
editor.apply();
}
public String getUserData(Context context) {
SharedPreferences sharedpreferences = context.getSharedPreferences(PREF, Context.MODE_PRIVATE);
return sharedpreferences.getString(DATA_KEY, null);
}
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());
}
My Android app fails to display the shared preferences that I set in a different class.
Am I missing something in my code? I save them fine but they don't display in my main Activity. All I see is the default text when I run the app. I have tried all I can to no avail. I can't figure out where the problem is. Below are my code files:
1. MnsEditor.java
public class MnsEditor extends Activity {
private MsItem mnses;
private Button saveBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mns_editor);
Intent intent = this.getIntent();
mnses = new MsItem();
mnses.setStartKey(intent.getStringExtra("startKey"));
mnses.setStartDate(intent.getStringExtra("StartDate"));
mnses.setShiftKey(intent.getStringExtra("ShiftKey"));
mnses.setShift(intent.getStringExtra("Shift"));
mnses.setBKey(intent.getStringExtra("BKey"));
mnses.setB(intent.getStringExtra("B"));
mnses.setGKey(intent.getStringExtra("GKey"));
mnses.setG(intent.getStringExtra("G"));
mnses.setNxtKey(intent.getStringExtra("NxtKey"));
mnses.setNxt(intent.getStringExtra("Nxt"));
EditText ms = (EditText) findViewById(R.id.sdate);
ms.setText(mnses.getStartDate());
EditText sh = (EditText) findViewById(R.id.sDay);
sh.setText(mnses.getShift());
EditText bb = (EditText) findViewById(R.id.bB);
bb.setText(mnses.getB());
EditText bg = (EditText) findViewById(R.id.bG);
bg.setText(mnses.getG());
EditText nm = (EditText) findViewById(R.id.Nxt);
nm.setText(mnses.getNxt());
saveBtn = (Button) findViewById(R.id.savePrefs);
saveBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
saveAndFinish();
}
});
}
private void saveAndFinish() {
EditText mst = (EditText) findViewById(R.id.stDay);
String mnsesStart = mst.getText().toString();
EditText shi = (EditText) findViewById(R.id.ShiftDay);
String shift = shi.getText().toString();
EditText bb = (EditText) findViewById(R.id.bbB);
String bbb = b.getText().toString();
EditText gg = (EditText) findViewById(R.id.ggG);
String ggg = gg.getText().toString();
EditText nxt = (EditText) findViewById(R.id.Nxt);
String next = nxt.getText().toString();
Intent intent = new Intent();
intent.putExtra("startdatekey", mnses.getStartDate());
intent.putExtra("StartDate", mnsesStart);
intent.putExtra("ShiftKey", mnses.getShift());
intent.putExtra("Shift", shift);
intent.putExtra("BKey", mnses.getB());
intent.putExtra("B", bbb);
intent.putExtra("GKey", mnses.getG());
intent.putExtra("G", ggg);
intent.putExtra("NxtKey", mnses.getNxt());
intent.putExtra("Nxt", next);
setResult(RESULT_OK, intent);
finish();
}
}
2. MsDataSource.java
public class MsDataSource {
MsItem mnses;
private static final String MNS_PREFS = "mnsKEY";
public SharedPreferences mnsPrefs;
public static final String StartDate = "startKey";
public static final String Shift = "shiftKey";
public static final String B = "bKey";
public static final String G = "gKey";
public static final String Nxt = "nxtKey";
public MsDataSource(Context context) {
mnsPrefs = context.getSharedPreferences(MNS_PREFS, Context.MODE_PRIVATE);
}
public String getTheStartDate() {
String mnsstart = mensPrefs.getString(StartDate, "Not seen");
return mnsstart;
}
public String getTheShift() {
String shiftda = mensPrefs.getString(Ovulation, "no data");
return shiftda;
}
public String getTheBoy() {
String Bda = mensPrefs.getString(B, "not accessible");
return Bda;
}
public String getTheGirl() {
String Gda = mensPrefs.getString(G, "does not exist");
return Gda;
}
public String getTheNextMenses() {
String nxtmns = mensPrefs.getString(Nxt, "maybe later");
return nxtmns;
}
public boolean update(mnsesItem mns) {
SharedPreferences.Editor editor = mnsPrefs.edit();
editor.putString(mns.getStartKey(), mns.getStartDate());
editor.putString(mns.getShiftKey(), mns.getShift());
editor.putString(mns.getBKey(), mns.getB());
editor.putString(mns.getGKey(), mns.getG());
editor.putString(mns.getNxtKey(), mns.getNxt());
editor.commit();
return true;
}
}
3. Mst.java
public class Mst extends Activity {
private TextView startdate;
private TextView shiftday;
private TextView bday;
private TextView gday;
private TextView nextday;
public static final String StartDate = "startKey";
public static final String Shift = "shiftKey";
public static final String B = "bKey";
public static final String G = "gKey";
public static final String Nxt = "nxtKey";
private static final int EDITOR_ACTIVITY_REQUEST = 1001;
private MsDataSource datasource;
MsItem mnses;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mns_layout);
startdate = (TextView) findViewById(R.id.mnsstartd);
shiftday = (TextView) findViewById(R.id.shd);
bday = (TextView) findViewById(R.id.bbd);
gday = (TextView) findViewById(R.id.bgd);
nextday = (TextView) findViewById(R.id.nxtmnsd);
datasource = new MsDataSource(this);
refreshDisplay();
}
private void refreshDisplay() {
mnses = datasource.findAll();
startdate.setText(datasource.mnsPrefs.getString(StartDate, "not retrieved"));
shiftday.setText(datasource.mnsPrefs.getString(Shift, "unavailable"));
bday.setText(datasource.mnsPrefs.getString(B, "not seen"));
gday.setText(datasource.mnsPrefs.getString(G, "not found"));
nextday.setText(datasource.mnsPrefs.getString(Nxt, "no data"));
}
private void createMns() {
MsItem mns = MsItem.getNew();
Intent intent = new Intent(this, MnsEditor.class);
intent.putExtra("startKey", mns.getStartKey());
intent.putExtra("StartDate", mns.getStartDate());
intent.putExtra("shiftKey", mns.getShiftKey());
intent.putExtra("Shift", mns.getShift());
intent.putExtra("bKey", mns.getBKey());
intent.putExtra("B", mns.getB());
intent.putExtra("gKey", mns.getGKey());
intent.putExtra("G", mns.getG());
intent.putExtra("nxtKey", mns.getNxtKey());
intent.putExtra("Nxt", mns.getNxt());
startActivityForResult(intent, EDITOR_ACTIVITY_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == EDITOR_ACTIVITY_REQUEST && resultCode == RESULT_OK) {
MsItem mns = new MsItem();
mns.setStartKey(data.getStringExtra("startKey"));
mns.setStartDate(data.getStringExtra("StartDate"));
mns.setShiftKey(data.getStringExtra("shiftKey"));
mns.setShift(data.getStringExtra("Shift"));
mns.setBKey(data.getStringExtra("bKey"));
mns.setB(data.getStringExtra("B"));
mns.setGKey(data.getStringExtra("gKey"));
mns.setG(data.getStringExtra("G"));
mns.setNextmnsesKey(data.getStringExtra("nxtKey"));
mns.setNxt(data.getStringExtra("Nxt"));
datasource.update(mns);
refreshDisplay();
}
}
}
4. MsItem.java
#SuppressLint("SimpleDateFormat")
public class MsItem {
private String startKey;
private String StartDate;
private String shiftKey;
private String Shift;
private String bKey;
private String B;
private String gKey;
private String G;
private String nxtKey;
private String Nxt;
public String getStartKey() {
return startKey;
}
public void setStartKey(String startKey) {
this.startKey = startKey;
}
public String getStartDate() {
return StartDate;
}
public void setStartDate(String startDate) {
StartDate = startDate;
}
public String getShiftKey() {
return shiftKey;
}
public void setShiftKey(String shiftKey) {
this.shiftKey = shiftKey;
}
public String getShift() {
return Shift;
}
public void setShift(String shift) {
Shift = shift;
}
public String getbKey() {
return bKey;
}
public void setbKey(String bKey) {
this.bKey = bKey;
}
public String getB() {
return B;
}
public void setB(String b) {
B = b;
}
public String getgKey() {
return gKey;
}
public void setgKey(String gKey) {
this.gKey = gKey;
}
public String getG() {
return G;
}
public void setG(String g) {
G = g;
}
public String getNxtKey() {
return nxtKey;
}
public void setNxtKey(String nxtKey) {
this.nxtKey = nxtKey;
}
public String getNxt() {
return Nxt;
}
public void setNxt(String nxt) {
Nxt = nxt;
}
public static MsItem getNew(){
Locale locale = new Locale("en_US");
Locale.setDefault(locale);
String pattern = "yyyy-MM-dd HH:mm:ss Z";
SimpleDateFormat formatter = new SimpleDateFormat(pattern);
String startdatekey = formatter.format(new Date());
String skey = formatter.format(new Date());
String bkey = formatter.format(new Date());
String gkey = formatter.format(new Date());
String nkey = formatter.format(new Date());
MsItem mnses = new MsItem();
mnses.setStartKey(startdatekey);
mnses.setStartDate("");
mnses.setShiftKey(skey);
mnses.setShift("");
mnses.setbKey(bkey);
mnses.setB("");
mnses.setgKey(gkey);
mnses.setG("");
mnses.setNxtKey(nkey);
mnses.setNxt("");
return mnses;
}
}
Try this:
public String getStartDate(){
mnsPrefs = context.getSharedPreferences(StartDate, Context.MODE_PRIVATE);
String mnsstart = mnsPrefs.getString(StartDate, "");
return mnsstart;
}
public String getShift(){
mnsPrefs = context.getSharedPreferences(shift, Context.MODE_PRIVATE);
String shiftda = mnsPrefs.getString(Shift, "");
return shiftda;
}
its more readable
Use MODE_APPEND instead MODE_PRIVATE.
MODE_APPEND(File creation mode: for use with openFileOutput, if the file already exists then write data to the end of the existing file instead of erasing it).
SharedPreferences editor = context.getSharedPreferences(
"used_name", Context.MODE_APPEND);
editor.putString("username", value);
editor.commit();
One issue I can see is, that You are trying to get the sharedPreferences, but You are initializing the same object a few times inside Your MsDataSource.java class:
mnsPrefs = context.getSharedPreferences(StartDate, Context.MODE_PRIVATE);
mnsPrefs = context.getSharedPreferences(shift, Context.MODE_PRIVATE);
mnsPrefs = context.getSharedPreferences(B, Context.MODE_PRIVATE);
mnsPrefs = context.getSharedPreferences(G, Context.MODE_PRIVATE);
mnsPrefs = context.getSharedPreferences(Nxt, Context.MODE_PRIVATE);
So this will not work. For different sharedPref objects, You need to initialize them unique for example:
public SharedPreferences mnsPrefs1;
public SharedPreferences mnsPrefs2;
public SharedPreferences mnsPrefs3;
public SharedPreferences mnsPrefs4;
public SharedPreferences mnsPrefs5;
mnsPrefs1 = context.getSharedPreferences(StartDate, Context.MODE_PRIVATE);
mnsPrefs2 = context.getSharedPreferences(shift, Context.MODE_PRIVATE);
mnsPrefs3 = context.getSharedPreferences(B, Context.MODE_PRIVATE);
mnsPrefs4 = context.getSharedPreferences(G, Context.MODE_PRIVATE);
mnsPrefs5 = context.getSharedPreferences(Nxt, Context.MODE_PRIVATE);
but there must be more. I need to see Your code from MsItem.java class, I think, here You are saving the SharedPrefs, right?
EDIT
You don´t need to initialize so many SharedPreference objects, it´s enough to make only one and give it different keys for every value. For example:
private final String sharedPrefKey = "MY_KEY";
public MsDataSource(Context context) {
mnsPrefs = context.getSharedPreferences(sharedPrefKey, Context.MODE_PRIVATE);
}
and then update() method in MsDataSource.java should work. But by the way, I think Your initialization of Your MsItem in Your Mst.java class at onActivityResult is made in the wrong way, isn´t it? You wrote
MsItem mns = new MsItem();
But musn´t it be
MsItem mns = MsItem.getNew();
? Because with only new MsItem(), all the Strings and stuff are not initialized inside MsItem.