checkbox + customAdapter + listview + sharedpreferences - android

I have a listview with a custom adapter of two lines(textview) and one checkbox.
I would like to save the state of the checkbox when I close the app, but I don't know how, I tried many things but nothing!
I can do it with a android.R.layout.simple_list_item_multiple_choice but no with my adapter.
onCreate
private SimpleAdapter notes;
ArrayList<HashMap<String, String>> arraylist_hashmap = new ArrayList<HashMap<String, String>>();
if (lenguage.equals("Deutsch")) {
HashMap<String, String> item;
for (int i = 0; i < StatesAndCapitalsAleman.length; i++) {
item = new HashMap<String, String>();
item.put("line1", StatesAndCapitalsAleman[i][0]);
item.put("line2", StatesAndCapitalsAleman[i][1]);
arraylist_hashmap.add(item);
}
notes = new SimpleAdapter(this, arraylist_hashmap, R.layout.main_item_two_line_row,
new String[] { "line1", "line2" },
new int[] { R.id.text1, R.id.text2 });
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
setListAdapter(notes);
Save state
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
SaveSelections();
super.onBackPressed();
}
private void SaveSelections() {
// save the selections in the shared preference in private mode for the
// user
SharedPreferences.Editor prefEditor = sharedpreferences.edit();
String savedItems = getSavedItems();
prefEditor.putString(MyPREFERENCES.toString(), savedItems);
prefEditor.commit();
}
private String getSavedItems() {
String savedItems = "";
int count = this.listView_ale.getAdapter().getCount();
for (int i = 0; i < count; i++) {
if (this.listView_ale.isItemChecked(i)) {
if (savedItems.length() > 0) {
savedItems += "," + this.listView_ale.getItemAtPosition(i);
} else {
savedItems += this.listView_ale.getItemAtPosition(i);
}
}
}
return savedItems;
}

You need to create an create an custom adapter with your own model with.
Create model which has a selected boolean field an other fields as per your requirement. And then create a custom adapter for your list. and then you can modify the model object on the checkbox's check state as selected true/false and latter you can save the sate as per your requirement.

Related

implement favorite button in listview android studio

I am implementing favorite button in ListView trying from the last five days. I have created a ListView which gets the current textview text and saves it in the ArrayList (names) and if the data is already present then deletes it, works perfectly but when I close the app the ArrayList gets empty i wants to save the array list in preferences.
array declaration:
ArrayList<String> names = new ArrayList<>();
Below is the code
favoritebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick( View v) {
if (!names.contains(textView_name.getText())){
names.add((String) textView_name.getText());
for (int i=0; i<names.size(); i++) {
System.out.println(names.get(i));
favoritebutton.setBackgroundResource(R.drawable.fav_checked);
}
}
else {
System.out.println(textView_name.getText() + " is already present in the Array at index " + names.indexOf(textView_name.getText()));
int currentIndex = names.indexOf(textView_name.getText());
names.remove(currentIndex);
for (int i=0; i<names.size(); i++) {
System.out.println(names.get(i));
favoritebutton.setBackgroundResource(R.drawable.star_off);
}
}
}
});
You can use SharedPreferences to retrieve and store data like below:
private ArrayList<String> names;
private SharedPreferences sharedPreferences;
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
String favoriteItems = sharedPreferences.getString("FAVORITE_ITEMS", "");
if(favoriteItems.isEmpty())
names = new ArrayList<>();
else
names = new ArrayList<>(Arrays.asList(favoriteItems.split(",")); //Update like this
favoritebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick( View v) {
if (!names.contains(textView_name.getText())){
names.add((String) textView_name.getText());
for (int i=0; i<names.size(); i++) {
System.out.println(names.get(i));
favoritebutton.setBackgroundResource(R.drawable.fav_checked);
}
}
else {
System.out.println(textView_name.getText() + " is already present in the Array at index " + names.indexOf(textView_name.getText()));
int currentIndex = names.indexOf(textView_name.getText());
names.remove(currentIndex);
for (int i=0; i<names.size(); i++) {
System.out.println(names.get(i));
favoritebutton.setBackgroundResource(R.drawable.star_off);
}
}
sharedPreferences.edit().putString("FAVORITE_ITEMS", TextUtils.join(",", names)).apply();
}
});
You will have to save that list in preferences after each update you can use Gson lib for that which convert array list to JsonArray and JsonArray to Arraylist which will help to you...
String str = fetchFromPref();
ArrayList<String> names = covertToArrayListFromJSOnString(str);
favoritebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick( View v) {
if (!names.contains(textView_name.getText())){
names.add((String) textView_name.getText());
for (int i=0; i<names.size(); i++) {
System.out.println(names.get(i));
favoritebutton.setBackgroundResource(R.drawable.fav_checked);
}
}
else {
System.out.println(textView_name.getText() + " is already present in the Array at index " + names.indexOf(textView_name.getText()));
int currentIndex = names.indexOf(textView_name.getText());
names.remove(currentIndex);
for (int i=0; i<names.size(); i++) {
System.out.println(names.get(i));
favoritebutton.setBackgroundResource(R.drawable.star_off);
}
}
String str = convertArrayListToJson(names).toString();
saveToPrefrences(str);
}
});

Listview not updating based on value on Array Adapter

I call the method below to update my listview
ListView list = (ListView) listView.findViewById(R.id.plan_list);
itemsList = sortAndAddSections(getItems_search(name));
ListAdapter adapter = new ListAdapter(getActivity(), itemsList);
list.setAdapter(adapter);
but that code is associated with a value that changes and also this is the other code
private ArrayList<plan_model> getItems_search(String param_cusname) {
Cursor data = myDb.get_search_plan(pattern_email, param_name);
int i = 0;
while (data.moveToNext()) {
String date = data.getString(3);
String remarks = data.getString(4);
items.add(new plan_model(cusname, remarks);
}
return items;
}
and this is my sorter
private ArrayList sortAndAddSections(ArrayList<plan_model> itemList) {
Collections.sort(itemList);
plan_model sectionCell;
tempList.clear();
tmpHeaderPositions.clear();
String header = "";
int addedRow = 0;
int bgColor = R.color.alt_gray;
for (int i = 0; i < itemList.size(); i++) {
String remarks = itemList.get(i).getRemarks();
String date = itemList.get(i).getDate();
if (!(header.equals(itemList.get(i).getDate()))) {
sectionCell = new plan_model(remarks, date);
sectionCell.setToSectionHeader();
tmpHeaderPositions.add(i + addedRow);
addedRow++;
tempList.add(sectionCell);
header = itemList.get(i).getDate();
bgColor = R.color.alt_gray;
}
sectionCell = itemList.get(i);
sectionCell.setBgColor(bgColor);
tempList.add(sectionCell);
if (bgColor == R.color.alt_gray) bgColor = R.color.alt_white;
else bgColor = R.color.alt_gray;
}
tmpHeaderPositions.add(tempList.size());
for (int i = 0; i < tmpHeaderPositions.size() - 1; i++) {
sectionCell = tempList.get(tmpHeaderPositions.get(i));
sectionCell.setDate(sectionCell.getDate() + " (" +
(tmpHeaderPositions.get(i + 1) - tmpHeaderPositions.get(i) - 1) + ")");
}
return tempList;
}
my question is the value name changes but my listview is not how can I update my listview? because i need to update it based on search parameter
If your itemList is being updated properly, you don't need to create another instance of the adapter, just use notifyDataSetChanged():
private void createList() {
ListView list = (ListView) listView.findViewById(R.id.plan_list);
itemsList = sortAndAddSections(getItems_search(name));
adapter = new ListAdapter(getActivity(), itemsList);
list.setAdapter(adapter);
}
private void updateList() {
sortAndAddSections(getItems_search(name)); // Update itemList without re-assign its value, otherwise the adapter will loose reference
adapter.notifyDataSetChanged()
}
In getItems_search() add this line at the beginning:
items.clear();
Every time the value of name changes you have to do the following:
itemsList.clear();
itemsList = sortAndAddSections(getItems_search(name));
list.setAdapter(new ListAdapter(getActivity(), itemsList));

ArrayList turn becomes when an app is resumes after onKill in android

My arraylist becomes null after restarting the app i.e after onKill.
I have declared the array list as Private
I dnt know what is the problem please help .
I have used shared preferences But somehow that dosnt help as welll
When i close the app/kill and restart the arraylist becomes null
private ArrayList<String> PlacardHolder = new ArrayList<String>();
private ArrayList<String> SecondaryPlacardArray = new ArrayList<String>();
private ArrayList<String> DangerousGoodsArray = new ArrayList<String>();
private ArrayList<String> Existing_placards= new ArrayList<String>();
private int PlacardHolderRemainingslots = 2;
private int PlacardHolderPositions=0;
private int PrimaryPlacardCount=0;
private int SecondaryPlacardCount=0;
private boolean Flag_Dangerous_placard_Existing=false;
//String[] PrimaryPlacardArray=new String[3];
private int DangerousGoodsArrayCount=0;
private static int CommonCount=0;
int PrimaryConditionCount=0;
//to take the positions of the placards in the placard holder so that it can be replaced
//Array to store position of placards in the position holder
int[] NoOfPrimaryCount= new int [3];
int count=0;
private localization localLanguage;
public static String filename="MySharedString";
SharedPreferences PlacardHolderData;
SharedPreferences.Editor sEdit;
#SuppressLint("NewApi")
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.main);
PlacardHolderData=getSharedPreferences(filename, 0);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
///Adding to the placard code in between...Its quite big
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
// menuInflater.inflate(R.menu.menu, menu);
menu.add(menu.NONE,menu_undo,menu.NONE, localization.Menu_Items_Undo_Last);
menu.add(menu.NONE,menu_placards,menu.NONE, localization.Menu_Items_Show_Placard);
menu.add(menu.NONE,menu_dall,menu.NONE,localization.Menu_Items_Deliver_All);
menu.add(menu.NONE,menu_delete,menu.NONE,localization.Menu_Items_Delete);
menu.add(menu.NONE,info,menu.NONE,"Info");//localization reqired
menu.add(menu.NONE,change_locale,menu.NONE,localization.Menu_change_locale);
menu.add(menu.NONE,menu_office,menu.NONE,localization.Menu_Items_Sync_With_Office);
menu.add(menu.NONE,menu_trackSettings,menu.NONE,"Track Settings");//localization reqired
menu.add(menu.NONE,menu_quit,menu.NONE,localization.Menu_Items_Quit);
return super.onCreateOptionsMenu(menu);
}
#SuppressWarnings("deprecation")
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// undo last item from list
case menu_undo:
try {
String idUndo = Utils.idForUndo.get("idUndo");
Log.e(TAG," Utils ids size " + Utils.idForUndo.size() );
for(int i = 0; i < Utils.Placard_Detailss.size(); i++ )
{
Log.e(TAG," placards hash map content " + Utils. Placard_Detailss.get(idUndo));
Log.e(TAG," placards hash map content " + Utils. Placard_Detailss.get(Utils. Placard_Detailss.get(idUndo) ));
}
if (idUndo != null) {
Log.e(TAG, "idUndo--> "+idUndo);
UpdateDBData ud = new UpdateDBData(getApplicationContext());
ud.undoLast(idUndo);
ArrayList<String> Placard_Details_Undo= new ArrayList<String>(Utils.Placard_Details_for_undo);
Log.e(TAG,"pLACARD DETAILS FOR UNDO sixze"+ Utils.Placard_Details_for_undo.size());
for(int i = 0; i <Placard_Details_Undo.size();i++)
{
Log.e(TAG,"pLACARD DETAILS FOR UNDO"+Placard_Details_Undo.get(i));
}
undoLastPlacard( Utils. Placard_Detailss.get(idUndo) , Utils. Placard_Detailss.get(Utils. Placard_Detailss.get(idUndo) ) );
} else {
Toast.makeText(context,localization.Undo_last_message,Toast.LENGTH_LONG).show();
}
getBannerData();
} catch (Exception e2) {
//
e2.printStackTrace();
}
return true;
// show all placards that are selected
case menu_placards:
try {
// PlacardHolderData=PreferenceManager.getDefaultSharedPreferences(context);
// sEdit= PlacardHolderData.edit();
//
// ArrayList<String> myAList=new ArrayList<String>();
// int size = PlacardHolderData.getInt("size", 0);
// PlacardHolderData=getSharedPreferences(filename, 0);
// Log.e(TAG, "size" + size);
//
// for(int j=0;j<size;j++)
// {
// myAList.add(PlacardHolderData.getString("val"+j, "No Data"));
// }
//
// Log.e(TAG, "size" + size);
//
for(int j=0;j< PlacardHolder.size();j++)
{
Log.e(TAG, "Alist" + PlacardHolder.get(j));
}
if (PlacardHolder.size() < 1) {
Toast.makeText(context,localization.Sorry_No_Items_to_Show,Toast.LENGTH_LONG).show();
return false;
}
alconvert = new AlertDialog.Builder(MainActivity.this).create();
LayoutInflater inflater = getLayoutInflater();
View convertView = (View) inflater.inflate(R.layout.custom_listview, null);
alconvert.setView(convertView);
TextView titleSAll = new TextView(this);
titleSAll.setText(localization.Placards_on_the_Truck);
titleSAll.setBackgroundColor(Color.BLACK);
titleSAll.setPadding(10, 10, 10, 10);
titleSAll.setGravity(Gravity.CENTER);
titleSAll.setTextColor(Color.WHITE);
titleSAll.setTextSize(20);
alconvert.setCustomTitle(titleSAll);
CustomAdapterShowAllPlacards myAdptShowAll = new CustomAdapterShowAllPlacards(PlacardHolder,MainActivity.this);
ListView lv = (ListView) convertView.findViewById(R.id.listView2);
lv.setAdapter(myAdptShowAll);
alconvert.setButton(localization.Dialog_Ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int arg1) {
dialog.dismiss();
}
});
alconvert.show();
} catch (Exception e1) {
//
e1.printStackTrace();
}
return true;
Yes when you killed your app or finish your activity all the object created into the heap is cleaned by the garbage collector. so after killing your app or finish your activity your array list object is not available into the heap memory. so when u access it it always gives you null value.
so you need to again initialized array list reference variable. to do it :-
you need to store all the arrayList value into the cache or into the data base. and after storing it into the cache or database. then initialize the arrayList reference from cache or data base.

Android CheckedTextVIew Clear All/Select All

I have a ListView that utilizes a CheckedTextView and a clear all button that has the following code:
btnClearAll.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int listsize = songsList.size();
filelv = (ListView)getView().findViewById(R.id.FileList);
checkedCount = 0;
for (int i=0; i<listsize-1; i++) {
// if(currentPlayList.get(i).equals ("Checked")){
songsList.get(i).get("songCheckedStatus").equals("Not Checked");
filelv.setItemChecked(i, false);
}
}
});
When the code executes, each array "songsList" value is set to "Not Checked" correctly, so I know that the button is working. However, the CheckedTextView items are not "unticking".
Where am I going wrong?
olution:
As mentioned above, I just set up a global variable and passed whether I wanted to Select All or Clear All to it. Then I just called my function for populating the ListView. As the ListView is built, it checks the variable in a simple "if" statement, and adds whether to check or uncheck. The cursor adapter then does the check/uncheck as it reruns.
//The code for clearing all.
btnClearAll.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
checkedCount = 0;
GetMusicMode = "ClearAll";
GetMusic getMusic = new GetMusic();
getMusic.execute();
}
});
And this from my data grabber for the ListView.
....
String track_Title = null;
String track_Path = null;
String track_Artist = null;
String track_Album = null;
String track_ID = null;
String track_TrackNumber = null;
String track_AlbumID = null;
String track_ArtistID = null;
String track_Checked = null;
if (Constants.GetMusicMode.equals("SelectAll")){
track_Checked = "Checked";
}else{
track_Checked = "Not Checked";
}
.....
.....
HashMap<String, String> song = new HashMap<String, String>();
song.put("songTitle", track_Title);
song.put("songPath", track_Path);
song.put("songArtist", track_Artist);
song.put("songAlbum", track_Album);
song.put("songTrackNumber", track_TrackNumber);
song.put("songID", track_ID);
song.put("songAlbumID", track_AlbumID);
song.put("songArtistID", track_ArtistID);
song.put("songCheckedStatus", track_Checked);
// Adding each song to SongList
songsList.add(song);
....throw to cursor adapter
and finally, this section from the cursoradapter getview
if (songsList.get(position).get("songCheckedStatus").equals("Checked")){
holder.checkTextView.setChecked(true);
}else{
holder.checkTextView.setChecked(false);
}

Saving Android Preferences

Hi, I have a listview and i'm wanting it so that when you press on an item it stores your selection in shared preferences. The purpose for this is so that next time I open the app it skips the selection process.
So what I'm wanting to know is how do I incorporate this function into my code?
Here is my code so far:
public class SelectTeamActivity extends ListActivity {
public String fulldata = null;
public String position = null;
public String divisionName= null;
public List<String> teamsList = null;
public String divName = null;
protected void loadData() {
fulldata = getIntent().getStringExtra("fullData");
position = getIntent().getStringExtra("itemIndex");
Log.v("lc", "selectteamActivity:" + fulldata);
Log.v("lc", "position:" + position);
int positionInt = Integer.parseInt(position);
try{
JSONObject obj = new JSONObject(fulldata);
teamsList = new ArrayList<String>();
JSONObject objData = obj.getJSONObject("data");
JSONArray teamInfoArray = objData.getJSONArray("structure");
for(int r = 0; r < teamInfoArray.length(); r++ ){
JSONObject teamFeedStructureDict = teamInfoArray.getJSONObject(r);
JSONArray teamStructureArray =
(JSONArray) teamFeedStructureDict.get("divisions");
JSONObject teamFeedDivisionsDictionary =
teamStructureArray.getJSONObject(positionInt);
divName = teamFeedDivisionsDictionary.getString("name");
JSONArray teamNamesArray =
(JSONArray) teamFeedDivisionsDictionary.get("teams");
for(int t = 0; t < teamNamesArray.length(); t++){
JSONObject teamNamesDict = teamNamesArray.getJSONObject(t);
teamsList.add(teamNamesDict.getString("name"));
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.selectact);
loadData();
TextView headerText = (TextView) findViewById(R.id.header_text);
headerText.setText(divName);
TextView redHeaderText = (TextView) findViewById(R.id.redheadertext);
redHeaderText.setText("Please select your team:");
setListAdapter( new ArrayAdapter<String>(this, R.layout.single_item,
teamsList));
ListView list = getListView();
list.setTextFilterEnabled(true);
}
#Override
protected void onListItemClick (ListView l, View v, int position, long id) {
Intent intent = new Intent(this, HomeActivity.class);
String curPos = Integer.toString(position);
//or just use the position:
intent.putExtra("itemIndex", curPos);
intent.putExtra("fullData", fulldata); //or just the part you want
startActivity(intent);
}
}
In your Activity's onCreate():
SharedPreferences preferences = getSharedPreferences("preferences", MODE_WORLD_WRITEABLE);
In your onListItemClick():
preferences.edit().putInt("KEY", position).commit();
Everywhere in your project:
int position = preferences.getInt("KEY", -1);
(-1 is a default value that means when there is no value with the given key, return this value)

Categories

Resources