I am trying to restore the previous state of my Checkboxes. I have nearly 20 checkbox in my Activity and what i want is when i restart my app, all the checkbox should be checked if it was checked before exiting the app. As i am using a custom adapter so i found it very difficult to achieve.
Here is my adapter's code -
public class IconAdapter extends BaseAdapter
{
private Activity activity;
private Object[] data;
private ArrayList<HashMap<String,String>> listItems;
public static LayoutInflater inflater = null;
private PackageManager pm;
public ArrayList<Boolean> itemChecked = null;
public ArrayList<String> itemSelected = new ArrayList<String>();
public ArrayList<CheckBox> ctv = new ArrayList<CheckBox>();
//TextView textView;
CheckBox cb;
//ImageView imageView;
public CompleteTaskManager ctm = new CompleteTaskManager();
public IconAdapter(Activity a, ArrayList<HashMap<String,String>> items)
{
activity = a;
listItems = items;
data = items.toArray();
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
pm = a.getPackageManager();
if(itemChecked==null){
itemChecked = new ArrayList<Boolean>();
for(int i = 0; i < items.size(); i++)
{
itemChecked.add(i,false);
}}
for(int i = 0; i < items.size(); i++)
{
itemSelected.add(i," ");
}
for(int i = 0; i < items.size(); i++)
{
cb = new CheckBox(a);
ctv.add(i,cb);
}
}
public int getCount() {
return listItems.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public static class ViewHolder{
public TextView textView;
public ImageView imageView;
public CheckBox checkBox;
}
public View getView(final int position, View convertView, ViewGroup parent)
{
View row = convertView;
final ViewHolder holder;
if(convertView==null)
{
row = inflater.inflate(R.layout.item, parent, false);
holder = new ViewHolder();
holder.textView = (TextView)row.findViewById(R.id.text1);
holder.checkBox = (CheckBox)row.findViewById(R.id.check); holder.checkBox.setChecked(itemChecked.get(position));
holder.imageView = (ImageView)row.findViewById(R.id.image);
row.setTag(holder);
}
else
{
holder = (ViewHolder)row.getTag();
}
String s = data[position].toString();
String[] tokens = s.split(",");
String[] mToken = tokens[0].split("=");
String taskName = mToken[1];
holder.textView.setText(taskName);
String[] mTokens = tokens[1].split("=");
final String pkgName = mTokens[1].substring(0, (mTokens[1].length() - 1));
holder.checkBox.setTag(position);
//this is how i am trying to restore the checked checkboxes.
**for(int i = 0; i < itemSelected.size(); i++)
{
if(itemSelected.contains(pkgName))
{
holder.checkBox.setChecked(true);
}
}**
ctv.set(position,holder.checkBox);
holder.checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton button, boolean b) {
Integer posClicked = (Integer)button.getTag();
if(b)
{
itemChecked.set(posClicked, true);
itemSelected.set(posClicked, pkgName);
}
else
{
itemChecked.set(posClicked,false);
itemSelected.set(posClicked, " ");
}
}
});
holder.checkBox.setChecked(itemChecked.get(position));
try{
Drawable icon = pm.getApplicationIcon(pkgName);
holder.imageView.setImageDrawable(icon);
}
catch (PackageManager.NameNotFoundException ne)
{
}
row.setId(position);
return row;
}
public boolean isChecked(int position)
{
return itemChecked.get(position);
}
public String getPkgName(int position)
{
return itemSelected.get(position);
}
public void removeItem(int position)
{
listItems.remove(position);
}
}
and here is code in which i am trying to restore my pkgNames. I picked pkgName because i have noticed position could be shuffled as my list is dynamic but pkgName related to each item will stay same.
#Override
public void onPause()
{
super.onPause();
save(notes.itemSelected);
}
#Override
public void onResume()
{
super.onResume();
ArrayList<String> checkOld = load();
for (int i = 0 ; i < checkOld.size(); i++)
{
notes.itemSelected = checkOld;
}
}
#Override
public void onRestart()
{
super.onRestart();
ArrayList<String> checkOld = load();
for (int i = 0 ; i < checkOld.size(); i++)
{
notes.itemSelected = checkOld;
}
}
private void save(final ArrayList<String> isChecked) {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
for(Integer i = 0; i < isChecked.size(); i++)
{
editor.putString(i.toString(), isChecked.get(i));
}
editor.commit();
}
private ArrayList<String> load() {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
ArrayList<String> reChecked = new ArrayList<String>();
for(Integer i = 0; i < notes.getCount(); i++)
{
reChecked.add(i, sharedPreferences.getString(i.toString(), " "));
}
return reChecked;
}
}
Please Please HELP!!!!
See how-do-i-save-an-android-applications-state
Related
I am developing an android app for Restaurant Ordering system, Now I want to add some Description for the particular Item so that I had added the Dialogfragment and set it to the Custom Adapter ImageView Click listener, the dialog fragment showing correctly, as well as data, is also passing from edit text, but it shows in the last element of the listview.
I had tried various procedures and method but it still getting the same please help me, guys.
I am attaching the screen shots of my project
New TABLE ACTIVITY WHERE IS LISTVIEW
DIALOG FRAGMENT
AFTER ADDING DIALOG FRAGMENT DATA
Here I am Adding Custom Adapter Code
public class CustomAdapter_MenuList extends BaseAdapter{
Activity activity;
Context CONTEXT;
LayoutInflater layoutInflater;
public List<GetandSet> details;
CustomAdapter_MenuList.ViewHolder viewHolder;
GetandSet getandSet;
TextView GrandTotal;
TextView txtTotalItems;
ArrayList<String>Desciption = new ArrayList<>();
private EditText mInput;
Button btnadd,btnclose;
String desc;
public CustomAdapter_MenuList(Activity activity,Context context, List<GetandSet> details,TextView txtGrandtotal,TextView txttotalitems) {
this.activity = activity;
this.CONTEXT = context;
this.details = details;
this.GrandTotal = txtGrandtotal;
this.txtTotalItems = txttotalitems;
this.layoutInflater = (LayoutInflater) LayoutInflater.from(context);
}
#Override
public int getCount() {
return details.size();
}
#Override
public Object getItem(int position) {
return details.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
getandSet = new GetandSet();
final float menu_rate =
Float.parseFloat(details.get(position).getRate());
if (convertView == null) {
LayoutInflater inflater =
(LayoutInflater)CONTEXT.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.newtable_template, null);
viewHolder = new CustomAdapter_MenuList.ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (CustomAdapter_MenuList.ViewHolder) convertView.getTag();
}
for(int i = 0 ; i<details.size(); i++)
{
for(int j = i+1; j < details.size(); j++)
{
if(details.get(j).getMenu_id().equals(details.get(i).getMenu_id()))
{
details.remove(j);
j--;
getandSet = details.get(i);
getandSet.Menu_qty = details.get(i).getMenu_qty() + 1;
}
}
}
viewHolder.txtsrno.setText(details.get(position).getMenu_id());
viewHolder.txtsrno.setVisibility(View.INVISIBLE);
viewHolder.txtsrnotem.setText(String.valueOf(position+1));
viewHolder.txtmname.setText(details.get(position).getM_name());
viewHolder.txtrate.setText(details.get(position).getRate());
getandSet = details.get(position);
getandSet.Menu_price = menu_rate * getandSet.Menu_qty;
viewHolder.txtqty.setText(getandSet.Menu_qty+"");
viewHolder.txtprice.setText(getandSet.Menu_price +"");
GrandTotal.setText(String.valueOf(grandTotal(details)));
txtTotalItems.setText(String.valueOf(grandTotal(details,position)));
notifyDataSetChanged();
//Add Button Code
viewHolder.btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getandSet = details.get(position);
//updateQuantity(position, txtqty,itemrate, 1);
getandSet.Menu_qty = getandSet.Menu_qty + 1;
getandSet.Menu_price = menu_rate * getandSet.Menu_qty;
viewHolder.txtqty.setText(""+getandSet.Menu_qty);
viewHolder.txtprice.setText(getandSet.Menu_price +"");
notifyDataSetChanged();
}
});
//Minus Button
viewHolder.btnsub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getandSet = details.get(position);
//updateQuantity(position, txtqty,itemrate, -1);
if(getandSet.Menu_qty > 1)
{
getandSet.Menu_qty = getandSet.Menu_qty - 1;
getandSet.Menu_price = menu_rate * getandSet.Menu_qty ;
viewHolder.txtqty.setText(""+getandSet.Menu_qty);
viewHolder.txtprice.setText(getandSet.Menu_price +"");
notifyDataSetChanged();
}
}
});
//Add Description Button
viewHolder.btn_Desc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openDialog(position);
}
});
return convertView;
}
//View Holder Class
private class ViewHolder {
TextView txtsrno,txtmname, txtqty,txtrate,txtprice,txtsrnotem,txtdesc;
Button btnadd,btnsub;
ImageView btn_Desc;
public ViewHolder(View view)
{
txtsrno = (TextView)view.findViewById(R.id.txt_NTsrno);
txtsrnotem = (TextView)view.findViewById(R.id.txt_NT_srno);
txtmname = (TextView)view.findViewById(R.id.txt_NT_Item);
txtqty = (TextView)view.findViewById(R.id.txt_Nt_qty);
txtrate = (TextView)view.findViewById(R.id.txt_Nt_rate);
txtprice = (TextView)view.findViewById(R.id.txt_NT_price);
txtdesc = (TextView)view.findViewById(R.id.txt_NT_desc);
btnadd = (Button)view.findViewById(R.id.btn_add);
btnsub = (Button)view.findViewById(R.id.btn_sub);
btn_Desc = (ImageView) view.findViewById(R.id.img_desc);
}
}
//Grand - Total
private float grandTotal(List<GetandSet> items){
float totalPrice = 0;
for(int i = 0 ; i < items.size(); i++) {
totalPrice += items.get(i).getMenu_price();
}
return totalPrice;
}
//Number of Items
private int grandTotal(List<GetandSet> items,int p){
int totalitems = 0;
for(int i = 0 ; i < items.size(); i++) {
totalitems += 1;
}
return totalitems;
}
private void openDialog(final int position){
LayoutInflater inflater = LayoutInflater.from(activity);
View subView = inflater.inflate(R.layout.dialogfragment_description, null);
mInput = subView.findViewById(R.id.edt_desc);
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle("Add Description");
builder.setView(subView);
final AlertDialog alertDialog = builder.create();
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
desc = mInput.getText().toString();
//getandSet = details.get(position);
details.get(position).setDes(desc);
viewHolder.txtdesc.setText(details.get(position).getDes().toString());
notifyDataSetChanged();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
builder.show();
}
}
viewHolder.txtdesc.setText(details.get(position).getDes().toString());
notifyDataSetChanged();
Just put this lines after completion of openDialog() method
This loop return only visible position values.However I need the values of child items that are invisible.
for (int i = 0; i < material_issue_list.getCount(); i++) {
View layout = materialIssueAdapter.getViewByPositio(i, material_issue_list);
LinearLayout listItem = (LinearLayout) materialIssueAdapter.getViewByPositio(i, material_issue_list);
String batchSTR = ((AutoCompleteTextView) listItem.findViewById(R.id.batch_AutoComplete)).getText().toString();
String qtySTR = ((EditText) listItem.findViewById(R.id.issue_qty_ETD)).getText().toString();}
My full adapter class,Some one help me suggest to get the correct output.My problem I'm getting null values from the views that are invisible.
Only the visible values are being updated to arraylist.
Thanks in advance.
public class IssueMaterialAdapter extends BaseAdapter {
private Activity activity;
public static ArrayList Dummylist;
private static LayoutInflater inflater = null;
public Resources res;
public static ArrayList<BatchNav> batchNavs_Arr;
static ArrayList<String> batch_Arr;
public static ArrayList<String> batch_data;
public static ArrayList<String> issue_qty;
LinkedHashSet<String> hashSet;
public static ArrayList<BatchModel> batchModels = new ArrayList<BatchModel>();
public static HashMap<ViewHolder, String> batch_map;
public static HashMap<ViewHolder, String> qty_map;
HashMap<String, String> mValues = new HashMap<String, String>();
ArrayList<SaveDataModel> saveDataModels;
public IssueMaterialAdapter(Activity a, ArrayList dummy) {
activity = a;
Dummylist = dummy;
loadBatch();
this.batch_map = new HashMap<>();
inflater = (LayoutInflater) activity.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
if (Dummylist.size() <= 0)
return 1;
return Dummylist.size();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View vi = convertView;
final ViewHolder holder;
if (convertView == null) {
vi = inflater.inflate(R.layout.material_issue_details_list, null);
holder = new ViewHolder();
holder.batch = (AutoCompleteTextView) vi.findViewById(R.id.batch_AutoComplete);
holder.issue = (EditText) vi.findViewById(R.id.issue_qty_ET);
holder.material_descrption = (TextView) vi.findViewById(R.id.material_desc);
holder.unit_issue = (EditText) vi.findViewById(R.id.unit_issue_ET);
holder.matnr = (TextView) vi.findViewById(R.id.matnr);
holder.prdgrp = (TextView) vi.findViewById(R.id.prod_grp);
vi.setTag(holder);
batch_map.put(holder, "");
FilterWithSpaceAdapter<String> farmer_co_no_adapter = new FilterWithSpaceAdapter<String>(activity,
R.layout.custom_items, batch_Arr);
holder.batch.setAdapter(farmer_co_no_adapter);
holder.batch.setThreshold(1);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
if (Dummylist.size() == AgriDistributionActivity.get_materials.size()) {
holder.material_descrption.setText(AgriDistributionActivity.get_materials.get(position));
holder.matnr.setText(AgriDistributionActivity.get_matnr.get(position));
holder.prdgrp.setText(AgriDistributionActivity.selected_prdgrp.get(position));
}
try {
if (saveDataArr.size() > 0) {
holder.batch.setText(saveDataArr.get(position).getBatch());
holder.issue.setText(saveDataArr.get(position).getQty());
holder.unit_issue.setText(saveDataArr.get(position).getQty_uom());
}
} catch (Exception e) {
}
return vi;
}
public static class ViewHolder {
public EditText issue, unit_issue;
public AutoCompleteTextView batch;
public TextView material_descrption, matnr,prdgrp;
}
private void loadBatch() {
batch_Arr = new ArrayList<String>();
batchNavs_Arr = new ArrayList<BatchNav>();
hashSet = new LinkedHashSet<>();
BatchNavEntityCollection batchNavEntityCollection = BatchNavEntityCollection.getInstance();
batchNavs_Arr = batchNavEntityCollection.getBatchOutVal();
for (int i = 0; i < batchNavs_Arr.size(); i++) {
String batch = batchNavs_Arr.get(i).getCharg();
batch_Arr.add(batch);
hashSet.addAll(batch_Arr);
batch_Arr.clear();
batch_Arr.addAll(hashSet);
}
}
public View getViewByPositio(int position, ListView listView) {
final int firstListItemPosition = listView.getFirstVisiblePosition();
final int lastListItemPosition = firstListItemPosition + listView.getChildCount() - 1;
if (position < firstListItemPosition || position > lastListItemPosition) {
return listView.getAdapter().getView(position, null, listView);
} else {
final int childIndex = position - firstListItemPosition;
return listView.getChildAt(childIndex);
}
}
}
You have saveDataArr list which holds all your data.
You can add a getter if you want to do it from an activity , add something like this to your adapter :
private SaveDataModelsendLog(int position) {
return saveDataArr(position);
}
That should do the trick , having said all that you should also look at the difference between static and non-static variables ,
it seems like you have to many of them ,
Enjoy.
I have an app in which listview with two arraylist suppose 1st "listStorage" and second is "existingDataSet" i have to compare these two arraylist value if found same then enable toggle of that index.
code:-
private LayoutInflater layoutInflater;
private List<AllAppList> listStorage;
private Context mContext;
ArrayList<WhiteListModel> newDataSet, existingDataSet;
private String TAG = AppAdapter.class.getSimpleName();
private MySharedPreference sharedPreference;
private WhiteListModel whiteListModel;
private Gson gson;
public AppAdapter(Context context, List<AllAppList> customizedListView) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
listStorage = customizedListView;
this.mContext = context;
existingDataSet = new ArrayList<>();
newDataSet = new ArrayList<>();
gson = new Gson();
sharedPreference = new MySharedPreference(mContext);
whiteListModel = new WhiteListModel();
//retrieve data from shared preference
String jsonScore = sharedPreference.getAppsArrayListData();
Type type = new TypeToken<ArrayList<WhiteListModel>>() {
}.getType();
existingDataSet = gson.fromJson(jsonScore, type);
}
#Override
public int getCount() {
return listStorage.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder listViewHolder;
if (convertView == null) {
listViewHolder = new ViewHolder();
convertView = layoutInflater.inflate(R.layout.installed_app_list_item, parent, false);
listViewHolder.textInListView = (TextView) convertView.findViewById(R.id.list_app_name);
listViewHolder.imageInListView = (ImageView) convertView.findViewById(R.id.app_icon);
listViewHolder.switchCompat = (SwitchCompat) convertView.findViewById(R.id.toggleButton);
convertView.setTag(listViewHolder);
} else {
listViewHolder = (ViewHolder) convertView.getTag();
}
listViewHolder.textInListView.setText(listStorage.get(position).getName());
listViewHolder.imageInListView.setImageDrawable(listStorage.get(position).getIcon());
for (int i = 0; i<existingDataSet.size(); i++){
for (int j= 0; j<listStorage.size(); j++){
if (existingDataSet.get(i).getPackName().equalsIgnoreCase(listStorage.get(j).getPackName())){
listViewHolder.switchCompat.setChecked(true);
}
}
}
listViewHolder.switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(final CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
new AlertDialog.Builder(mContext, R.style.AppCompatAlertDialogStyle).setTitle("Warning").setMessage("You want to whiteList this application?").setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Adding items in Dataset
AllAppList appList = listStorage.get(position);
whiteListModel.setName(appList.getName());
whiteListModel.setPackName(appList.getPackName());
if (existingDataSet != null) {
existingDataSet.add(whiteListModel);
saveScoreListToSharedpreference(existingDataSet);
} else {
newDataSet.add(whiteListModel);
saveScoreListToSharedpreference(newDataSet);
}
//Notifying adapter data has been changed.....
notifyDataSetChanged();
listViewHolder.switchCompat.setChecked(false);
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
listViewHolder.switchCompat.setChecked(false);
}
}).show();
}
}
});
return convertView;
}
/**
* Save list of scores to own sharedpref
*
* #param whiteListApps
*/
private void saveScoreListToSharedpreference(ArrayList<WhiteListModel> whiteListApps) {
Gson gson = new Gson();
//convert ArrayList object to String by Gson
String jsonScore = gson.toJson(whiteListApps);
Log.e(TAG, "LIST::" + jsonScore);
//save to shared preference
sharedPreference.saveAppsArrayListData(jsonScore);
}
private static class ViewHolder {
static SwitchCompat switchCompat;
TextView textInListView;
ImageView imageInListView;
}
}
for (int i = 0 ; i < existingDataSet.size() ; i++){
if (existingDataSet.get(i).getPackName().equalsIgnoreCase(listStorage.get(i).getPackName())){
listViewHolder.switchCompat.setChecked(true);
}
}
}
can you try this? switch should retain its value false if not contains within 2 list when on getView because it trigger several times.
boolean isChecked = false
for (int i = 0; i<existingDataSet.size(); i++){
for (int j= 0; j<listStorage.size(); j++){
if (existingDataSet.get(i).getPackName().equalsIgnoreCase(listStorage.get(j).getPackName())){
isChecked = true;
}
}
}
listViewHolder.switchCompat.setChecked(isChecked);
I'm developing an android app which has a custom listview with a checkbox. I want to pass all the checked items from one activity to another. how should I pass them? and where should I manage the checkbox (to get all the checked items) in the custom adapter or the activity?
Note: I retrieve all the data from my server using json response.
Here's my Model :
public class Groups {
public String name;
public boolean selected= false;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public Groups() {
}
}
My Adapter:
public class AdapterMainActivity extends BaseAdapter{
Activity activity;
private LayoutInflater inflater;
List<Groups> groupsList;
public AdapterMainActivity(Activity activity, List<Groups> groupses) {
this.activity = activity;
this.groupsList = groupses;
}
#Override
public int getCount() {
return groupsList.size();
}
#Override
public Object getItem(int position) {
return groupsList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (inflater == null) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.custom_list, null);
TextView name = (TextView) convertView.findViewById(R.id.textViewName);
final CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
final Groups groups = groupsList.get(position);
name.setText(groupsList.get(position).getName());
checkBox.setChecked(groups.selected);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
groups.selected = isChecked;
MainActivity.getInstance().updateArrayList(groupsList);
}
});
}
return convertView;
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
ListView listViewGroups;
Button buttonSentToActivity;
List<Groups> groupsList;
List<Groups> resultGroupList;
ArrayList<Boolean> areChecked;
List<String> finalArray;
private AdapterMainActivity adapterMainActivity;
static MainActivity yourActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
yourActivity = this;
groupsList= new ArrayList<Groups>();
resultGroupList= new ArrayList<Groups>();
ReadGroup(37);
adapterMainActivity = new AdapterMainActivity(this, groupsList);
listViewGroups = (ListView) findViewById(R.id.listViewGroups);
listViewGroups.setAdapter(adapterMainActivity);
buttonSentToActivity = (Button) findViewById(R.id.buttonSendTo2Activity);
buttonSentToActivity.setOnClickListener(buttonSentToActivityListener);
Log.e("Group list size ", String.valueOf(groupsList.size()));
finalArray = new ArrayList<>();
for (int i = 0; i < resultGroupList.size(); i++) {
if (resultGroupList.get(i).selected) {
finalArray.add(resultGroupList.get(i).getName());
Log.e("final array size", String.valueOf(finalArray.size()));
}
}
}
public void ReadGroup(long cid) {
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response.toString());
JSONArray readArray = jsonObject.getJSONArray("groups");
for (int i = 0; i < readArray.length(); i++) {
Log.e("i is: ", String.valueOf(i));
JSONObject jssonRow = readArray.getJSONObject(i);
String groupName = jssonRow.getString("name");
Groups groups = new Groups();
groups.setName(groupName);
Log.e("NAME is: ", groupName);
groupsList.add(groups);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapterMainActivity.notifyDataSetChanged();
}
};
Log.e("Client id is: ", String.valueOf(cid));
ReadGroupRequesr readGroupRequest = new ReadGroupRequesr(cid, responseListener);
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
queue.add(readGroupRequest);
Log.e("out of the loop", "");
}
public static MainActivity getInstance() {
return yourActivity;
}
public void updateArrayList(List<Groups> arrayList) {
this.resultGroupList = arrayList;
}
View.OnClickListener buttonSentToActivityListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
//Bundle b= new Bundle();
//b.putStringArrayList("arrayList", (ArrayList<String>) finalArray);
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putStringArrayListExtra("arrayList", (ArrayList<String>) finalArray);
//intent.putExtras(b);
Log.e("final array size", String.valueOf(finalArray.size()));
startActivity(intent);
}
};
}
At the very first, manage your checkboxes :
In your activity class add a boolean array or arraylist having size same as your list array size and initialize it with all value as false initially :
String[] titlesArray;
ArrayList<Boolean> arrChecked;
// initialize arrChecked boolean array and add checkbox value as false initially for each item of listview
arrChecked = new ArrayList<Boolean>();
for (int i = 0; i < titles.size(); i++) {
arrChecked.add(false);
}
Now replace your adapter class with this :
class VivzAdapter extends ArrayAdapter<String> implements OnCheckedChangeListener {
Context context;
int[] images;
String[] titlesArray, descrptionArray;
List<Integer> positions = new ArrayList<Integer>();
ArrayList<Boolean> arrChecked;
VivzAdapter(Context context, String[] titles, int[] images, String[] description, ArrayList<Boolean> arrChecked) {
super(context, R.layout.single_row, R.id.textView1, titles);
this.context = context;
this.images = images;
this.titlesArray = titles;
this.descrptionArray = description;
this.arrChecked = arrChecked;
}
class MyViewHolder {
ImageView myImage;
TextView myTitle;
TextView myDescription;
CheckBox box;
MyViewHolder(View v) {
myImage = (ImageView) v.findViewById(R.id.imageView1);
myTitle = (TextView) v.findViewById(R.id.textView1);
myDescription = (TextView) v.findViewById(R.id.textView2);
box = (CheckBox) v.findViewById(R.id.checkBox1);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
MyViewHolder holder = null;
if (row == null) {
// 1.Âștime
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//row contem RelativeLayout(root) em single_row.xml
row = inflater.inflate(R.layout.single_row, parent, false);
holder = new MyViewHolder(row);
row.setTag(holder);
//Log.d("VIVZ", "Creating a new Row");
} else {
//reciclamos aqui, qeremos usar antigo objecto holder
holder = (MyViewHolder) row.getTag();
//Log.d("VIVZ", "Recycling stuff");
}
holder.myImage.setImageResource(images[position]);
holder.myTitle.setText(titlesArray[position]);
holder.myDescription.setText(descrptionArray[position]);
//set position as id
holder.box.setId(position);
//set onClickListener of checkbox rather than onCheckedChangeListener
holder.box.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int id = v.getId();
if (arrChecked.get(id)) {
//if checked, make it unchecked
arrChecked.set(id, false);
} else {
//if unchecked, make it checked
arrChecked.set(id, true);
}
}
});
//set the value of each checkbox from arrChecked boolean array
holder.box.setChecked(arrChecked.get(position));
return row;
}
}
After that, implement click listener of send button say btnSend button (I am considering that you are sending your data from one activity to another activity on click of send button) :
btnSend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<String> arrTempList = new ArrayList();
for(int i=0; i<titles.size(); i++){
if(arrChecked.get(i) == true){
arrTempList.add(titles[i]);
}
}
// here you can send your arrTempList which is having checked items only
}
});
Here's the solution for this Question:
My adapter:
public class ChooseContactsAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
public ArrayList<Contacts> contactsList;
public CheckBox checkBoxAdapter;
public ChooseContactsAdapter(Activity activity, ArrayList<Contacts> group) {
this.activity = activity;
this.contactsList = group;
}
#Override
public int getCount() {
return contactsList.size();
}
#Override
public Object getItem(int position) {
return contactsList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.custom_choose_contacts_sms,
null);
final TextView fNAme = (TextView) convertView.findViewById(R.id.textViewCustomSMSSelectContactFName);
TextView LName = (TextView) convertView.findViewById(R.id.textViewCustomSMSSelectContactLName);
checkBoxAdapter = (CheckBox) convertView.findViewById(R.id.checkBoxSelectContact);
checkBoxAdapter.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
CheckBox cb = (CheckBox) view;
Contacts contacts = (Contacts) cb.getTag();
contacts.setSelected(cb.isChecked());
Toast.makeText(activity.getApplicationContext(),
"Clicked on Checkbox: " + cb.getText() +
" is " + cb.isChecked(),
Toast.LENGTH_LONG).show();
}
});
final Contacts contacts = contactsList.get(position);
fNAme.setText(contacts.getContactFName());
LName.setText(contacts.getContactLName());
checkBoxAdapter.setChecked(contacts.isSelected());
checkBoxAdapter.setTag(contacts);
}
return convertView;
}
}
In my activity I have button to go from 1 activity to the 2 activity:
private View.OnClickListener buttonSubmitGroupListener =new View.OnClickListener() {
#Override
public void onClick(View view) {
List <Integer> contactsIDArray= new ArrayList<Integer>();
List<Contacts> arrayOfContacts= chooseContactsAdapter.contactsList;
for(int i=0; i< arrayOfContacts.size(); i++){
Contacts contacts= arrayOfContacts.get(i);
if(contacts.isSelected()==true){
contactsIDArray.add(contacts.getContactID());
}
}
for (int i = 0; i < contactsIDArray.size(); i++) {
Log.e("Id Array size ", String.valueOf(contactsIDArray.size()));
Log.e("Selected id ", String.valueOf(contactsIDArray.get(i)));
}
intent = new Intent(getApplicationContext(), SendSMSActivity.class);
Bundle b = new Bundle();
b.putIntegerArrayList("checkedContacts", (ArrayList<Integer>) contactsIDArray);
intent.putExtras(b);
startActivity(intent);
}
};
Second Activity add this code:
Bundle b = getIntent().getExtras();
List<Integer> result = new ArrayList<Integer>();
result = b.getIntegerArrayList("checkedContacts");
#Override
public void onPause()
{
super.onPause();
save(notes.itemSelected);
}
#Override
public void onResume()
{
super.onResume();
notes.itemSelected.clear();
notes.itemSelected = load();
}
#Override
public void onRestart()
{
super.onRestart();
notes.itemSelected.clear();
notes.itemSelected = load();
}
private void save(final ArrayList<String> isChecked) {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
for(Integer i = 0; i < isChecked.size(); i++)
{
editor.putString(i.toString(), isChecked.get(i));
}
editor.commit();
}
private ArrayList<String> load() {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
ArrayList<String> reChecked = new ArrayList<String>();
for(Integer i = 0; i < notes.getCount(); i++)
{
String s= i.toString();
Log.e(TAG, s);
reChecked.add(i, sharedPreferences.getString(s, "empty"));
}
return reChecked;
}
Here is my custom adapter whose instance called notes i am using in above code.
public class IconAdapter extends BaseAdapter
{
private Activity activity;
private Object[] data;
private ArrayList<HashMap<String,String>> listItems;
public static LayoutInflater inflater = null;
private PackageManager pm;
public ArrayList<Boolean> itemChecked = new ArrayList<Boolean>();
public ArrayList<String> itemSelected = new ArrayList<String>();
public ArrayList<CheckBox> ctv = new ArrayList<CheckBox>();
//TextView textView;
CheckBox cb;
//ImageView imageView;
public CompleteTaskManager ctm = new CompleteTaskManager();
public IconAdapter(Activity a, ArrayList<HashMap<String,String>> items)
{
activity = a;
listItems = items;
data = items.toArray();
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
pm = a.getPackageManager();
for(int i = 0; i < items.size(); i++)
{
itemChecked.add(i,false);
}
for(int i = 0; i < items.size(); i++)
{
itemSelected.add(i, " ");
}
for(int i = 0; i < items.size(); i++)
{
cb = new CheckBox(a);
ctv.add(i,cb);
}
}
public int getCount() {
return listItems.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public static class ViewHolder{
public TextView textView;
public ImageView imageView;
public CheckBox checkBox;
}
public View getView(final int position, View convertView, ViewGroup parent)
{
View row = convertView;
final ViewHolder holder;
if(convertView==null)
{
row = inflater.inflate(R.layout.item, parent, false);
holder = new ViewHolder();
holder.textView = (TextView)row.findViewById(R.id.text1);
holder.checkBox = (CheckBox)row.findViewById(R.id.check);
holder.imageView = (ImageView)row.findViewById(R.id.image);
row.setTag(holder);
}
else
{
holder = (ViewHolder)row.getTag();
}
String s = data[position].toString();
String[] tokens = s.split(",");
String[] mToken = tokens[0].split("=");
String taskName = mToken[1];
holder.textView.setText(taskName);
String[] mTokens = tokens[1].split("=");
final String pkgName = mTokens[1].substring(0, (mTokens[1].length() - 1));
holder.checkBox.setTag(position);
holder.checkBox.setChecked(itemChecked.get(position));
/*for(int i = 0; i < itemSelected.length; i++)
{
if(itemSelected[i].equals(pkgName))
{
holder.checkBox.setChecked(true);
}
}*/
ctv.set(position,holder.checkBox);
holder.checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton button, boolean b) {
Integer posClicked = (Integer)button.getTag();
if(b)
{
itemChecked.set(posClicked, b);
itemSelected.set(posClicked, pkgName);
}
else
{
itemChecked.set(posClicked, b);
itemSelected.set(posClicked, " ");
}
}
});
holder.checkBox.setChecked(itemChecked.get(position));
try{
Drawable icon = pm.getApplicationIcon(pkgName);
holder.imageView.setImageDrawable(icon);
}
catch (PackageManager.NameNotFoundException ne)
{
}
row.setId(position);
return row;
}
public boolean isChecked(int position)
{
return itemChecked.get(position);
}
public String getPkgName(int position)
{
return itemSelected.get(position);
}
public void removeItem(int position)
{
listItems.remove(position);
}
}
Could anybody tell me why i am getting a ClassCastException at reChecked.add(i, sharedPreferences.getString(s, "empty"));.
I mean it's strange that its telling me that i am casting boolean into string but how???? i did not even used boolean anywhere in this code.
Note. - notes.itemSelected is an ArrayList of string type.
Please help.
Actually i figure it out why i was getting ClassCastException. first of all it wasn't MAC OSX which we were thinking was the reason for this exception. And i just found out why this exception was occurring.
Let me explain what happened. Before storing the ArrayList of String type i saved one ArrayList of type Boolean using same for() loop so it means that key with the name of i.toString() was already taken and i was calling my save() method in onPause() which was never called because i was not able to run my app on device or emulator because of this exception so the saved keys were never overwritten. And when i figured it out i just changed the key name to j+"0" (just a random one) and bang it's stopped throwing the exception.
P.S. Exception was there because the key was already used.
I hope it will help others who are facing or might face the same situation in future.
#Roflcoptr and #Durga I really appreciate your help guys thanks a lot.
Thanks.
A ClassCastException will occur when you are not type casting the data types properly. I have corrected your save method:
private void save(final ArrayList<String> isChecked) {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
for(Integer i = 0; i < isChecked.size(); i++)
{
editor.putString(i+"", isChecked.get(i));
}
editor.commit();
}
Similarly you should also change the code in your load method...
There reason has to be that you have a Shared Preferences with that key that is not a String.
The documentation says that in this case a ClassCastException is thrown: