How to save dynamically added items in Listview with sharedpreferences? - android

protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
preferences = getSharedPreferences(FAVORI, 0);
ListView favlist = (ListView) findViewById(R.id.favoriliste);
ArrayList<String> foo = new ArrayList<String>();
String [] bar = foo.toArray(new String[0]);
public void favekle(String string) {
foo.add(string);
bar = foo.toArray(new String[0]);
favadapter = new MyFavAdapter(Diziler.this,
android.R.layout.simple_list_item_1, R.id.txtTitle, bar);
// favlist= new ArrayList<>();
favlist.setAdapter(favadapter);
favadapter.notifyDataSetChanged();
}
favadapter = new MyFavAdapter(Diziler.this,
android.R.layout.simple_list_item_1, R.id.txtTitle, bar);
// favlist= new ArrayList<>();
favlist.setAdapter(favadapter);
favadapter.notifyDataSetChanged();
Hello.I need help.I want save dynamically added items in Listview with SharedPreferences.
I'm adding listview items with public void favekle function.I'm adding items to ArrayList<> than i convert ArrayList<> to string array finally i set items to adapter.
If i restart application my listview items disappear.
How can i save added items with sharedpreferences?I used StringBuilder but it didn't work.Thank you.

You can save to shared preference in this way
SharedPreferences sp = context.getSharedPreferences(
"file name", 0);
SharedPreferences.Editor spEdit = sp.edit();
spEdit.putLong(key, value);
spEdit.commit();

You are supposed to store single key-value paired data with SharedPreferences. Trying to store big grouped data is not efficient at all. You should use an SQLite database.
SQLite and ContentProvider Tutorial

You can store string sets in Shared Preferences, then convert them back to a List when you retrieve them.
ArrayList<String> list = new ArrayList<String>();
list.add("test1");
list.add("test2");
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putStringSet("stringset", new HashSet<String>(list))
.commit();

Related

SharedPreference saving just one value

I'm trying to make favorites module in my app. If user click favorite button for a radio, this radio must displayed in Favorites screen. But just last clicked radio shown in Favorites screen. I want to save more than one radios in Favorites. Where I'm doing wrong? thanks in advance.
This is favorite button in RadioFragment
add_favorites_button= (Button) view.findViewById(R.id.add_favorites_button);
add_favorites_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences settings = getActivity().getSharedPreferences("PREFS", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("radio_link", radio_play_link);
editor.putString("radio_namee", radio_name);
editor.commit();
}
});
And I'm trying to get these values and put in ArrayList in FavoritesFragment. To display received values, I sent them in textview to try.
public class FavoritesFragment extends Fragment {
public FavoritesFragment() {
// Required empty public constructor
}
TextView radio_name_txt, radio_link_txt;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_favorites, container, false);
List<String> radio_name_list = new ArrayList<>();
List<String> radio_link_list = new ArrayList<>();
SharedPreferences settings = getActivity().getSharedPreferences("PREFS",0);
radio_name_list.add(settings.getString("radio_namee", ""));
radio_link_list.add(settings.getString("radio_link", ""));
radio_name_txt = (TextView) view.findViewById(R.id.radio_name_txt);
radio_link_txt = (TextView) view.findViewById(R.id.radio_link_txt);
String a= "";
String b= "";
for (int i =0; i<radio_name_list.size(); i++) {
a = a +radio_name_list.get(i);
b = b +radio_link_list.get(i);
}
radio_name_txt.setText(a);
radio_link_txt.setText(b);
return view;
}
}
You have a lot of data and Shared Preferences is not the write option to store your data for 7000 items. Shared preference is good for easy and less frequent data storage, For your case you need to make a SQLite Database. If its totally new to your then pay a visit in Androids only Documentation Training in this link.
since you are using same key for every radio button insert it will overwrite the previous values.
You need to store values in an array and then store array in the preferneces.
Or the better way is to use sqllite database in the android to store the likes in a table.
Try displaying the values from the Lists radio_name_list and radio_link_list in a ListView:
Save the values in an Array List.
Create a ListView instead of a TextView.
Create an ArrayAdapter and set it as the adapter for your ListView.
As far as I can see you only have one TextView. Try creating a ListView instead of a TextView. It will be more organized.
editor.putString("radio_link", radio_play_link);
editor.putString("radio_namee", radio_name);
You are overwriting the favorite every time you try to add a new one, so instead of doing the above, do this:
editor.putString(radio_play_link, radio_play_link);
editor.putString(radio_name, radio_name);
So now you have a key-value pair, and you can iterate over your favorites like this:
String radioLink = "", radioKey = "";
for (Map.Entry<String, ?> entry : getSharedPreferences("PREFS",0).getAll().entrySet()) {
radioKey = entry.getKey();
radioLink = (String) entry.getValue();
}

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

Android: ListView displays only last values saved in an array

hi i have tried the following code to store the user input values of EditText to an array in another activity and display the values in the array. every time the user input values in EditText of Activity01. it should be stored in an array on the Activity02 to display all the values of user inputs.
The ListView displays one last entered value from Array.
This is the code what i have tried.
Activity01.java
Button GrmBtnSave = (Button) findViewById(R.id.grmbtnsave);
Grmitem = (AutoCompleteTextView) findViewById(R.id.itemsearch);
GrmBtnSave.setOnClickListener(new OnClickListener(){
public void onClick(View view){
Intent intent = new Intent ( ItemSearch.this, MainInvoiceActivity.class );
intent.putExtra("GRM_ITEM", Grmitem.getText().toString());
startActivity(intent);
}
}
});
Activity02.java
ListView lv1;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
protected void onCreate(Bundle savedInstanceState) {
//.....
//.....
lv1=(ListView)findViewById(R.id.getalllist);
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, list);
lv1.setAdapter(adapter);
String val="";
if(getIntent().getStringExtra("GRM_ITEM")!=null && getIntent().getStringExtra("GRM_ITEM").length() > 0){
val = getIntent().getStringExtra("GRM_ITEM");
list.add(val);
}
adapter.notifyDataSetChanged();
}
I tried solving it but still i get the last entered value in the EditText.
Thank you for help
The static keyword will do the magic.
Make change in declaration of list in your activity02.java like this. I have tested it. and it works.
static ArrayList<String> list = new ArrayList<String>();

How to make custom list with three columns with text in android

This is my code,in this code i put data in the string array and through looping i put all the data into the list called AcerList and give that list to adapter. The by getting the index from previous class i am checking the condition according to which i am giving an adapter if it's legal.
ListView lstView;
String AcerProductsArray[] = { "Acer Aspire V5-571 Ultra Book i3","AceAspireS3391i3","Acer Aspire S3-391 i3"};
ArrayList<String> AcerList = new ArrayList<String>();
ArrayAdapter<String> AcerAdapter;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.selectedcategory);
lstView = (ListView) findViewById(R.id.list);
try{
for(int i=0;i<AcerProductsArray.length;i++)
{
AcerList.add(AcerProductsArray[i]);
}catch(){}
AcerAdapter = new ArrayAdapter<String> (this, android.R.layout.simple_list_item_1, AcerList);
Bundle extras = getIntent().getExtras();
int index = 0;
index = extras.getInt("index");
if(index == 0){
lstView.setAdapter(AcerAdapter);
AcerAdapter.notifyDataSetChanged();
}
This is my output.But i also want to set the price and details using customized lists,In xml file i have only one list and three textViews. i havent use any database all the programe in hard coded.Please help me in solving this..
A string array is not going to work for you. Define a class e.g Acer and define all the required attributes for the class. Then pass an array of the Acer objects to your adapter rather then Strings. e.g
The Acer class:
public class Acer{
String name;
String price;
String details;
public Acer(String _name, String _price, String _details){
this.name =_name;
this.price = _price;
this.details = _details;
}
}
Then pass an array of Acer objects to your adapter and you will be able to acess all the properties for an object inside the adapter. e.g if you want the price for the selected item, you would do this inside the adapter :
array_of_acers.get(position).price;
Also you would be needing a custom array adapter for this. A nice and simple example for a custom listview with custom adapter is given here

Populate ListView with Dynamic Array

I have a EditText box so a user can input names and then click the Add button and the name saves to the array playerList and clears the box so another name can be added.
I also have a ListView on the same Activity which will then be populated by the names in the Array playerList. The problem is that the ListView dosen't seem to be populated.
So I tried with a defualt set String teststring which you can see below and that populates the ListView fine. My question is how come it isn't working with the Array playerList maybe its not saving to the Array correctly?
Update just need adapter.notifyDataSetChanged(); adding to refresh the ListView Credit to #Lalit Poptani and #Jave
ArrayList<String> playerList = new ArrayList<String>();
ListView listview;
protected String[] teststring = {"Name 1", "Name 2"};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.addremove);
ListAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, teststring);
ListView employeeList = (ListView) findViewById(R.id.namelistview);
employeeList.setAdapter(adapter);
Button confirm = (Button) findViewById(R.id.add);
confirm.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
EditText playername = (EditText) findViewById(R.id.userinput);
String name = playername.getText().toString();
playerList.add(name);
playername.setText("");
}});
To refresh the ListView after you add new data to it you have to call adapter.notifyDataSetChanged(). This is refresh your ListView will new data.
But in your case you are populating your ListView with String[] so it won't work dynamically you will have to give the size of the String[]. So, I will suggest you to populate your ListView with ArrayList itself for adding the content dynamically.
ListAdapter adapter = new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1,playerList);
You should call adapter.notifyDataSetChanged() after adding new items to make it update with the new data.
Notifies the attached observers that the underlying data has been
changed and any View reflecting the data set should refresh itself.

Categories

Resources