How do I remember (using shared preferences) ,items in my static array ? - android

I have a static array in my code and I am trying to remember the checks on them (only 1 is checkable at a time). Say I have items 1 ,2 ,3 and 4 and 3 is checked (1 2 4 will be unchecked) and if i click done button and return to the view later I would like to see 3 checked from last time. Is there a way I CAN DO THIS?
here's my code :
public static final String[] groups = new String[] { "A", "B", "C", "D" };
public static final String[][] children = new String[][] {
{ "1" } ,
{ "2" },
{ "3"},
{ "4" }
};
View view = inflater.inflate(R.layout.fragment_dead, container, false);
categoriesList1 = (ExpandableListView)view.findViewById(R.id.categories);
String currTemplate = MainFragment.Default;
for(#SuppressWarnings("rawtypes") Map.Entry entry: map.entrySet()){
if(mTemplateId.equals(entry.getValue())){
currTemplate = (String) entry.getKey();
break;
}
}
mAdapter = new MenuExpandableListAdapter(Fragment.groups,
MainFragment.children, currTemplate, this.getActivity());
mAdapter.setSelectionListner(this);
categoriesList1.setGroupIndicator(null);
categoriesList1.setChildIndicator(null);
categoriesList1.setAdapter(mAdapter);
categoriesList1.setOnChildClickListener(mAdapter);
return view;
#Override
public void onClick(final View view) {
MainActivity activity = (MainActivity) getActivity();
switch (view.getId()) {
case R.id.button_done:
saveUserPreferences();
activity.hideSoftKeyboard(getView());
break;
default:
break;
}

You should read this to learn more about the basics of data storage, it's actually really easy :
http://developer.android.com/guide/topics/data/data-storage.html#pref
You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed).

you should generate another array containing only the checked choices , and save it (by shared data or singleton class).
than when you are showing this Activity you put this values checked. so of course if this activity is opened for the first time, your checked items array will be null, so all the values would be unchecked.
to check by java , you can try this :
// also check this lines in the above example
ViewHolder holder = (ViewHolder) view.getTag();
holder.checkbox.setChecked(list.get(position).isSelected());

Related

Filtering Objects in RecyclerView with a switch

i have a RecyclerView that i passed anArrayList<MovieCategory> list to, and i want to filter it with a switch.Class MovieCategory has 4 boolean variables isAction, isComedy, isHorror and isThriller. So a movie can be: isAction = true if it's just an Action film, or it can be isAction = true isComedy = true if it's an action-comedy etc. There are 4 switches representing the 4 categories and when i flip the action switch i want to see moview where isAction = true, and when the switch is fliped back i want all the movies to reappear.I did solve the problem, each time the switch is flipped this function is called
for(Iterator<MovieCategory> it = list.iterator();it.hasNext();){
MovieCategory movieCategory = it.next();
if(!MovieCategory.isAction()){
removed.add(new Backup(movieCategory,movieCategory.indexOf(profileCard)));
it.remove();
}
}
adapter.notifyDataSetChanged();
Whre Backup is
class Backup{
MovieCategoty card;
int index;
public Backup(MovieCategoty movieCategory, int index) {
this.movieCategory = movieCategory;
this.index = index;
}
}
And when the switch is flipped off again i simple call
if(removed != null) {
for (Backup b : removed) {
list.add(b.index, b.movieCategory);
}
}
adapter.notifyDataSetChanged();
to put everything back where it was. The issue i have with this is i have to repeat this process for every switch, which means creating 4 ArrayList's and I'm worried about using too much memory because the RecyclerView can hold 10 Objects, or it can hold 50+ Objects, ie. it's not limited. So is there a better, more efficient way of doing this?

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();
}

How to Keep the ExpandableListView Checkboxes Checked States?

Currently I can check/uncheck the checkboxes by groupPosition and childPosition, and it's working fine. I save the groupPosition and childPosition to the SQLite Database.
When I added the delete option, my checkbox checked states are off/messed up.
For example, I have the following:
Group1,
Child1, Child2, Child3
I check all 3 of them and save the checked positions to the SQLite Database.
The checked positions would be 0,0 and 0,1 and 0,2 in the Database.
After I deleted Child1,
Child2 becomes position 0, Child3 becomes position 1 which would mess up the checked states.
I am trying to find a way to save the group name and child name instead of the positions to the SQLite Database, then load those names in Oncrete method.
MainActivity:
if(category_array.get(groupPosition).subcategory_array.get(childPosition).selected) {
category_array.get(groupPosition).subcategory_array.get(childPosition).selected = false;
try{
MySQLITE_DATABASE.deleteRows(groupPosition, childPosition);
}
catch (Exception e) {}
}
else
{
category_array.get(groupPosition).subcategory_array.get(childPosition).selected = true;
MySQLITE_DATABASE.addRow(groupPosition, childPosition);
}
Adapter code:
private List<Category> mGroupCollection;
if(mGroupCollection.get(groupPosition).subcategory_array.get(childPosition).selected) {
childHolder.checkBox.setBackgroundResource(R.drawable.checkbox_checked);
} else {
childHolder.checkBox.setBackgroundResource(R.drawable.checkbox_unchecked);
}
Date Holder Classes:
public class Category {
public String category_name = null;
public String cat_SelectedChildCount_name;
public ArrayList<SubCategory> subcategory_array = new ArrayList<SubCategory>();
}
//==============================
public class SubCategory {
public String subcategory_name = null;
public boolean selected = false;
}
I want to save the group name and child name instead of positions to the SQLite Database and then load them in OnCreate method.
I have tried this but it is not working:
String Group_Name = category_array.get(Integer.parseInt(groupPosition)).category_name;
String Child_Name = category_array.get(Integer.parseInt(groupPosition)).
subcategory_array.get(Integer.parseInt(childPosition)).subcategory_name;
if(category_array.get(Group_Name).subcategory_array.get(Child_Name).selected) {
category_array.get(Group_Name).subcategory_array.get(Child_Name).selected = false;
MySQLITE_DATABASE.DeleteRow(Group_Name, Child_Name);
}
else {
category_array.get(Group_Name).subcategory_array.get(Child_Name).selected = true;
MySQLITE_DATABASE.AddRow(Group_Name, Child_Name);
}
I know that I need to change the code in the adapater, data holder classes, and mainactivity in order to make it work, but I am out of ideas. I have been thinking and thinking, but nothing works...
Can someone please please guide me on this?
I am sorry for the long code.
Thank you and thank you.
Try any of the following if it suit's your requirement.
If you want to use the position strictly (May be there is no unique option)
Keep the DB design like
| id | parent_position | child_position |
Assume you have N childs. If you delete a child (Suppose it's 0). do this
Update all the child's with (child_position = child_position - 1) whose position is greater than
the deleted child of the parent. So the position remains unchanged.
Personally i would suggest don't use the position if a delete option is there. Option that i found, But don't know your use case
If you are loading the list from the database use the database primarykey as the key to save it in the SQLite database on selection/unselection. In this case you don't want to know the parent position as well.

Android Development - Code for clicking one list view to another

I simply want to create a ListView containing "a","b","c". When I click on each item, I want each item to direct a unique activity, each containing a different ListView.
Listview
A
1
2
3
B
3
4
5
C
6
7
8
Please provide the best code for this. Its so hard to find something on here that does this. Most entries are too specific for me to get a clear understanding of how to do all this in the most consistent, efficient manner.
Thanks in advance!
If you want a ListView with A, B, C in one Activity and the sublists in another Activity, you really only need one generic ListActivity to handle this. You only have to pass the ListActivity different sets of data.
In the onCreate() below:
If the Activity is not passed special data it will display A, B, C and it will use the onListItemClick() method to start the sub-Activities.
If the Activity does have the extra data stored in the Intent, then it displays this extra data in the ListView and will ignore any calls to onListItemClick().
public class Example extends ListActivity {
boolean isSubList = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] array;
Intent received = getIntent();
// Setup as main ListView
if(received == null || !received.hasExtra("array")) {
array = new String[] {"A", "B", "C"};
}
// Setup as sub ListView
else {
isSubList = true;
array = received.getStringArrayExtra("array");
}
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, array));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
if(!isSubList) {
Intent starting = new Intent(Example.this, Example.class);
switch(position) {
case 0:
starting.putExtra("array", new String[] {"1", "2", "3"});
break;
case 1:
starting.putExtra("array", new String[] {"4", "5", "6"});
break;
case 2:
starting.putExtra("array", new String[] {"7", "8", "9"});
break;
}
startActivity(starting);
}
}
}

Accounting for ListView sort while ignoring leading "The" in Android

I have a ListView that is populated by three (3) ArrayList's:
items, ratings and comments
However, I need to sort items by ignoring the leading 'the'. I already have accomplished this by rearranging the items ArrayList using a Collections.sort (see code below), but this is the issue: the comments and ratings are not rearranged so it comes out of order in the ListView.
For example, if the list was:
Cars 3 4
People 5 3
The Animals 7 4
After items sort I am getting:
The Animals 3 4
Cars 5 3
People 7 4
So the items are lining up as I'd like but the associated comments and ratings aren't sorted. I am not sure how to make that happen and where to place it. I think in the ArrayAdapter?
Here is the code I do to change the items list:
Comparator<String> ignoreLeadingThe = new Comparator<String>() {
public int compare(String a, String b) {
a = a.replaceAll("(?i)^the\\s+", "");
b = b.replaceAll("(?i)^the\\s+", "");
return a.compareToIgnoreCase(b);
}
};
Collections.sort(items, ignoreLeadingThe);
Here is the questions? Where and how can I sort the ratings and comments lists based on the position of the item list?
Edit:
this is my getView code in my ArrayAdapter:
ItemObject io = getItem(position);
String name = io.name;
String total = io.total;
String rating = io.ratings;
String comment = io.comments;
holder.t1.setText(name);
holder.t2.setText(total);
holder.t3.setText(comment);
holder.t4.setText(rating);
Note: There is a 4th ArrayList called total I did not mention in the above example.
You should look at creating a class to wrap your items in the ArrayList, something like this:
class MyItem {
String item;
int ratings;
int comments;
}
Then have an ArrayList of these objects instead:
List<MyItem> myList = new ArrayList<MyItem>();
Then in your comparator, just do it like you're doing, but testing against MyItem.item instead of just a and b. Something like this:
Comparator<MyItem> ignoreLeadingThe = new Comparator<MyItem>() {
public int compare(MyItem a, MyItem b) {
a.item = a.item.replaceAll("(?i(^the\\s+", "");
b.item = b.item.replaceAll("(?i(^the\\s+", "");
return a.item.compareToIgnoreCase(b.item);
}
};
Collections.sort(myList, ignoreLeadingThe);

Categories

Resources