#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:
Related
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 am stuck when trying to get the value of selected checkbox listview values in my activity. I don't know how to do it, can any one suggest me a resolution to this issue?. Here is my code :
public class CandidateAdapter extends BaseAdapter implements OnCheckedChangeListener {
Context ctxt;
private LayoutInflater mInflater;
private ArrayList<CandidateModel> candidateList = new ArrayList<CandidateModel>();
private SparseBooleanArray mCheckStates;
public CandidateAdapter(Context context,ArrayList<CandidateModel> candidateList) {
mInflater = LayoutInflater.from(context);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.candidateList = candidateList;
mCheckStates = new SparseBooleanArray(candidateList.size());
}
#Override
public int getCount() {
return candidateList.size();
}
#Override
public CandidateModel getItem(int position) {
return candidateList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder holder;
if(view == null){
view = mInflater.inflate(R.layout.table_row_candidate,null);
holder = new ViewHolder();
holder.candidateName = (TextView)view.findViewById(R.id.candidatenametxt);
holder.contactNumber = (TextView)view.findViewById(R.id.contactnumbertxt);
holder.email = (TextView)view.findViewById(R.id.emailtxt);
holder.contactCheckBox = (CheckBox)view.findViewById(R.id.contactchk);
view.setTag(holder);
}
else{
holder = (ViewHolder)view.getTag();
}
final CandidateModel cm = candidateList.get(position);
String contactNumber = cm.getContactNumber();
String candidateName = cm.getCandidateName();
String email = cm.getEmail();
if(!candidateName.equals("null") && candidateName!=null)
{
holder.candidateName.setText(cm.getCandidateName());
}
else{
holder.candidateName.setText("confidential");
}
if(!contactNumber.equals("null") && contactNumber!="" && contactNumber!=null && !contactNumber.equals("NA"))
{
holder.contactNumber.setText(cm.getContactNumber());
}
else{
holder.contactNumber.setVisibility(View.GONE);
}
if(!email.equals("null") && email!="" && email!=null && !email.equals("NA"))
{
holder.email.setText(cm.getEmail());
}
else{
holder.email.setVisibility(View.GONE);
}
holder.contactCheckBox.setTag(position);
holder.contactCheckBox.setChecked(mCheckStates.get(position, false));
holder.contactCheckBox.setOnCheckedChangeListener(this);
return view;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
private class ViewHolder{
public TextView candidateName;
public TextView contactNumber;
public TextView email;
public CheckBox contactCheckBox;
}
}
///Code in my activity. Here I am actually adding the data to the adapter.
i want the data of selected checkboxes from the list view, how would I achieve it?.
dataarray = datajsonobject.getJSONArray("candidateList");
CandidateAdapter ca = null;
final ArrayList<CandidateModel> candidateList = new ArrayList<CandidateModel>();
for (int i = 0; i < dataarray.length(); i++) {
JSONObject dataobject = new JSONObject();
dataobject = dataarray.getJSONObject(i);
String candidate_name = dataobject.getString("fullName");
String url = dataobject.getString("url");
String email = dataobject.getString("email");
String contactNumber = dataobject.getString("contactNumber");
String candidateId = dataobject.getString("candidateId");
//CandidateModel cm = new CandidateModel(candidate_name,score);
CandidateModel cm = new CandidateModel();
cm.setJobId(job_id);
cm.setCandidateName(candidate_name);
cm.setResumeURL(url);
cm.setContactNumber(contactNumber);
cm.setEmail(email);
cm.setSelected(false);
cm.setCandidateId(candidateId);
candidateList.add(cm);
}
ca = new CandidateAdapter(Candidate.this,candidateList);
clist.setAdapter(ca);
clist.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
CandidateModel selItem = candidateList.get(position);//get the selected RowItem from the list
Intent downloadResumeIntent = new Intent(
getApplicationContext(),
DownloadResume.class);
final String url = selItem.getResumeURL();
downloadResumeIntent.putExtra("url",url);
downloadResumeIntent.putExtra("jobId",job_id);
//downloadResumeIntent.putExtra("resumeUniqueID", uniqueResumeId);
startActivity(downloadResumeIntent);
Toast.makeText(getApplicationContext(), "CLICKED", Toast.LENGTH_SHORT).show();
}
});
Try to add one more boolean field in adapter item modle class CandidateModel :
public class CandidateModel {
private boolean isSelected;
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean isSelected) {
this.isSelected = isSelected;
}
}
Use isSelected field directly instead SparseBooleanArray or no need to SparseBooleanArray :
holder.contactCheckBox.setChecked(cm.isSelected());
holder.contactCheckBox..setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
cm.setSelected(isChecked);
}
});
Get checked all item :
public ArrayList<CandidateModel> getCheckAllItem(){
ArrayList<CandidateModel> candidateModelArrayList = new ArrayList<CandidateModel>();
for(CandidateModel model :candidateList){
if(model.isSelected()){
candidateModelArrayList.add(model);
}
}
return candidateModelArrayList
}
Check item at position :
public boolean isItemChecked (int index){
return candidateList.get(index).isSelected();
}
maintain arraylist globally in adapter maintain the check box state in the arraylist now you can get the arraylist in activity by calling the adaptet.arraylist;
If candidateList order remains the same all the time, then it is ok to use position as Tag value.
Try putting this method in your adapter and call it from activity.
public ArrayList<CandidateModel> GetCheckedItems(){
ArrayList<CandidateModel> checkedItems = new ArrayList<CandidateModel>();
for(int position = 0; position < candidateList.size(); position++){
if(mCheckStates.get(position))
checkedItems.add(candidateList.get(position));
}
return checkedItems;
}
Maybe i misunderstand your question :). Best regards.
Use the getter methods from class CandidateModel to retrieve all the data you want. eg: selItem.getResumeURL();
why do you need to know the checkbox's state if you know the position in the list that has been clicked? regardless of the answer you can use the already present method adapter.isChecked(position) to see if the checkbox is checked or not.
my app contains a list view which is being populated by a spinner value
this list contains toggle button in each row and for customization purpose i have used baseadapter in list view
i am changing image of toggle button on checked and unchecked
the functionality is going well on toggle button and listview but the problem occurrs when i closes the app and then again opens it it gets refreshed and the toggle state become unchecked and the unchecked image is shown every where
so to solve this i have saved the value of toggle button in shared preferences but now i dont know where to check this in base adapter class plz help me
the necessary code for this
public class DDListAdapter extends BaseAdapter {
ArrayList<DataModelDD> listArray;
int curIndex=1000, pIndex;
public DDListAdapter(String[] str, String[] str1) {
listArray = new ArrayList<DataModelDD>();
for (int i=0; i < str.length; i++) {
listArray.add(new DataModelDD(str[i],str1[i], " Day Alert on " + str[i],false));
}
}
public void DDListUpdate(String[] str, String[] str1){
listArray = new ArrayList<DataModelDD>();
for (int i=0; i < str.length; i++) {
listArray.add(new DataModelDD(str[i],str1[i], " Day Alert on " + str[i],false));
}
this.notifyDataSetChanged();
}
#Override
public int getCount() {
return listArray.size(); // total number of elements in the list
}
#Override
public Object getItem(int i) {
return listArray.get(i); // single item in the list
}
#Override
public long getItemId(int i) {
return i; // index number
}
#Override
public View getView(final int index, View view, final ViewGroup parent) {
lIndex = index;
pIndex = index;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
view = inflater.inflate(R.layout.lstdd, parent, false);
final DataModelDD dmFl = listArray.get(index);
final TextView lbl1 = (TextView) view.findViewById(R.id.txtDDate);
final TextView lbl2 = (TextView) view.findViewById(R.id.txtDres);
lbl1.setText(dmFl.getDDate());
lbl2.setText(dmFl.getDres());
final ToggleButton btnlock = (ToggleButton) view.findViewById(R.id.btnDAlarm);
if (dmFl.getdSel()) {
//selected
btnlock.setButtonDrawable(a_icon);
} else {
//not selected
btnlock.setButtonDrawable(a_dicon);
}
btnlock.setTag(pIndex);
btnlock.setOnCheckedChangeListener(new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(btnlock.isChecked()){
btnlock.setButtonDrawable(a_icon);
btnlock.setChecked(true);
dmFl.setdSel(true);
Integer position = (Integer) buttonView.getTag();
sp = context.getSharedPreferences("MyPref", 0);
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean("value"+month+"_"+state+"_"+cday, true);
editor.commit();
}
else{
final String alarmTime = dmFl.getDDate();
disableAlarm(buttonView,alarmTime);
btnlock.setButtonDrawable(a_dicon);
btnlock.setChecked(false);
dmFl.setdSel(false);
Integer position = (Integer) buttonView.getTag();
}
}
});
return view;
}
}
and the data model class
package com.example.dd;
public class DataModelDD {
private String DDate;
private String Dres;
private String ShrStr;
private Boolean dSel;
public DataModelDD(String DDate, String Dres, String ShrStr, Boolean dSel){
this.DDate = DDate;
this.Dres = Dres;
this.ShrStr = ShrStr;
this.dSel = dSel;
}
public String getDDate(){
return this.DDate;
}
public void setDDate(String DDate){
this.DDate = DDate;
}
public String getDres(){
return this.Dres;
}
public void setDres(String Dres){
this.Dres = Dres;
}
public String getShrStr(){
return this.ShrStr;
}
public void setShrStr(String ShrStr){
this.ShrStr = ShrStr;
}
public Boolean getdSel(){
return this.dSel;
}
public void setdSel(Boolean dSel){
this.dSel = dSel;
}
}
you need to do
is
SharedPreferences prefs = getSharedPreferences(settingsTAG, 0);
boolean rb0 = prefs.getBoolean("rb0", true);
if (dmFl.getdSel()||rb0) {
//selected
btnlock.setButtonDrawable(a_icon);
} else {
//not selected
btnlock.setButtonDrawable(a_dicon);
}
I have an activity with a custom ListView. I have two TextViews in each row, one of them contains static text and the other contains numbers which are randomly changed on a Button press. I need to save the data of both TextViews in two seperate ArrayLists (if the value of the number TextView is not 0). The values are being stored inside the ArrayLists as I wish, however the records are being inserted twice; such that when I loop through the ArrayList and show them in a Toast I get twice the value of the rows entered.
Below are my code snippets:
On Button click adding value of Number TextView
holder.add.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
int temp = numPickerValues.get(position);
temp += 1;
numPickerValues.set(position, temp);
notifyDataSetChanged();
}
});
holder.num.setText(String.valueOf(numPickerValues.get(position)));
Adding values of non-0 TextViews to ArrayList
if(!holder.num.getText().equals("0"))
{
materialNames.add(holder.txt.getText().toString());
materialAmounts.add(holder.num.getText().toString());
}
This is the fun part.
I debugged the application to check where the problem lies and I found out it is looping inside the ListView twice and thus storing the values twice inside the ArrayLists, however I do not have the values duplicated in my ListView. The duplicated value of one TextView is being shown after another, so it is not exactly looping twice, otherwise the values would be separated by others.
Any idea of what is going on?
Displaying values
public String getTest()
{
test= "";
for(String i : materialNames)
{
test = test + " " + i;
}
return test;
}
Then I call the above method from another activity on Button Click
btnConfirm.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast tt = Toast.makeText(getApplicationContext(), adapter.getTest(), Toast.LENGTH_LONG);
tt.show();
}
});
Custom Adapter class
public class MaterialListViewAdapter extends BaseAdapter
{
ViewHolder holder;
int counter = 0;
String test = null;
TextView txtNum;
private ArrayList<MaterialClass> data;
private ArrayList<Integer> numPickerValues;
private ArrayList<String> materialNames;
private ArrayList<String> materialAmounts;
public static LayoutInflater inflater = null;
public static Dialog dialog;
String materialName;
public MaterialListViewAdapter(Context applicationContext,
int materialdialogcontent, ArrayList<MaterialClass> materials)
{
this.data = materials;
this.numPickerValues = new ArrayList<Integer>();
this.materialNames = new ArrayList<String>();
this.materialAmounts = new ArrayList<String>();
int size = Material.materialList.size();
for(int i=0; i < size; i++)
{
this.numPickerValues.add(0);
}
inflater = (LayoutInflater)applicationContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount()
{
return data.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)
{
if(convertView == null)
{
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.materialdialogcontent, null);
holder.txt = (TextView)convertView.findViewById(R.id.txtMaterialName);
holder.add = (Button)convertView.findViewById(R.id.btnAdd);
holder.sub = (Button)convertView.findViewById(R.id.btnSub);
holder.num = (TextView)convertView.findViewById(R.id.txtNum);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder)convertView.getTag();
}
holder.txt.setText(data.get(position).getName());
holder.add.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
int temp = numPickerValues.get(position);
temp += 1;
numPickerValues.set(position, temp);
notifyDataSetChanged();
}
});
holder.sub.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
int temp = numPickerValues.get(position);
temp -= 1;
numPickerValues.set(position, temp);
notifyDataSetChanged();
}
});
holder.num.setText(String.valueOf(numPickerValues.get(position)));
if(!holder.num.getText().equals("0"))
{
materialNames.add(holder.txt.getText().toString());
materialAmounts.add(holder.num.getText().toString());
}
return convertView;
}
public String getTest()
{
test= "";
for(String i : materialNames)
{
test = test + " " + i;
}
return test;
}
private static class ViewHolder
{
TextView txt;
Button add;
Button sub;
TextView num;
}
}
if(!holder.num.getText().equals("0"))
{
materialNames.add(holder.txt.getText().toString());
materialAmounts.add(holder.num.getText().toString());
}
Above code in getView may be run many times. So, you can use HashMap instead of your materialNames and materialAmounts to avoid duplication.
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