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
Related
I am developing an application which has some switch buttons, which have SharedPreferences so that when the application is closed and reopened, the previously activated buttons remain so.
SharedPreferences in the MainActivity class:
private Spinner spipol;
private Switch quim, fil, fis, tri, esp, engl, inf, eti, reli, est, pol, dib, edf, mate;
private SharedPreferences sharedPreferences, sharfil, sharquim, shardfis, shartrig, sharesp, sharemater, sharing, sharinf, shareti, sharrel, sharest, sharpol, sharedf;
public static final String ex1 = "switch1";
public static final String ex = "switch";
dib = (Switch) findViewById(R.id.switch1);
sharedPreferences = getSharedPreferences("dib", MODE_PRIVATE);
final SharedPreferences.Editor editor = sharedPreferences.edit();
dib.setChecked(sharedPreferences.getBoolean(ex, false));
dib.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
editor.putBoolean(ex, true);
} else {
editor.putBoolean(ex, false);
}
editor.commit();
}
});
What I need is to know how I can do something similar to what I have with the switch buttons, but with my spinner:
spipol = (Spinner) findViewById (R.id.spipol);
String [] options = {"", "Short assignment", "Workshop", "Study", "Questions", "Review"};
ArrayAdapter <String> adapter = new ArrayAdapter <String> (this, android.R.layout.simple_spinner_dropdown_item, options);
spipol.setAdapter (adapter);
}
I searched the internet for how to do it, but in all the places I saw, they used a save button, what I would like to know is if I can do this without the need to implement this button.
I tried this but it didn't work:
spipol.setOnItemSelectedListener (new AdapterView.OnItemSelectedListener () {
#Override
public void onItemSelected (AdapterView <?> parent, View view, int position, long id) {
CaptureSpinner = (String) parent.getItemAtPosition (position);
index = position;
System.out.println ("Index:" + index);
}
#Override
public void onNothingSelected (AdapterView <?> parent) {
}
});
}
public void savePreference (Context context, int index) {
SharedPreferences sharpref = getPreferences (getApplicationContext (). MODE_PRIVATE);
SharedPreferences.Editor editor = sharpref.edit ();
editor.putInt ("Data", index);
System.out.println ("Index:" + index);
editor.apply ();
}
}
First you need to change the savePreference() to the code below. you don't need to pass a Context or position. you can get the item selected directly from your Spinner to be able to call this method on onStop()
public void savePreference() {
SharedPreferences sharpref = getSharedPreferences("Spinner", MODE_PRIVATE);
SharedPreferences.Editor editor = sharpref.edit();
editor.putInt("Data", spipol.getSelectedItemPosition());
System.out.println("Index:" + spipol.getSelectedItemPosition());
editor.apply();
}
Call the mothod above in the onStope() method :
#Override
protected void onStop() {
super.onStop();
savePreference();
}
And on your onCreate() you just need to call this :
spipol = findViewById(R.id.spipol);
String[] options = {"", "Short assignment", "Workshop", "Study", "Questions", "Review"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, options);
spipol.setAdapter(adapter);
// here to restore the last selected item
SharedPreferences sharpref = getSharedPreferences("Spinner", MODE_PRIVATE);
spipol.setSelection(sharpref.getInt("Data", 0));
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();
};
};
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();
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);
}
}
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);
}