How can I save the ListView to restore? - android

How can I save the ListView and restore it by resume? Because when i close the app all contents are delete.
Thanks for answers
public class ToDoList extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView myListView = (ListView)findViewById(R.id.todolist);
final EditText myEditText = (EditText)findViewById(R.id.addtodo);
final ArrayList todoItems = new ArrayList();
final ArrayAdapter aa;
aa = new ArrayAdapter(this,
android.R.layout.simple_list_item_1,
todoItems);
myListView.setAdapter(aa);
String edittext="";
SharedPreferences settings = getSharedPreferences("PreferencesName", 0);
edittext = settings.getString("Content", edittext);
todoItems.add(0, edittext);
myEditText.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN)
if (keyCode == KeyEvent.KEYCODE_ENTER){
todoItems.add(0, myEditText.getText().toString());
aa.notifyDataSetChanged();
String edittext= myEditText.getText().toString();
SharedPreferences settings = getSharedPreferences("PreferencesName", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("Content", edittext);
myEditText.setText("");
return true;
}
return false;
}
});
}}

According to the comment you gave - about losing data after closing application - there are few options which you have to solve your problem.
What you have to do is to store your data for further use - you can either use SharedPreferences or SQLite database.
SharedPreferences
It is good choice for small amounts of data. If
you're trying to store ListView's content, SharedPreferences is
most likely not a good option for you.
This code you can use for storing data in your SharedPreferences:
SharedPreferences settings = getSharedPreferences("PreferencesName", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInteger("FirstInteger", a);
editor.putInteger("SecondInteger", b);
(...)
And this is how you retrieve it:
SharedPreferences settings = getSharedPreferences("PreferencesName", 0);
int a = settings.getInteger("FirstInteger", false);
int b = settings.getInteger("SecondInteger", false);
Anyway, here you can read more
about it:
http://developer.android.com/guide/topics/data/data-storage.html
Database
Better for larger amounts of data. It is more difficult,
but if you know basics of MySQL, you will have no problem with using
it. There is a good tutorial about using SQLite database in android
application:
http://www.vogella.com/articles/AndroidSQLite/article.html
After you have stored your data, you can then access the local storage to retrieve them, refill adapter and recreate ListView.

Related

Saving state of CheckBoxes

Please help me! Checkbox does not save state after restarting the app
I have a ListView with CheckBoxes and I want that when user selects any check box and closes the application, and again opens the application, the same CheckBoxes should be selected. i.e I have to save the state of the CheckBoxes
// custom BaseAdapter class
...
boolean [] itemChecked;
//getView ...
//getSharedPreferences
sharedPrefs = context.getSharedPreferences(PACKAGE_NAME, Context.MODE_PRIVATE);
//Click ckeckbox
viewHolder.check_task.setChecked(sharedPrefs.getBoolean(PACKAGE_NAME , false));
viewHolder.check_task.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//SharedPreferences
SharedPreferences.Editor editor = context.getSharedPreferences(PACKAGE_NAME , Context.MODE_PRIVATE).edit();
if (viewHolder.check_task.isChecked()) {
//if value is false
itemChecked[i] = true;
viewHolder.check_task.setChecked(true);
//put True
editor.putBoolean(PACKAGE_NAME, true);
editor.apply();
} else {
//if value is false
itemChecked[i] = false;
viewHolder.check_task.setChecked(false);
//put False
editor.putBoolean(PACKAGE_NAME, false);
editor.apply();
}}}); return myView; }
You are always setting the last checked box state in shared preferences since you are using the same key each time. If you want to set multiples you would have to define a new key for each boolean using something like editor.putBoolean(PACKAGE_NAME + index, true); then retrieve it using the same logic. This will result in each index having an entry in shared preferences. Another approach would be to use GSON to save the entire array in onPause and restore it when the app is relaunched.

Remove item from SharedPreference when removed from Listview

In my code, with the help of context menu I'm able to delete a particular item from Listview but as I'm using sharedpreferences to save arraylist called "places" then it restores the sharedpreference when the app is launched back again. Now how should I implement my sharedpreferences such that when a particular item is deleted from listview, the same item also gets deleted from arraylist "places" of shared preferences.
Below is my code snippet
static ArrayList<String> places = new ArrayList<String>();
static ArrayList<LatLng> locations = new ArrayList<>(); //to save lat and long
static ArrayAdapter arrayAdapter;
public ListView listView;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
sharedPreferences = this.getSharedPreferences("com.starprojects.memorableplaces", Context.MODE_PRIVATE);
registerForContextMenu(listView);
//tricker locations
ArrayList<String> latitudes = new ArrayList<>();
ArrayList<String> longitudes = new ArrayList<>();
//initially set
places.clear();
latitudes.clear();
longitudes.clear();
locations.clear();
//to restore
try {
places = (ArrayList<String>) ObjectSerializer.deserialize(sharedPreferences.getString("places", ObjectSerializer.serialize(new ArrayList<>())));
latitudes = (ArrayList<String>) ObjectSerializer.deserialize(sharedPreferences.getString("latitudes", ObjectSerializer.serialize(new ArrayList<>())));
longitudes = (ArrayList<String>) ObjectSerializer.deserialize(sharedPreferences.getString("longitudes", ObjectSerializer.serialize(new ArrayList<>())));
Log.i("palces",places.toString());
} catch (IOException e) {
e.printStackTrace();
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
// sharedPreferences = getSharedPreferences("places",0);
SharedPreferences.Editor editor = sharedPreferences.edit();
if((item.getTitle()).equals("Delete"))
{
places.remove(info.position);
editor.remove("places"); //problem is here, how to get particular index to be removed from arraylist places and save it.
editor.commit();
arrayAdapter.notifyDataSetChanged();
return true;
}
return super.onContextItemSelected(item);
}
}
you can get index by
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
int index = info.position;
it means you must a list in you shared preference or you have a different key for your shared preference.
Case 1: if you have a list in your shared preference than update the shared preference with the remove of data of data from the listview.
Case 2: if you assigned different key_names for each of the list item then you can simply remove or clear that key_name when the data is removed from the shared preference.
If I'm getting the point of your question you are trying to keep the shared preferences copy up to date with the one you display and vice-versa.
To accomplish this I think that you just need to put the updated places array list into shared preferences, like this:
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
SharedPreferences.Editor editor = sharedPreferences.edit();
if ((item.getTitle()).equals("Delete")) {
// Update local list
places.remove(info.position);
// Set list into shared preferences
// Or if you use a JSON string you could serialize and use putString()
editor.putStringSet("places", places);
// Use apply it's async
editor.apply();
arrayAdapter.notifyDataSetChanged();
return true;
}
return super.onContextItemSelected(item);
}
Please use apply() in place of commit(). It's faster and asynchronous

Get and set Spinner values

I am to android coding and have what I hope will be a simple question. I have an app that has a demographics page, with various spinners (although I will only use 1 for this example). The spinners are already populated, but the user can save them once they have made their choice so every time they open this app the previous choices are there.
My code to load the values into the spinner is
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_demographics);
// Show the Up button in the action bar.
setupActionBar();
SharedPreferences prefs = getSharedPreferences("data_file", MODE_PRIVATE);
int ageValue = prefs.getInt("Age", 0);
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
//set the default according to value
spinner.setSelection(ageValue);
}
and then my code to save the data is
public void submitDemo(View view) {
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
int ageValue = spinner.getSelectedItemPosition();
//save the current data from the spinner
SharedPreferences prefs = getSharedPreferences("data_file", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("Age", ageValue);
editor.commit();
finish();
}
I'm not bothered about capturing the value when they change the spinner, just simply at the end. I know it's probably something simple that I'm missing, but if anyone can help I would greatly appreciate it
First, set an adapter:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(),
android.R.layout.simple_spinner_item,
getResources().getStringArray(R.array.your_string_array));
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
If setSelection(value) doesn't work try with
spinner.setSelection(ageValue, true);
This will "animate" the selection, i.e. scroll it to the selected position.

Save listview item

I'm trying to implement a listview and what I want exactly is:
The app launches, 1 item from ListView is being chosen and starts a webview. This step is done
But what I want is that 2. time when I launch the app, it will start from that item and not show the list again. So it will continue always to start on that item I pressed first time.
I hope someone can show me a tutorial I can follow or some keyword I will try to see if I can do it.
*UPDATE --> Code
public class AndroidListViewActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] adobe_products = getResources().getStringArray(R.array.adobe_products);
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, adobe_products));
ListView lv = getListView();
SharedPreferences prefs = getSharedPreferences("PREFERENCE", MODE_PRIVATE);
boolean firstrun = prefs.getBoolean("firstrun", true);
if (firstrun) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstrun", false);
editor.apply();
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent(getApplicationContext(), EnkeltView.class);
// sending data to new activity
i.putExtra("url", "https://google.dk");
startActivity(i);
}
});
}
// Save the state
getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.edit()
.putBoolean("firstrun", false)
.commit();
}
}
Use SharedPreference works like a DB but in a small scale:SharedPreference
Android documentation: This data will persist across user sessions (even if your application is killed).
So SharedPreferences shouldn't be getting wiped when a device reboots or force closes.
you can store item in shared preferences in 1st time and during second time you can check if your shared Preference is not null then It launch the application with item stored in it.

Spinner value into a ListPreference

I'm trying to save a Spinner value into a ListPreference. I can't get it to work. I've tried to get this working for a long time now. Does anyone have a solution or can anyone point me in the right direction.
So this is what I have:
SharedPreferences preferences;
private static final String KEY_WEIGHT_PREFERENCE = "weightunit";
...
preferences = PreferenceManager.getDefaultSharedPreferences(this);
...
This is the main part, both the Spinner and the ListPreference grab the same data from an array xml.
SharedPreferences.Editor edit = preferences.edit();
Spinner weight = (Spinner) findViewById(R.id.weightUnitSpinner);
int selectedPosition = weight.getSelectedItemPosition();
edit.putInt(KEY_WEIGHT_PREFERENCE, selectedPosition);
edit.commit();
Thanks!
What isn't working?
There's a sample app called Spinner that contains a sample Spinner. It saves the state of the Spinner to saved preferences in onPause(), and restores it in onResume().
I found the answer, the SpinnerValue needs to be saved as a string in order to get recognized by the ListPreference.
Here's my final code:
private void updatePreferenceWeightValue() {
SharedPreferences.Editor edit = preferences.edit();
Spinner weight = (Spinner) findViewById(R.id.weightUnitSpinner);
int selectedPosition = weight.getSelectedItemPosition();
String weightValue = "";
weightValue = Integer.toString(selectedPosition);
edit.putString(KEY_WEIGHT_PREFERENCE, weightValue);
edit.commit();
}

Categories

Resources