implement favorite button in listview android studio - android

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

Related

how to get all values of particular TextView of listView? -Android

i have made ListView with three columns 'item','qty','rate' i get this entries from the user and i have made the listview work perfectly but i want to get all the values of the 'rate' column and add them for the net amount.
Here is my android code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
populateList();
adapter = new listviewAdapter(List.this, list);
lview.setAdapter(adapter);
}
private void populateList() {
HashMap temp = new HashMap();
list = new ArrayList<HashMap>();
item = etItem.getText().toString();
qty = etQty.getText().toString();
rate = etRate.getText().toString();
temp.put(FIRST_COLUMN, "1");
temp.put(SECOND_COLUMN, item);
temp.put(THIRD_COLUMN, qty);
temp.put(FOURTH_COLUMN, rate);
list.add(temp);
}
I tried out this method below but it only toast the first value.But i want to get all the values under the rate column and add them up for the net-amount.
public void get() {
StringBuilder sb = new StringBuilder();
for(int i=0; i<adapter.getCount(); i++) {
String a = ((TextView) findViewById(R.id.FourthText)).getText().toString();
adapter.getItem(i).toString();
sb.append(a);
sb.append("\n");
}
text = sb.toString();
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
}
I think this might help you.
private int GrandTotal(ListView list) {
int sum=0;
for (int i = 0; i < list.getCount(); i++) {
View v = list.getChildAt(i);
TextView rate = (TextView) v.findViewById(R.id.rate);
sum = sum + Integer.parseInt(rate.getText().toString() )
}
return sum;
}
:)
public void getTotalRate() {
int totalRate = 0;
for (int i = 0; i < list.size(); i++) {
HashMap temp = list.get(i);
/// here fourth column is rate
int rate = (int) temp.get(FOURTH_COLUMN);
totalRate = totalRate + rate;
}
Toast.makeText(getApplicationContext(), "total rate=" + totalRate, Toast.LENGTH_LONG).show();
}

How to add data in array on button click?

int size = mcq.size();
String arr[] = null;
int i;
{
for (i = 0; i < size; i++) {
if (op1.isPressed()) {
arr[i] = tv1.getText().toString();
// Log.e("Array",arr[i]);
} else if (op2.isPressed()) {
arr[i] = tv2.getText().toString();
//Log.e("Array",arr[i]);
} else if (op3.isPressed()) {
arr[i] = tv3.getText().toString();
// Log.e("Array",arr[i]);
} else if (op4.isPressed()) {
arr[i] = tv4.getText().toString();
//Log.e("Array",arr[i]);
}
I am trying to store the data in an array when the button is pressed,but it always shows null.And when the for loop is over I want to display my array.
here , Arrays in Java have a size so u cannot do like this. Instead of this
use list,
ArrayList<String> arr = new ArrayList<String>();
Inorder to do using String array :
String[] arr = new String[SIZEDEFNE HERE];
For ur answer :
ArrayList<String> arr = new ArrayList<String>();
int i;
{
for (i = 0; i < size; i++) {
if (op1.isPressed()) {
arr.add(tv1.getText().toString());
} else if (op2.isPressed()) {
arr.add(tv2.getText().toString());
} else if (op3.isPressed()) {
arr.add(tv3.getText().toString());
} else if (op4.isPressed()) {
arr.add(tv4.getText().toString());
}
Retrive value using
String s = arr.get(0);
This is because your string array is null. Declare it with the size as
String[] arr = new String[size];
Try Array List. use the following code in your main java
final ArrayList<String> list = new ArrayList<String>();
Button button= (Button) findViewById(R.id.buttonId);
final EditText editText = (EditText) findViewById(R.id.editTextId)
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
list.add(editText.getText().toString());
}
});
To avoid duplication in arraylist .You can use arraylist for faster then String array
ArrayList<String> list = new ArrayList<String>();
list.add("Krishna");
list.add("Krishna");
list.add("Kishan");
list.add("Krishn");
list.add("Aryan");
list.add("Harm");
System.out.println("List"+list);
HashSet hs = new HashSet();
hs.addAll(list);
list.clear();
list.addAll(hs);

How can I save and restore checked items with simple_list_item_checked?

I want to know the best way to save and restore checked items, using on adapter the "simple_list_item_checked", I've been trying for a long time using SharedPreferences, but didn't work. Could you give me some examples? Thanks in advance!
Here, found my old code for you. You can use SparseBooleanArray for this.
private SparseBooleanArray sbArray;
//set all of the items checked in the start
if (sbArray == null) {
for (int i = 0; i < listView.getCount(); i++) {
listView.setItemChecked(i, true);
}
}
selectedIdees = new ArrayList<>();
//if we already did some checking in filters, we get our previous selections.
if (sbArray != null) {
Log.i(LOG_TAG, "sbArray size " + sbArray.size());
for (int i = 0; i < sbArray.size(); i++) {
int key = sbArray.keyAt(i);
if (sbArray.get(key)) {
listView.setItemChecked(key, true);
}
Then somewhere I placed okButton and set onClickListener to it.
okBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sbArray = listView.getCheckedItemPositions();
Log.i(LOG_TAG, "sbArray created. size= " + sbArray.size());
for (int i = 0; i < sbArray.size(); i++) {
int key = sbArray.keyAt(i);
if (sbArray.get(key)) {
selectedIdees.add(key + 1);
Log.i(LOG_TAG, "added + " + (key + 1));
}
Then I suggest to save it in shared prefs, creating the parcelable wrapper around it.

Shared Preference: Retrieve and Display the data stored

I have make used of shared preference to store my data into MyUserChoice.xml:
<string name="MyUserChoice">ApplicationInfo{1ebad2cb com.example.user.example},
ApplicationInfo{15c7caa8 com.android.gallery},
ApplicationInfo{bc0a9c1 com.android.quicksearchbox}</string>
I have tried to retrieve the 3 string above.
for (int i = 0; i < count; i++) {
String currentItem = (String) myList.getAdapter()
.getItem(i);
if (selectedItems.contains(currentItem)) {
myList.setItemChecked(i, true);
Toast.makeText(getApplicationContext(),
"Current Item: " + currentItem,
Toast.LENGTH_LONG).show();
} else {
myList.setItemChecked(i, false);
}
}
What I want to achieve is that upon I relaunch my app, it should display each of this string one after another.
Current Item: ApplicationInfo{1ebad2cb com.example.user.example},
Current Item: ApplicationInfo{15c7caa8 com.android.gallery},
Current Item: ApplicationInfo{bc0a9c1 com.android.quicksearchbox}
Instead, it returns nothing and I saw this in my logcat:
10-09 01:19:18.756 1311-1311/com.android.systemui W/ResourceType﹕ No package identifier when getting value for resource number 0x00000000
10-09 01:19:18.756 1311-1311/com.android.systemui W/PackageManager﹕ Failure retrieving resources for com.example.checkboxsharedpreferences: Resource ID #0x0
10-09 01:19:18.781 1311-1327/com.android.systemui I/art﹕ Background sticky concurrent mark sweep GC freed 10643(410KB) AllocSpace objects, 0(0B) LOS objects, 0% free, 22MB/22MB, paused 5.699ms total 16.577ms
10-09 01:19:19.371 931-931/? W/SurfaceFlinger﹕ couldn't log to binary event log: overflow.
Anyone knows what's wrong with my coding? Hereby attached is my MainActivity.java:
ListView myList;
Button getChoice, clearAll, selectAll;
SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "MyUserChoice" ;
ArrayList<String> selectedItems = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myList = (ListView)findViewById(android.R.id.list);
getChoice = (Button)findViewById(R.id.getchoice);
clearAll = (Button)findViewById(R.id.clearall);
selectAll = (Button)findViewById(R.id.selectall);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice);
myList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
myList.setAdapter(adapter);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if(sharedpreferences.contains(MyPREFERENCES)){
LoadSelections();
}
getChoice.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
String selected = "";
int cntChoice = myList.getCount();
SparseBooleanArray sparseBooleanArray = myList.getCheckedItemPositions();
for (int i = 0; i < cntChoice; i++) {
if (sparseBooleanArray.get(i)) {
selected += myList.getItemAtPosition(i).toString() + "\n";
System.out.println("Checking list while adding:" + myList.getItemAtPosition(i).toString());
SaveSelections();
}
}
Toast.makeText(MainActivity.this, selected, Toast.LENGTH_LONG).show();
}
});
clearAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ClearSelections();
}
});
selectAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SelectAllSelections();
}
});
packageManager = getPackageManager();
new LoadApplications().execute();
}
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.myList.getAdapter().getCount();
for (int i = 0; i < count; i++) {
if (this.myList.isItemChecked(i)) {
if (savedItems.length() > 0) {
savedItems += "," + this.myList.getItemAtPosition(i);
} else {
savedItems += this.myList.getItemAtPosition(i);
}
}
}
return savedItems;
}
private void LoadSelections() {
// if the selections were previously saved load them
if (sharedpreferences.contains(MyPREFERENCES.toString())) {
String savedItems = sharedpreferences.getString(MyPREFERENCES.toString(), "");
selectedItems.addAll(Arrays.asList(savedItems.split(",")));
int count = this.myList.getAdapter().getCount();
for (int i = 0; i < count; i++) {
String currentItem = (String) myList.getAdapter()
.getItem(i);
if (selectedItems.contains(currentItem)) {
myList.setItemChecked(i, true);
Toast.makeText(getApplicationContext(),
"Current Item: " + currentItem,
Toast.LENGTH_LONG).show();
} else {
myList.setItemChecked(i, false);
}
}
}
}
private void ClearSelections() {
// user has clicked clear button so uncheck all the items
int count = this.myList.getAdapter().getCount();
for (int i = 0; i < count; i++) {
this.myList.setItemChecked(i, false);
}
// also clear the saved selections
SaveSelections();
}
private void SelectAllSelections() {
// user has clicked clear button so uncheck all the items
int count = this.myList.getAdapter().getCount();
for (int i = 0; i < count; i++) {
this.myList.setItemChecked(i, true);
}
// also clear the saved selections then uncomment the below line.
// SaveSelections();
}
protected void onListItemClick(ListView l, View v, int position, long id){
super.onListItemClick(l, v, position, id);
ApplicationInfo app = applist.get(position);
try{
Intent intent = packageManager.getLaunchIntentForPackage(app.packageName);
/*if(intent != null){
startActivity(intent);
}*/
}catch(ActivityNotFoundException e){
Toast.makeText(MainActivity.this,e.getMessage(), Toast.LENGTH_LONG).show();
}catch(Exception e){
Toast.makeText(MainActivity.this,e.getMessage(), Toast.LENGTH_LONG).show();
}
}
private List<ApplicationInfo> checkForLaunchIntent(List<ApplicationInfo> list){
ArrayList<ApplicationInfo> appList = new ArrayList<ApplicationInfo>();
for(ApplicationInfo info : list){
try{
if(packageManager.getLaunchIntentForPackage(info.packageName)!=null){
appList.add(info);
}
}catch(Exception e){
e.printStackTrace();
}
}
return appList;
}
private class LoadApplications extends AsyncTask<Void, Void, Void>{
private ProgressDialog progress = null;
protected Void doInBackground(Void... params){
applist = checkForLaunchIntent(packageManager.getInstalledApplications(PackageManager.GET_META_DATA));
listadapter = new AppAdapter(MainActivity.this, R.layout.activity_list_app, applist);
return null;
}
protected void onPostExecute(Void result){
setListAdapter(listadapter);
progress.dismiss();
super.onPostExecute(result);
}
protected void onPreExecute(){
progress = ProgressDialog.show(MainActivity.this, null, "Loading apps info...");
super.onPreExecute();
}
}
}
Change MyPREFERENCES.toString() to MyPREFERENCES.It is already String.No need to use .toString();
SharedPreferences.Editor prefEditor = sharedpreferences.edit();
String savedItems = getSavedItems();
prefEditor.putString(MyPREFERENCES, savedItems);
prefEditor.commit();
Retrieving data from SharedPreferences:
SharedPreferences sharedpreferences= getSharedPreferences(PREF_NAME, MODE_PRIVATE);
String channel = sharedpreferences.getString(MyPREFERENCES, "null");
this
sharedpreferences.contains(MyPREFERENCES.toString())
isn't returning something usefull.
replace it with that
!sharedpreferences.getString(MyPREFERENCES, "").equals("")

get checked items from listview in android

I have a dynamic listview with one text and one checkbox per line.when i click a button.,i need to get all checked item names & Unchecked item names separately as arraylilst.How could i do that.Examples are much better..
I used..
SparseBooleanArray checked = mainlw.getCheckedItemPositions();
for (int i = 0; i < checked.size(); i++) {
if(checked.valueAt(i) == true) {
Planet tag = (Planet) mainlw.getItemAtPosition(checked.keyAt(i));
String selectedName=tag.getName();
Toast.makeText(getApplicationContext(), selectedName, Toast.LENGTH_SHORT).show();
}
}
Try this out and implement this logic according to your requirement.
int cntChoice = myList.getCount();
String checked = "";
String unchecked = "";
SparseBooleanArray sparseBooleanArray = myList.getCheckedItemPositions();
for(int i = 0; i < cntChoice; i++)
{
if(sparseBooleanArray.get(i) == true)
{
checked += myList.getItemAtPosition(i).toString() + "\n";
}
else if(sparseBooleanArray.get(i) == false)
{
unchecked+= myList.getItemAtPosition(i).toString() + "\n";
}
}
use CHOICE_MODE_MULTIPLE in your ListView and use getCheckedItemPositions() to get the checked ones.
So Onclick of button u can do this,From this you will get the items that are checked:-
#Override
public void onClick(View v)
{
System.out.println("check"+getListView().getCheckItemIds().length);
for (int i = 0; i < getListView().getCheckItemIds().length; i++)
{
System.out.println(getListView().getAdapter().getItem((int)getListView().getCheckItemIds()[i]).toString());
}
}

Categories

Resources