ListView Position on button click - android

I am android developer, I have a custom listview with a checkbox. This layput also contain a delete button. I want when I click on cheakbox all the item in a particular row is selected and on click of delete it is deleted.
The problem is when I click on delete button I get a list of +1 row value.
Initially I already define :
int position=0;
btmsgdelete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("request send for message delete");
for(Message msg:almsg) {
if(msg.isSelected()) {
CheckBox chk = (CheckBox)findViewById(R.id.checkBox1);
System.out.println("msg is selected");
msgid=almsg.get(position).getEmpid();
System.out.println(msgid);
empname=almsg.get(position).getEmpname();
System.out.println(empname);
msgheader=almsg.get(position).getHeader();
System.out.println(msgheader);
}
}

Try this sample code
public class MainActivity extends Activity {
private int textViewResourceId;
private ArrayList<CompareListData> searchResults;
private ListView lst;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
searchResults = GetSearchResults();
lst = (ListView) findViewById(R.id.list);
findViewById(R.id.delete).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < searchResults.size(); i++) {
if (searchResults.get(i).getSelected()) {
searchResults.remove(i);
}
}
lst.setAdapter(new Adapter(MainActivity.this, textViewResourceId,
searchResults));
}
});
System.out.println("size " + searchResults.size());
lst.setAdapter(new Adapter(MainActivity.this, textViewResourceId,
searchResults));
}
private ArrayList<CompareListData> GetSearchResults() {
ArrayList<CompareListData> results = new ArrayList<CompareListData>();
CompareListData sr1 = new CompareListData();
sr1.setName("John Smith");
results.add(sr1);
sr1 = new CompareListData();
sr1.setName("Jane Doe");
results.add(sr1);
sr1 = new CompareListData();
sr1.setName("Steve Young");
results.add(sr1);
sr1 = new CompareListData();
sr1.setName("Fred Jones");
results.add(sr1);
return results;
}
}
CompareListData.java
public class CompareListData {
String name;
boolean selected;
public String getName() {
return name;
}
public void setName(String Name) {
name = Name;
}
public boolean getSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
Adapter.java
public class Adapter extends BaseAdapter{
public static int count = 0;
public LayoutInflater inflater;
public static ArrayList<CompareListData> selectedId;
public ArrayList<CompareListData> listObjects;
Context contex;
public Adapter(Context context, int textViewResourceId,
ArrayList<CompareListData> objects) {
super();
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.listObjects = objects;
this.contex = context;
}
public static class ViewHolder
{
TextView txtViewLoanName;
CheckBox chkSelected;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View view = null;
if(convertView==null)
{
final ViewHolder holder = new ViewHolder();
view = inflater.inflate(R.layout.row_comparelist, null);
holder.txtViewLoanName= (TextView) view.findViewById(R.id.rowcomparelist_tv_loanname);
holder.chkSelected= (CheckBox) view.findViewById(R.id.rowcomparelist_chk_selected);
holder.chkSelected.setId(position);
holder.chkSelected.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
CompareListData element = (CompareListData) holder.chkSelected.getTag();
element.setSelected(buttonView.isChecked());
}
});
view.setTag(holder);
holder.chkSelected.setTag(listObjects.get(position));
}
else{
view = convertView;
((ViewHolder) view.getTag()).chkSelected.setTag(listObjects.get(position));
}
ViewHolder holder = (ViewHolder) view.getTag();
holder.txtViewLoanName.setText(listObjects.get(position).getName());
holder.chkSelected.setChecked(listObjects.get(position).getSelected());
return view;
}
public int getCount() {
return listObjects.size();
}
public Object getItem(int position) {
return listObjects.get(position);
}
public long getItemId(int position) {return position;
}
}

Related

How to get shared preference value from baseadaptor to activity

Selecting multiple items from custom list view and passing to another
list view. When I close the application, these selected items are getting clean.
I have used shared preference ,I could not able to get the data>
MainActivity
MainActivity.java
public class MainActivity extends Activity {
private Button bt_inst_app;
GridView gridView, gv_shortcut;
List<AppList> installedApps;
List<AppList> res = new ArrayList<AppList>();
private String appName, appPackageName;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
gv_shortcut = (GridView) findViewById(R.id.gv_shortcut);
bt_inst_app = (Button) findViewById(R.id.bt_inst_app);
bt_inst_app.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder quick_links_alert = new AlertDialog.Builder(MainActivity.this);
quick_links_alert.setTitle("Edit Quick Links");
LinearLayout quick_links_layout = new LinearLayout(MainActivity.this);
quick_links_layout.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams quick_links_layoutparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
quick_links_layoutparams.setMargins(20, 0, 30, 0);
gridView = new GridView(MainActivity.this);
installedApps = getInstalledApps();
final GridViewAdapter gridViewAdapter = new GridViewAdapter(MainActivity.this, installedApps);
gridView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
gridView.setAdapter(gridViewAdapter);
gridView.setNumColumns(5);
quick_links_alert.setView(gridView);
quick_links_alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
final List<AppList> mArrayProducts = gridViewAdapter.getCheckedItems();
final QuickLinksGridViewAdaptor selected_apps = new QuickLinksGridViewAdaptor(MainActivity.this, mArrayProducts);
gv_shortcut.setAdapter(selected_apps);
gv_shortcut.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String s = mArrayProducts.get(position).getPackageName();
Intent PackageManagerIntent = getPackageManager().getLaunchIntentForPackage(s);//Here some time getting NULL
startActivity(PackageManagerIntent);
}
});
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
quick_links_alert.show();
}
private List<AppList> getInstalledApps() {
List<PackageInfo> packs = getPackageManager().getInstalledPackages(0);
for (int i = 0; i < packs.size(); i++) {
PackageInfo p = packs.get(i);
//if ((isSystemPackage(p) == false)) {
if (((p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) != true) {
appName = p.applicationInfo.loadLabel(getPackageManager()).toString();
Drawable icon = p.applicationInfo.loadIcon(getPackageManager());
appPackageName = p.applicationInfo.packageName;
res.add(new AppList(icon, appName, appPackageName));
}
}
return res;
}
});
}
}
GridViewAdapter.java
public class GridViewAdapter<T> extends BaseAdapter {
Context mContext;
//private final int length = 9;*/
private LayoutInflater layoutInflater;
List<AppList> listStorage;
MainActivity homeactivity;
private int selectedIndex;
private int selectedColor = Color.parseColor("#1b1b1b");
SparseBooleanArray mSparseBooleanArray;
SharedPreferences settings;
public GridViewAdapter(Context context, List<AppList> customizedListView) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.mContext = context;
listStorage = customizedListView;
mSparseBooleanArray = new SparseBooleanArray();
}
public void setSelectedIndex(int ind) {
selectedIndex = ind;
notifyDataSetChanged();
}
public ArrayList<T> getCheckedItems() {
ArrayList<T> mTempArry = new ArrayList<T>();
for (int i = 0; i < listStorage.size(); i++) {
if (mSparseBooleanArray.get(i)) {
mTempArry.add((T) listStorage.get(i));
}
}
return mTempArry;
}
#Override
public int getCount() {
return listStorage.size();
}
public Object getItem(int position) {
return listStorage.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder listViewHolder;
if (convertView == null) {
listViewHolder = new ViewHolder();
LayoutInflater vi = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.add_apps_grid_item, parent, false);
listViewHolder.textInListView = (TextView) convertView.findViewById(R.id.item_name);
listViewHolder.imageInListView = (ImageView) convertView.findViewById(R.id.item_type);
listViewHolder.tvPkgName = (TextView) convertView.findViewById(R.id.tvPack);
listViewHolder.select_app = (CheckBox) convertView.findViewById(R.id.select_app);
convertView.setTag(listViewHolder);
} else {
listViewHolder = (ViewHolder) convertView.getTag();
}
listViewHolder.textInListView.setText(listStorage.get(position).getName());
listViewHolder.imageInListView.setImageDrawable(listStorage.get(position).getIcon());
listViewHolder.tvPkgName.setText(listStorage.get(position).getPackageName());
listViewHolder.select_app.setTag(position);
listViewHolder.select_app.setChecked(mSparseBooleanArray.get(position));
final AppList item = listStorage.get(position);
listViewHolder.textInListView.setText(item.getName());
SharedPreferences settings = mContext.getSharedPreferences("data", Context.MODE_PRIVATE);
boolean Checked = settings.getBoolean(item.getName(), false);
listViewHolder.select_app.setChecked(Checked);
listViewHolder.select_app.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Toast.makeText(mContext, "pkg name==" + listStorage.get(position).getPackageName(), Toast.LENGTH_LONG).show();
if (listViewHolder.select_app.isChecked() == true) {
SharedPreferences settings = mContext.getSharedPreferences("data", Context.MODE_PRIVATE);
// Toast.makeText(mContext, "You deselected " + Context.MODE_PRIVATE, Toast.LENGTH_SHORT).show();
mSparseBooleanArray.put((Integer) buttonView.getTag(), settings.edit().putBoolean(item.getName(), true).commit());
// Toast.makeText(mContext, "You selected " + item.getName(), Toast.LENGTH_SHORT).show();
} else {
SharedPreferences settings = mContext.getSharedPreferences("data", Context.MODE_PRIVATE);
mSparseBooleanArray.put((Integer) buttonView.getTag(), settings.edit().putBoolean(item.getName(), false).commit());
// Toast.makeText(mContext, "You deselected " + item.getName(), Toast.LENGTH_SHORT).show();
}
// Toast.makeText(mContext, "Shared prefernce---->" + mContext.toString(), Toast.LENGTH_SHORT).show();
}
});
return convertView;
}
OnCheckedChangeListener mCheckedChangeListener = new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
mSparseBooleanArray.put((Integer) buttonView.getTag(), isChecked);
}
};
static class ViewHolder {
TextView textInListView, tvPkgName;
ImageView imageInListView;
CheckBox select_app;
}
}
AppList.java
public class AppList implements Parcelable {
private String name;
private String packageName;
Drawable icon;
private boolean selected;
public AppList(Drawable icon, String name, String packageName) {
this.name = name;
this.icon = icon;
this.packageName = packageName;
}
protected AppList(Parcel in) {
name = in.readString();
packageName = in.readString();
selected = in.readByte() != 0;
}
public static final Creator<AppList> CREATOR = new Creator<AppList>() {
#Override
public AppList createFromParcel(Parcel in) {
return new AppList(in);
}
#Override
public AppList[] newArray(int size) {
return new AppList[size];
}
};
public String getName() {
return name;
}
public String getPackageName() {
return packageName;
}
public Drawable getIcon() {
return icon;
}
public String toString() {
return name;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(name);
parcel.writeString(packageName);
parcel.writeByte((byte) (selected ? 1 : 0));
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
QuickLinksGridViewAdaptor.java
public class QuickLinksGridViewAdaptor<T> extends BaseAdapter {
private Context context;
//private final int length = 9;*/
private LayoutInflater layoutInflater;
List<AppList> listStorage;
MainActivity homeactivity;
private int selectedIndex;
SparseBooleanArray mSparseBooleanArray;
int num = 1;
public QuickLinksGridViewAdaptor(Context context, List<AppList> customizedListView) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
listStorage = customizedListView;
mSparseBooleanArray = new SparseBooleanArray();
}
public void setSelectedIndex(int ind) {
selectedIndex = ind;
notifyDataSetChanged();
}
public ArrayList<T> getCheckedItems() {
ArrayList<T> mTempArry = new ArrayList<T>();
for (int i = 0; i < listStorage.size(); i++) {
if (mSparseBooleanArray.get(i)) {
mTempArry.add((T) listStorage.get(i));
}
}
return mTempArry;
}
#Override
public int getCount() {
//return 8;
if(num*8 >= listStorage.size()){
return listStorage.size();
}else{
return num*8;
}
}
public Object getItem(int position) {
return listStorage.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder listViewHolder;
if (convertView == null) {
listViewHolder = new ViewHolder();
convertView = layoutInflater.inflate(R.layout.add_apps_grid_item1, parent, false);
listViewHolder.textInListView = (TextView) convertView.findViewById(R.id.item_name1);
listViewHolder.imageInListView = (ImageView) convertView.findViewById(R.id.item_type1);
convertView.setTag(listViewHolder);
} else {
listViewHolder = (ViewHolder) convertView.getTag();
}
listViewHolder.textInListView.setText(listStorage.get(position).getName());
listViewHolder.imageInListView.setImageDrawable(listStorage.get(position).getIcon());
return convertView;
}
static class ViewHolder {
TextView textInListView;
ImageView imageInListView;
}
}
You can either use savedInstanceState method to save and retrieve data in an Activity or You can save the boolean check value every time you change the value of your selection(either selected or non selected state) into SharedPreferences using key as name/id of the value to be selected, and value as true or false.
You can easily check the shared preferences then, to check whether this value is present in shared preferences or not. And use Boolean value to show the selection.
Hope you get this answer.

Android - Spinner is not stable in custom ArrayAdapter

I have a custom array adapter with 2 textView, 1 spinner and 1 checkbox. When I run my app and select the item in the spinner and scroll the custom adapter the strings in spinner is not stable. It's changing its position in the customAdapter. The code for my getView(),
public class ListAdap extends ArrayAdapter<List> {
private static final String TAG = "ListAdap";
private final ArrayList<List> nameList;
public ListAdap(Context context, int resource, ArrayList<List> list) {
super(context, resource, list);
this.nameList = list;
}
public static class ViewHolder {
ArrayList excuseList;
TextView number;
Spinner excuse;
TextView name;
CheckBox isPaid;
ArrayAdapter adapter;
}
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
ViewHolder viewHolder = null;
final List currentNameList = getItem(position);
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.pending_list, parent, false);
viewHolder = new ViewHolder();
final ArrayList excuseList = new ArrayList();
excuseList.add("");
excuseList.add("Tommorow");
excuseList.add("Sunday");
excuseList.add("Monday");
excuseList.add("Tuesday");
excuseList.add("Wednesday");
excuseList.add("Thursday");
excuseList.add("Friday");
excuseList.add("Next Week");
viewHolder.excuse = (Spinner) listItemView.findViewById(R.id.excuseSpinner);
ArrayAdapter adapter = new ArrayAdapter(getContext(), android.R.layout.simple_list_item_1, excuseList);
viewHolder.excuse.setAdapter(adapter);
final ViewHolder finalViewHolder = viewHolder;
viewHolder.excuse.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
currentNameList.get(position).setPos(String.valueOf(pos));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
viewHolder.excuse.setSelection(Integer.parseInt(currentNameList.get(position).getPos()));
viewHolder.number = (TextView) listItemView.findViewById(R.id.number);
viewHolder.number.setText(currentNameList.getNumber());
viewHolder.name = (TextView) listItemView.findViewById(R.id.name);
viewHolder.name.setText(currentNameList.getName());
viewHolder.isPaid = (CheckBox) listItemView.findViewById(R.id.checkBox);
listItemView.setTag(viewHolder);
final ViewHolder finalViewHolder1 = viewHolder;
viewHolder.isPaid.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
List namelist = (List) cb.getTag();
if (String.valueOf(cb.isChecked()) == "true"){
Log.v("ConvertView", String.valueOf(cb.isChecked()) + finalViewHolder1.name.getText());
Toast.makeText(getContext(),finalViewHolder1.name.getText() +" Paid", Toast.LENGTH_SHORT).show();
cb.setChecked(true);
}
namelist.setSelected(cb.isChecked());
}
});
} else {
viewHolder = (ViewHolder) listItemView.getTag();
}
List list = nameList.get(position);
viewHolder.number.setText(currentNameList.number);
viewHolder.name.setText(currentNameList.name);
viewHolder.isPaid.setChecked(list.ispaid());
viewHolder.isPaid.setTag(list);
viewHolder.excuse.setTag(list);
return listItemView;
}
public class MultiSelectSpinner {
private String pos;
public String getPos()
{
return pos;
}
public void setPos(String pos)
{
this.pos = pos;
}
}
}
List.class
public class List{
String number;
String name;
Boolean paid = false;
public List(String number, String name, boolean paid) {
this.number = number;
this.name = name;
this.paid = paid;
}
public String getNumber() {
return number;
}
public String getName() {
return name;
}
public Boolean ispaid() {
return paid;
}
public void setSelected(boolean selected)
{
this.paid = selected;
}
}

Update a ListView using SharedPreference

I want to send multiple rows from the 1st list when the star button is pressed to the 2nd Activity list
My code works only for one single row . For example if I'm pressing the first star ,on my SecondActivity it will be only the first row but if I press the first and the last star ,only the last row it will be shown on the SecondActivity
1st list :http://i.stack.imgur.com/6lD8j.png
1st adapter:
public class AdapterExploreListView extends BaseAdapter implements Filterable {
ArrayList<Track> tracks;
Context context;
private ArrayList<Track> items;
private ArrayList<Track> orig;
public static final String Title = "titleKey";
public static final String Username = "usernameKey";
public AdapterExploreListView(Context context, ArrayList<Track> tracks) {
this.tracks = new ArrayList<>();
this.tracks = tracks;
this.context = context;
getFilter();
}
#Override
public int getCount() {
return tracks.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View rowView = view;
// reuse views
if (rowView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
rowView = inflater.inflate(R.layout.row_list_explore, null);
// configure view holder
ViewHolder viewHolder = new ViewHolder();
viewHolder.title = (TextView) rowView.findViewById(R.id.titleTextView);
viewHolder.userName = (TextView) rowView.findViewById(R.id.userNameTextView);
viewHolder.listImageView = (ImageView) rowView.findViewById(R.id.favbutton);
rowView.setTag(viewHolder);
}
// fill data
final ViewHolder holder = (ViewHolder) rowView.getTag();
Track track = tracks.get(i);
holder.title.setText(track.getTitle());
holder.userName.setText(track.getUsername());
holder.listImageView.setImageResource(R.drawable.favoritespic);
holder.listImageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context,ForthActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
SharedPreferences sp = context.getSharedPreferences("Save",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
String n = holder.title.getText().toString();
String e = holder.userName.getText().toString();
editor.putString(Title, n);
editor.putString(Username, e);
editor.commit();
}
});
// if(!track.getArtworkUrl().equalsIgnoreCase("null"))
// {
// ImageLoader.getInstance().displayImage(track.getArtworkUrl(), holder.listImageView);
// } else {
// ImageLoader.getInstance().displayImage(track.getAvatarUrl(), holder.listImageView);
// }
return rowView;
}
static class ViewHolder {
TextView title;
TextView userName;
ImageView listImageView;
}
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
final FilterResults oReturn = new FilterResults();
final ArrayList<Track> results = new ArrayList<Track>();
if (orig == null) orig = items;
if (constraint != null) {
if (orig != null && orig.size() > 0) {
for (final Track g : orig) {
if (g.getTitle().toLowerCase().contains(constraint.toString()))
results.add(g);
}
}
oReturn.values = results;
}
return oReturn;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
items = (ArrayList<Track>) results.values;
notifyDataSetChanged();
}
};
}
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
boolean notifyDataSetChanged = true;
}
}
2nd adapter:
public class AdapterExploreListView2 extends BaseAdapter {
private ArrayList<CustomObject> objects;
Context context;
public static final String Title = "titleKey";
public static final String Username = "usernameKey";
public AdapterExploreListView2(Context context, ArrayList<CustomObject> objects) {
this.objects = new ArrayList<>();
this.objects = objects;
this.context = context;
}
#Override
public int getCount() {
return objects.size();
}
public CustomObject getItem(int position) {
return objects.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
View rowView = view;
// reuse views
if (rowView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
rowView = inflater.inflate(R.layout.row_list_forthact, null);
// configure view holder
ViewHolder viewHolder = new ViewHolder();
viewHolder.title = (TextView) rowView.findViewById(R.id.titleTV);
viewHolder.userName = (TextView) rowView.findViewById(R.id.userNameTV);
// viewHolder.listImageView = (ImageView) rowView.findViewById(R.id.listImageView);
rowView.setTag(viewHolder);
}
// fill data
ViewHolder holder = (ViewHolder) rowView.getTag();
holder.title.setText(objects.get(position).getProp1());
holder.userName.setText(objects.get(position).getProp2());
return rowView;
}
static class ViewHolder {
TextView title;
TextView userName;
// ImageView listImageView;
}
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
boolean notifyDataSetChanged = true;
}
}
2nd activity:
public class ForthActivity extends Activity {
SharedPreferences sharedpreferences;
public static final String Title = "titleKey";
public static final String Username = "usernameKey";
CustomObject obj;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.forthact);
// title = (TextView) findViewById(R.id.etitle);
// username = (TextView) findViewById(R.id.eemail);
sharedpreferences = getSharedPreferences("Save",
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Title)) {
obj.setProp1(sharedpreferences.getString(Title, ""));
}
if (sharedpreferences.contains(Username)) {
obj.setProp2(sharedpreferences.getString(Username, ""));
}
ArrayList<CustomObject> object = new ArrayList<CustomObject>();
AdapterExploreListView2 customAdapter = new AdapterExploreListView2(ForthActivity.this, object);
ListView lv = (ListView) findViewById(R.id.forthlistview);
lv.setAdapter(customAdapter);
}
}
CustomObject class:
public class CustomObject {
private String prop1;
private String prop2;
public CustomObject(String prop1, String prop2) {
this.prop1 = prop1;
this.prop2 = prop2;
}
public void setProp1(String prop1) {
this.prop1 = prop1;
}
public void setProp2(String prop2) {
this.prop2 = prop2;
}
public String getProp1() {
return prop1;
}
public String getProp2() {
return prop2;
}
}

implementation of Checkbox in Custom ListActivity

In the following code
here is my main Activity Where i choose various product and proceed further
but when I checked multiple or one it pass 0 value;
that is in Toast I am not getting anything as below in image
public class MainActivity extends ListActivity {
ListView list;
Button btn1;
String url="";
private ArrayList <Product> allProducts = new ArrayList<Product>();
private ProductAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
btn1 = (Button) findViewById(R.id.btn);
list = getListView();
url="http://192.168.1.100/test/product.txt?id=";//+d.getInt("id");
try{
ConnectivityManager c =(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo n =c.getActiveNetworkInfo();
if (n!= null && n.isConnected()){
Log.d("url*********",url);
new Background().execute(url);
}
}catch(Exception e){}
adapter = new ProductAdapter(this,allProducts);
setListAdapter(adapter);
getListView().setItemsCanFocus(false);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringBuffer responseText = new StringBuffer();
responseText.append("The following were selected...\n");
for(int i=0;i<allProducts.size();i++){
Product product = allProducts.get(i);
if(product.isChecked()){
responseText.append("\n" + product.getProduct_name());
}
}
Toast.makeText(getApplicationContext(),
responseText, Toast.LENGTH_LONG).show();
}
});
}
Here is ProductAdapter
public class ProductAdapter extends ArrayAdapter<Product> {
ArrayList<Product> allProducts;
LayoutInflater vi;
int Resource;
Context context;
public ProductAdapter (Context context ,ArrayList<Product> objects)
{
super(context, R.layout.productrow, objects);
allProducts = objects;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
convertView = inflater.inflate(R.layout.productrow, parent, false);
TextView name = (TextView) convertView.findViewById(R.id.price);
CheckBox cb = (CheckBox) convertView.findViewById(R.id.cb1);
int s = allProducts.get(position).getProduct_price();
name.setText(Integer.toString(s));
cb.setText(allProducts.get(position).getProduct_name());
if(allProducts.get(position).isChecked())
cb.setChecked(true);
else
cb.setChecked(false);
return convertView;
}
}
My Product.java file which is my model
public class Product {
int product_id;
private boolean checked = false ;
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
String product_name;
int product_price;
int product_qunatity;
int hotel_id;
public int getProduct_id() {
return product_id;
}
public void setProduct_id(int product_id) {
this.product_id = product_id;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public int getProduct_price() {
return product_price;
}
public void setProduct_price(int product_price) {
this.product_price = product_price;
}
public int getProduct_qunatity() {
return product_qunatity;
}
public void setProduct_qunatity(int product_qunatity) {
this.product_qunatity = product_qunatity;
}
public int getHotel_id() {
return hotel_id;
}
public void setHotel_id(int hotel_id) {
this.hotel_id = hotel_id;
}
}
Img Of screen Shot
Ok, there is declaration of checkbox CheckBox cb = (CheckBox) convertView.findViewById(R.id.cb1); but where is the listener?
I assume you need to add listener:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//your code goes here
cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.i(TAG, "Entered onCheckedChanged()");
//other stuff for listener
}
});
}

listview with edittext ,checkbox and textView in android

i have created a listview with checkbox,edittext and textview.
data is populated in listview with sql server. but i am not being able to use onCheckedChangedListener on checkbox. so that on clicking the checkbox corresponding data of textview and edittext is not being saved..
i know i am doing mistake somewhere in my adapter class..
How to save data and what logic should i use in onCheckedChangedListener in my adapter class?
code for pojo class
public class Model {
public String name="";
public boolean selected=false;
public String score="";
public Model(String name) {
this.name = name;
selected = false;
score="";
}
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 String getScore() {
return score;
}
public void setScore(String score) {
this.score = score;
}
}
code for Adapter class
public class MyAdapter extends ArrayAdapter<Model> {
private final List<Model> list;
private final Activity context;
public MyAdapter(Activity context, List<Model> list)
{
super(context, R.layout.row, list);
this.context = context;
this.list = list;
}
static class ViewHolder
{
protected TextView text;
protected CheckBox checkbox;
protected EditText scores;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View view = null;
if (convertView == null)
{
LayoutInflater inflator = context.getLayoutInflater();
view = inflator.inflate(R.layout.row, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.text = (TextView) view.findViewById(R.id.label);
viewHolder.scores=(EditText) view.findViewById(R.id.txtAddress);
viewHolder.scores.addTextChangedListener(new TextWatcher()
{
public void onTextChanged(CharSequence s, int start, int before, int count) {
Model element=(Model)viewHolder.scores.getTag();
element.setScore(s.toString());
}
public void beforeTextChanged(CharSequence s, int start, int count,int after)
{
}
public void afterTextChanged(Editable s)
{
}
});
viewHolder.checkbox = (CheckBox) view.findViewById(R.id.check);
viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
Model element = (Model) viewHolder.checkbox.getTag();
element.setSelected(buttonView.isChecked());
}
});
viewHolder.checkbox.setTag(list.get(position));
viewHolder.scores.setTag(list.get(position));
view.setTag(viewHolder);
}
else
{
view = convertView;
((ViewHolder) view.getTag()).checkbox.setTag(list.get(position));
((ViewHolder) view.getTag()).scores.setTag(list.get(position));
}
ViewHolder holder = (ViewHolder) view.getTag();
holder.text.setText(list.get(position).getName());
holder.scores.setText(list.get(position).getScore());
holder.checkbox.setChecked(list.get(position).isSelected());
return view;
}
}
code for MainActivity class
public class MainActivity extends Activity {
ListView listView;
Button btnSave;
Connection connect;
ArrayAdapter<Model> adapter;
MyConnection mycon;
List<Model> list = new ArrayList<Model>();
List<String>data=new ArrayList<String>();
List<String>data2=new ArrayList<String>();
StringBuilder sb;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
mycon=new MyConnection(getApplicationContext());
listView = (ListView) findViewById(R.id.my_list);
btnSave = (Button)findViewById(R.id.btnSave);
sb=new StringBuilder();
adapter = new MyAdapter(this,getModel());
listView.setAdapter(adapter);
if(list.isEmpty()){
Toast.makeText(getApplicationContext(), "kuldeep", Toast.LENGTH_LONG).show();
}
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < list.size(); i++) {
Toast.makeText(getBaseContext(), "Name : "+list.get(i).getName() +" Selected: "+list.get(i).isSelected()+"address: "+list.get(i).getScore().toString(), Toast.LENGTH_SHORT).show();
}
}
});
}
private List<Model> getModel() {
list.clear();
try{
Statement smt=mycon.connection().createStatement();
ResultSet rs=smt.executeQuery("WORKINGTYPE");
while(rs.next()){
list.add(new Model(rs.getString("FIELD_NAME")));
}
}catch(Exception e){
e.printStackTrace();
}
/* list.add(new Model("kuldeep"));
list.add(new Model("sandeep"));
list.add(new Model("ravi"));
list.add(new Model("pradeep"));
list.add(new Model("praveena"));
list.add(new Model("ruchi"));
list.add(new Model("vikas"));
list.add(new Model("sonu"));
list.add(new Model("ashu"));
*/
return list;
}
}
for saving data of textview and EditText what logic should i use and where in Adapter clss i should write it..
May not be a solution, but a suggestion.
Prefer not to declare your Listeners inside an 'if' condition. What I meant is,
IF convertview == null
find views
ELSE
getTag()
Rest of the codes
Is it that your checkbox event is not firing?
I use setOnClickListener for my Checkbox events:
CheckBox checkbox = (CheckBox)view.findViewById(R.id.item_checkbox);
checkbox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Mark model as selected/not selected
if (model.isSelected())
model.markAsNotSelected();
else
model.markAsSelected();
}
});
I know it's an old question, but if anyone else is facing same problem, replace the Adapter class with the following code.
public class MyAdapter extends ArrayAdapter<Model> implements TextWatcher{
private final List<Model> list;
private final Context context;
public MyAdapter(Context context, List<Model> list)
{
super(context, R.layout.row, list);
this.context = context;
this.list = list;
}
static class ViewHolder
{
protected TextView text;
protected CheckBox checkbox;
protected EditText scores;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
ViewHolder viewHolder = null;
if (convertView == null){
LayoutInflater inflator = LayoutInflater.from(context);
convertView = inflator.inflate(R.layout.row, null);
viewHolder = new ViewHolder();
viewHolder.text = (TextView) view.findViewById(R.id.label);
viewHolder.scores=(EditText) view.findViewById(R.id.txtAddress);
viewHolder.checkbox = (CheckBox) view.findViewById(R.id.check);
viewHolder.checkbox.setTag(list.get(position));
viewHolder.scores.setTag(list.get(position));
convertView.setTag(viewHolder);
}
else
{
convertView = (ViewHolder) convertView.getTag();
}
viewHolder.scores.addTextChangedListener(this)
viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
Model element = (Model) viewHolder.checkbox.getTag();
element.setSelected(buttonView.isChecked());
}
});
ViewHolder holder = (ViewHolder) view.getTag();
holder.text.setText(list.get(position).getName());
holder.scores.setText(list.get(position).getScore());
holder.checkbox.setChecked(list.get(position).isSelected());
return view;
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Model element=(Model)viewHolder.scores.getTag();
element.setScore(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,int after)
{
}
#Override
public void afterTextChanged(Editable s)
{
}
});
}

Categories

Resources