How to stop replacing previous entries in shared preferences? - java

My code used to replace the previous entries and I realized I needed to use different keys for storing in shared preferences. Now my code does not output anything in the listview. please help
Java code where I ask for information about the person (name, favcolor, favfood)
public class personInfo extends AppCompatActivity {
EditText editText_name;
EditText editText_favfood;
EditText editText_favcolor;
Button button_save;
static int count = 0;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_personinfo);
Log.d(MainActivity.class.getSimpleName(), "onCreate");
editText_name = (EditText) findViewById(R.id.editText_name);
editText_favcolor = (EditText) findViewById(R.id.editText_favcolor);
editText_favfood = (EditText) findViewById(R.id.editText_favfood);
button_save = (Button) findViewById(R.id.button_save);
button_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count++;
SharedPreferences sharedPreferences = getSharedPreferences("ENTRIES", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("name" + count, editText_name.getText().toString());
editor.putString("favcolor" + count, editText_favcolor.getText().toString());
editor.putString("favfood" + count, editText_favfood.getText().toString());
editor.apply();
editor.putInt("numOfEntries", count);
Intent it = new Intent(personInfo.this, listOfPeople.class);
startActivity(it);
}
});
}
}
Java code, page that is supposed to display the entries
public class listOfPeople extends AppCompatActivity {
ListView listView;
ArrayList<listEntry> list = new ArrayList<>();
listEntry le;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
listView = (ListView) findViewById(R.id.listView_persons);
SharedPreferences sharedPreferences = getSharedPreferences("ENTRIES", MODE_PRIVATE);
int count = sharedPreferences.getInt("numOfEntries", 0);
for(int i = 1; i <= count; i++){
String nameValue = sharedPreferences.getString("name" + i, "");
String favcolorValue = sharedPreferences.getString("favcolor" + i, "");
String favfoodValue = sharedPreferences.getString("favfood" + i, "");
le = new listEntry(nameValue, favcolorValue, favfoodValue);
list.add(le);
}
personListAdapter adapter = new personListAdapter(this, R.layout.entryrow, list);
listView.setAdapter(adapter);
}
}

You are applying (saving) preferences before putting count
editor.apply();
editor.putInt("numOfEntries", count);
Just put before applying
editor.putInt("numOfEntries", count);
editor.apply();

call editor.apply() after editor.putInt("numOfEntries", count);
editor.putInt("numOfEntries", count);
editor.apply();

Related

Android studio shared preferences highscore reset after restarting the app

I'm trying to get my app to save my highscore after I close the app and have tried some of the SharedPreference tutorials. But my highscore keeps resetting every time I restart the app. What am I doing wrong?
Edit: Blackapps helped me fix my code. It works now!
TextView RecordHigh2, RecordHigh2A;
static public int RecordHigh_i = 0;
static public int RecordHigh_A = 0;
public static final String myPrefsKey = "MyPrefsKey";
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_statistics);
sharedPreferences = getSharedPreferences(myPrefsKey, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
int A = sharedPreferences.getInt("test", -1);
if(sharedPreferences.getInt("Highscore", -1) < RecordHigh_i){
editor.putInt("Highscore", RecordHigh_i);
editor.commit();
} else{
RecordHigh_i = sharedPreferences.getInt("Highscore", -1);
}
if(sharedPreferences.getInt("HighscoreA", -1) < RecordHigh_A){
editor.putInt("HighscoreA", RecordHigh_A);
editor.commit();
} else{
RecordHigh_A = sharedPreferences.getInt("HighscoreA", -1);
}
RecordHigh2 = (TextView) findViewById(R.id.RecordHigh);
RecordHigh2.setText("Highscore: " + RecordHigh_i);
RecordHigh2A = (TextView) findViewById(R.id.RecordHighA);
RecordHigh2A.setText("Highscore Image: " + RecordHigh_A);
}
#Override
protected void onPause() {
super.onPause();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("Highscore", RecordHigh_i);
editor.commit();
};
};

How to save string sets to Shared Preferences

I have been able to save one entry to shared preferences and for it to display in a list view on another view but I am wanting to add multiple entries and them to display in the listview too. I thought I had the correct code but it doesn't see mto have changed anything. My intent is a favourites list, I take the entry data from one view and display it in another view.
SingleView Activity:
SharedPreferences.Editor fd;
SharedPreferences FeedPref;
private ArrayList<String> addArray = new ArrayList<>();
txt = (TextView) findViewById(R.id.name);
add = (Button) findViewById(R.id.btnAdd);
FeedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
fd = FeedPref.edit();
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String message = txt.getText().toString();
if (addArray.contains(message)) {
Toast.makeText((getBaseContext()), "Plant Already Added", Toast.LENGTH_LONG).show();
} else {
addArray.add(message);
FeedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
fd = FeedPref.edit();
fd.putInt("array_size", addArray.size());
for (int i = 0; i < addArray.size(); i++) {
fd.putString("Status_" + i, addArray.get(i));
}
fd.commit();
Toast.makeText((getBaseContext()), "Plant Added", Toast.LENGTH_LONG).show();
}
}
});
}
mygarden activity:
public class mygardenMain extends Activity {
//String[] presidents;
ListView listView;
//ArrayAdapter<String> adapter;
SharedPreferences FeedPref;
SharedPreferences.Editor fd;
//private ArrayList<String> addArray;
//public static final String PREFS = "examplePrefs";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mygarden_list);
listView = (ListView) findViewById(R.id.mygardenlist);
//addArray = new ArrayList<>();
FeedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
int size = FeedPref.getInt("array_size", 0);
for (int i = 0; i < size; i++) {
String mess = FeedPref.getString("Status_" + i, null);
String[] values = new String[]{mess};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values);
listView.setAdapter(adapter);
}
}
Set abc = new HashSet<>();
abc.add("john");
abc.add("test");
abc.add("again");
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putStringSet("key",abc);
editor.commit();
SingleView Activity:
SharedPreferences.Editor fd;
SharedPreferences FeedPref;
private ArrayList<String> addArray = new ArrayList<>();
txt = (TextView) findViewById(R.id.name);
add = (Button) findViewById(R.id.btnAdd);
FeedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
fd = FeedPref.edit();
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String message = txt.getText().toString();
if (addArray.contains(message)) {
Toast.makeText((getBaseContext()), "Plant Already Added", Toast.LENGTH_LONG).show();
} else {
FeedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
fd = FeedPref.edit();
Gson gson = new Gson();
String jsonText = Prefs.getString("key", "");
if(!jsonText.equals(""))
{
String[] text = gson.fromJson(jsonText, String[].class); //EDIT: gso to gson
if(text.length>0)
{
//addArray = Arrays.asList(text);
//addArray = new ArrayList(addArray);
List<String> addArrayNew = Arrays.asList(text);
addArray = new ArrayList(addArrayNew);
}
}
addArray.add(message);
gson = new Gson();
jsonText = gson.toJson(addArray );
prefsEditor.putString("key", jsonText);
prefsEditor.commit();
}
});
}
mygarden activity:
public class mygardenMain extends Activity {
//String[] presidents;
ListView listView;
//ArrayAdapter<String> adapter;
SharedPreferences FeedPref;
SharedPreferences.Editor fd;
//private ArrayList<String> addArray;
//public static final String PREFS = "examplePrefs";
String jsonText;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mygarden_list);
listView = (ListView) findViewById(R.id.mygardenlist);
//addArray = new ArrayList<>();
FeedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
int size = FeedPref.getInt("array_size", 0);
Gson gson = new Gson();
jsonText = FeedPref.getString("key", "");
if(!jsonText.equals(""))
{
String[] values= gson.fromJson(jsonText, String[].class);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values);
listView.setAdapter(adapter);
}
}

ArrayList of EditText to SharedPreferences

I develop an app for android.
I have a lot of variables of EditText type. I'd like to use a Button to save data which was entered by the user. The problem starts when I try to put every EditText one by one.
So I thought about using an ArrayList. I read that I can't put an ArrayList directly to SharedPreferences. But which way is better to do this? Use a Hash, serializable or one by one? I am a beginner so I don't know which way is better - it means more easy to use but longer.
In this case which I tried in one variable ("m" only) but when I click a Button to save this it goes out from app.
How can I improve this code to work correctly?
This is the code:
public class MainActivity extends ActionBarActivity {
public static final String MY_PREFS_NAME = "MyPrefsFile";
EditText m,m1,m2,m3,m00,m11,m22,m33;
Button button10;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText m = (EditText) findViewById(R.id.message);
final EditText m1 = (EditText) findViewById(R.id.message1);
final EditText m2 = (EditText) findViewById(R.id.message2);
final EditText m3 = (EditText) findViewById(R.id.message3);
final EditText m00 = (EditText) findViewById(R.id.message00);
final EditText m11 = (EditText) findViewById(R.id.message11);
final EditText m22 = (EditText) findViewById(R.id.message22);
final EditText m33 = (EditText) findViewById(R.id.message33);
List<EditText> messageLIST = new ArrayList<EditText>(){{
add(m);
add(m1);
add(m2);
add(m3);
add(m00);
add(m11);
add(m22);
add(m33);
}};
for(int i = 0; i < messageLIST.size(); i++)
{
messageLIST.get(i);
}
sharedPreferences = getApplication().getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String numberValue = sharedPreferences.getString("numberValue", null);
m.setText(numberValue);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void saveButton(View view)
{
Intent intent = new Intent(this,MainActivity.class);
m.getText().toString();
SharedPreferences sharedPreferences = getApplication().getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("numberValue", m.getText().toString());
editor.commit();
startActivity(intent);
}
}
I have no idea why you need to do this. You can just save comma seperated String for your all edit text values in preferenses.You dont need those lines ..
List<EditText> messageLIST = new ArrayList<EditText>(){{
add(m);
add(m1);
add(m2);
add(m3);
add(m00);
add(m11);
add(m22);
add(m33);
}};
for(int i = 0; i < messageLIST.size(); i++)
{
messageLIST.get(i);
}
Just do this
call getText.toString() on each edit text and append it by other value and then save it in a key to your preference
I would recommend you to create a Map<String, EditText>(). Add all your EditText's to the Map using put("Your key value", yourEditText). When you want to store it to SharedPreferences do this:
SharedPreferences sharedPreferences = getApplication().getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
for(Map.Entry<String, EditText> entry : map.entrySet()){
editor.putString(entry.getKey(), entry.getValue().getText().toString();
}
editor.commit();
In the for loop, you can create a json string and save it to the sharedprefs like;
public void saveToSharedPrefs(List<EditText> messageLIST) {
JSONArray jsonArrayParent = new JSONArray();
for (int i = 0; i < messageLIST.size(); i++) {
String str = messageLIST.get(i).getText().toString().trim();
try {
JSONObject jsonChid = new JSONObject();
jsonChid.put("key", str);
jsonArrayParent.put(jsonChid.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
SharedPreferences sharedPreferences = getApplication().getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("numberValue", jsonArrayParent.toString());
editor.commit();
}
and call this method in your saveButton method like
public void saveButton(View view) {
Intent intent = new Intent(this, MainActivity.class);
saveToSharedPrefs(messageLIST);
startActivity(intent);
}

Difficulty saving and storing

I am trying to save and store data in an android app using java. At the moment the data will not save and it causes my app to crash. Can anyone make any suggestions to my code? Part of my page includes a total budget and I am difficulty storing and saving the total budget.
public class Summary extends Activity implements TextWatcher, View.OnClickListener
{
DecimalFormat df = new DecimalFormat("£0.00");
int noOfGifts, giftsPurchased;
double cost;
EditText budgetEntered;
double savedBudget = 0;
String budgetString;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.summary);
budgetEntered = (EditText) findViewById(R.id.s2TotalBudget);
budgetEntered.addTextChangedListener(this);
Button saveBudget = (Button) findViewById(R.id.s2ViewList);
saveBudget.setOnClickListener(saveButtonListener);
if(savedBudget != 0)
{
saveBudget.setText(budgetString);
}
Bundle passedInfo = getIntent().getExtras();
if (passedInfo != null)
{
cost = passedInfo.getDouble("cost");
noOfGifts = passedInfo.getInt("noOfGifts");
giftsPurchased = passedInfo.getInt("giftsPurchased");
}
Button logoutButton = (Button) findViewById(R.id.s2LogoutButton);
logoutButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent myIntent = new Intent(Summary.this, MainActivity.class);
startActivity(myIntent);
}
});
Button viewList = (Button) findViewById(R.id.s2ViewList);
viewList.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent myIntent = new Intent(Summary.this, GiftList.class);
startActivity(myIntent);
}
});
String [][] summary = {{"Number of Presents to buy: ", (noOfGifts + "")},
{"Number of Presents bought:", (giftsPurchased + "")},
{"Cost: £", (cost + "")},
{"Budget: £", "50"}};
String passedBudget=null;
//convert totalPresents to double from String
String tempPresents = summary[0][1];
int presents = Integer.parseInt(tempPresents);
//convert presentsBought to double from String
String tempBought = summary[1][1];
int presentsToBuy = Integer.parseInt(tempBought);
//Number of presents
TextView s2PresentResult = (TextView) findViewById(R.id.s2PresentsResult);
s2PresentResult.setText(summary[0][1]);
//Number of presents to buy
TextView s2PresentsBuyResult = (TextView) findViewById(R.id.s2PresntsBuyResult);
s2PresentsBuyResult.setText((noOfGifts - giftsPurchased) + "");
Bundle passedId = getIntent().getExtras();
if (passedId != null)
{
passedBudget = passedId.getString("Enter Budget");
}
//EditText s2TotalBudget = (EditText) findViewById(R.id.s2TotalBudget);
//s2TotalBudget .addTextChangedListener((android.text.TextWatcher) this);
//s2TotalBudget .setText(passedBudget, TextView.BufferType.EDITABLE);
//Number of people
//TextView s2TotalBudget = (TextView) findViewById(R.id.s2TotalBudget);
//s2TotalBudget.setText("Enter budget");
//Number of people
TextView s2TotalCost = (TextView) findViewById(R.id.s2TotalCost);
s2TotalCost.setText(df.format(Double.parseDouble(summary[2][1])));
//Output if over or under budget
TextView s2CalculateOverBudget = (TextView) findViewById(R.id.s2CalculateOverBudget);
//convert totalCost to double from String
String temp = summary[2][1];
double totalCost = Double.parseDouble(temp);
//convert totalBudget to double from String
String tempTwo = "14";
double totalBudget = Double.parseDouble(tempTwo);
if((totalCost>totalBudget)&&(totalBudget!=0))
{
s2CalculateOverBudget.setTextColor(Color.rgb(209,0,0));
s2CalculateOverBudget.setText("You are over budget");
}
else if(totalBudget==0){
s2CalculateOverBudget.setText("");
}
else {
s2CalculateOverBudget.setText("You are within budget");
}
}
public View.OnClickListener saveButtonListener = new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(budgetEntered.getText().length()>0)
{
budgetString = budgetEntered.getText().toString();
}
}
};
public void onClick(View v)
{
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
}
#Override
public void afterTextChanged(Editable s)
{
this it the best way to store and load value in Android:
save values: (put this where you want to save the values, for example in the onStop or onPause method. Or, in your case, in the onClick method)
SharedPreferences settings = getSharedPreferences("MyPref", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("testValue", value);
editor.commit();
load values:
SharedPreferences settings = getSharedPreferences("MyPref", 0);
value = settings.getInt("testValue", defValue);

Remove item from SharedPreference list [android]

I want remove checked elements from my list, but not only from main app but from SharedPreferences also. Now, in my app i can remove chcecked elements but not from SharedPreferences, so if i come back to my activity all of removed elements are still visible. Please, help me.
This is my activity:
SharedPreferences preferences;
ArrayList<Object> list = new ArrayList<Object>();
ArrayAdapter<Object> adapter;
List<String> localization;
Button btnDelete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_moje_miejsca);
btnDelete = (Button) findViewById(R.id.btnDelete);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_multiple_choice, list);
preferences = getSharedPreferences("coordinates", Activity.MODE_PRIVATE);
Set<String> localizationSet = preferences.getStringSet("localization_set", new HashSet<String>());
localization = new ArrayList<>(localizationSet);
for (String listPosition : localizationSet) {
list.add(listPosition);
adapter.notifyDataSetChanged();
}
setListAdapter(adapter);
public void onClickBtnDelete(View view){
SharedPreferences.Editor editor = preferences.edit();
SparseBooleanArray checkedItemPositions = getListView().getCheckedItemPositions();
int itemCount = getListView().getCount();
for(int i = itemCount-1; i >= 0; i--){
if(checkedItemPositions.get(i)){
int position = i + 1;
adapter.remove(list.get(i));
}
}
editor.remove("localization_set").commit();
itemCount = getListView().getCount();
checkedItemPositions.clear();
adapter.notifyDataSetChanged();
for (int i = itemCount-1; i >= 0; i--){
localization.add((String) list.get(i));
setLocalization = new HashSet<String>(localization);
editor.putStringSet("localization_set", setLocalization).commit();
}
}
}
To remove a specific saved pref then use
SharedPreferences.Editor editor = settings.edit();
editor.remove("tag_to_delete");
editor.commit();
To remove all of your saved preferences then use this
SharedPreferences.Editor editor = settings.edit();
editor.clear();
editor.commit();
I found a problem. It's my mistake. I forgot clear a list and thats why the list duplicate itself. It's enough to add a localization.clear() method to solve this problem

Categories

Resources