How to get the check box selected position - android

How to get the selected position in checkbox itemId.
I have two item Veg and non-veg item. I want the result for veg Items only. I show the screen in veg items .But it is not working for veg list checked items.
Response
|1|Amaretto cookies|True
is itemId
food item
True/False.
Based on True or False I need to check the check boxes and retrieve the checked items
Veg items:
|21|1|Amaretto cookies|True|2|Amish White Bread|True|6|Caesar Salad|True|10|Guacamole|True|13|Macaroni and Cheese|True|16|Pancakes|True|17|Pasta|True|18|Ribollita|True|20|Pizza|True|21|Seven Layer Taco Dip|True|22|Shrimp Bisque|True|23|Spicy Bean Salsa|True|24|Sopapilla Cheesecake|True|25|Sopapilla Cheesecake Pie|True|26|Vegetarian Tortilla Stew|True|561|food|True|563|asdf|True|574|veg|True|579|a|True|593|hjg|True|619|hhy|True|
Non- Veg items:
|12|3|Barbeque|False|4|Buffalo Chicken Wings|False|5|Burgers|False|7|Classic Lasagna|False|8|Chicken Chow Mein|False|9|Fried Chicken|False|11|Japanese sushi|False|12|Mezze|False|14|Mutton Pepper Gravy|False|15|Paella Valenciana|False|19|Phad Thai Recipe|False|578|Pizza|False|
Url:
String user_url="http://mobileapps.iwedplanner.com/mobileapps/iwedplanner/mobile/version21/mmealitems.aspx?uname="+LoginForm.str1+"&occasion="+occasionval;
Code:
httpclass obj = new httpclass();
result = obj.server_conn(user_url);
System.out.println(result);
if (result != null)
{
token = new StringTokenizer2(result, "");
}
value = new ArrayList<String>();
while (token.hasMoreTokens())
{
value.add(token.nextToken());
}
value.add(Integer.toString(value.size()));
Integer k=null;
table=new Hashtable<Integer,ArrayList<String>>();
itemId = new ArrayList<String>();
stritem = new ArrayList<String>();
vegitems = new ArrayList<String>();
nonvegitems = new ArrayList<String>();
int id=0,c=0,n=value.size();
for(int j=0; j<n; j++)
{
z = value.get(j);
String[] mystring = z.split("<br>");
int arraysize = mystring.length;
for(int a=0; a<arraysize-1;a++)
{
str2.add(mystring[0]);
str3.add(mystring[1]);
}
}
for(int g=0; g<str2.size();g++)
{
String name = str2.get(g);
token2 = new StringTokenizer2(name, "|", false);
while (token2.hasMoreTokens())
{
vegitems.add(token2.nextToken());
}
}
for(int x=1;x<vegitems.size();x++)
{
itemId.add(vegitems.get(x));
x=x+1;
stritem.add(vegitems.get(x));
x=x+1;
status.add(vegitems.get(x));
}
setListAdapter(new IconicAdapter(this));
selection = (TextView) findViewById(R.id.selection);
getListView().setTextFilterEnabled(true);
save.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
tru = new StringBuffer();
fals = new StringBuffer();
for (int i = 0; i<status.size();i++)
{
if (status.get(i).equals("True"))
tru.append(itemId.get(i)+",");
else
fals.append(itemId.get(i)+",");
}
boolean netvalue = false;
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null && info.isAvailable()) {
String user_url="http://mobileapps.iwedplanner.com/mobileapps/iwedplanner/mobile/version21/minsertmealchoiceNew.aspx?uname="+username+"&occasion="+occasionval+
"&choice="+tru+fals+"&ownchoice=&category=";
httpclass obj = new httpclass();
result = obj.server_conn(user_url);
StringTokenizer st = new StringTokenizer(result, "|");
result = st.nextToken();
if ((result.equals("Engagement 1&")) || (result.equals("Wedding 1&")) || (result.equals("Reception 1&")))
{
#SuppressWarnings("rawtypes")
class IconicAdapter extends ArrayAdapter
{
Activity context;
#SuppressWarnings("unchecked")
IconicAdapter(Activity context)
{
super(context, R.layout.rsvp_mealsse, stritem);
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = context.getLayoutInflater();
View row = inflater.inflate(R.layout.rsvp_mealsse,null);//viewappointlist, null);
TextView index = (TextView) row.findViewById(R.id.index);
index.setText(String.valueOf(position+1)+".");
TextView label = (TextView) row.findViewById(R.id.title);
label.setText(stritem.get(position));
CheckBox check=(CheckBox)row.findViewById(R.id.check);
check.setId(Integer.parseInt(itemId.get(position)));
if(status.get(position).equals("True"))
check.setChecked(true);
else
check.setChecked(false);
check.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
int ind=itemId.indexOf(String.valueOf(buttonView.getId()));
status.set(ind, String.valueOf(isChecked));
}
});
return (row);
}
}
Snap :
This is what it should look like.False items are checked in the snap
Above shows the full code of my project.
These are my requirements:
It is all about event planner for Food. The invited guests can select and save the interested food items such as pizza, Caesar salad, Ameretocokies etc from the items list and mail to the inviter so that the inviter can view the saved items and arrange for the selected items.

I picked the solution from Romain Guy's solution #
https://groups.google.com/forum/?fromgroups#!topic/android-developers/No0LrgJ6q2M
I have used a ViewHolder pattern for smooth scrolling and performance. I have used a SparseBooleanArray to get checked items.
I assume you want the items whose corresponding check boxes are checked.
Also check this to understand listview re-cycles views
How ListView's recycling mechanism works
public class dsds extends Activity
{
ListView lv;
String result = null;
StringTokenizer2 token = null,token2=null;;
ArrayList<String> value,value2 = null;
ArrayList<String> str = null;
ArrayList<String> str2 = null;
ArrayList<String> newstatus=null;
Hashtable<Integer, String> checkstatus=null;
ArrayList<String>stateId=null;
StringBuffer tru,fals;
private SparseBooleanArray mCheckStates;
String z;
ArrayList<Holder> ha = new ArrayList<Holder>();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.text);
str2 = new ArrayList<String>();
stateId = new ArrayList<String>();
newstatus=new ArrayList<String>();
lv = (ListView) findViewById(R.id.listView1);
Button b= (Button) findViewById(R.id.button1);
new TheTask().execute();
b.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
StringBuilder result = new StringBuilder();
for(int i=0;i<str2.size();i++)
{
if(mCheckStates.get(i)==true)
{
result.append(str2.get(i));
result.append("\n");
}
}
Toast.makeText(dsds.this, result, 1000).show();
}
});
}
class TheTask extends AsyncTask<Void,Void,Void>
{
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet request = new HttpGet("http://mobileapps.iwedplanner.com/mobileapps/iwedplanner/mobile/version21/mmealitems.aspx?uname=abcdefg&occasion=Engagement");
try
{
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
String _response=EntityUtils.toString(resEntity);
if (_response != null)
{
//alertbox("",result);
String[] mystring = _response.split("<br>"); // splt by break
token = new StringTokenizer2(mystring[0], "|", false);// split by |
token2 = new StringTokenizer2(mystring[1], "|", false);
}
/////// for veg
value = new ArrayList<String>();
while (token.hasMoreTokens())
{
value.add(token.nextToken());
}
for(int i=1;i<value.size()-1;i=i+3)
{
// Log.i("....Veg ids.......",""+value.get(i));
stateId.add(value.get(i));
}
for(int i=2;i<value.size()-1;i=i+3)
{
str2.add(value.get(i));
// Log.i("....Veg ids.......",""+value.get(i));
}
for(int i=3;i<=value.size()-1;i=i+3)
{
newstatus.add(value.get(i));
// Log.i("....Veg ids.......",""+value.get(i));
}
// add all to list of Holder
for(int h=0;h<str2.size();h++)
{
Holder holder = new Holder();
holder.setTitle(str2.get(h));
holder.setId(stateId.get(h));
if(newstatus.get(h).equals("False"))
{
holder.setCheck(true);
}
else
{
holder.setCheck(false);
}
ha.add(holder);
}
}catch(Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
lv.setAdapter(new IconicAdapter(dsds.this));
}
}
#SuppressWarnings("rawtypes")
class IconicAdapter extends ArrayAdapter implements CompoundButton.OnCheckedChangeListener
{
Activity context;
LayoutInflater mInflater;
#SuppressWarnings("unchecked")
IconicAdapter(Activity context)
{
super(context, R.layout.list_item, str2);
mCheckStates = new SparseBooleanArray(str2.size());
mInflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
if(convertView==null)
{
convertView=mInflater.inflate(R.layout.list_item,parent,false);
holder = new ViewHolder();
holder.tv1 = (TextView) convertView.findViewById(R.id.textView1);
holder.tv2 = (TextView) convertView.findViewById(R.id.textView2);
holder.cb = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
Holder hol = ha.get(position);
holder.tv1.setText(hol.getId().toString());
holder.tv2.setText(hol.getTitle().toString());
if(hol.isCheck()==true)
{
holder.cb.setChecked(mCheckStates.get(position, true));
holder.cb.setTag(position);
}
else
{
holder.cb.setChecked(mCheckStates.get(position, false));
holder.cb.setTag(position);
}
holder.cb.setOnCheckedChangeListener(this);
return convertView;
}
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);
}
}
static class ViewHolder
{
TextView tv1,tv2;
CheckBox cb;
}
}
Holder class
public class Holder {
String title;
String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
boolean check;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public boolean isCheck() {
return check;
}
public void setCheck(boolean check) {
this.check = check;
}
}
text.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Button" />
<ListView
android:id="#+id/listView1"
android:layout_above="#id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" >
</ListView>
</RelativeLayout>
list_tiem.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="33dp"
android:layout_marginTop="40dp"
android:text="TextView" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView1"
android:layout_centerHorizontal="true"
android:text="TextView" />
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView2"
android:layout_alignBottom="#+id/textView2"
android:layout_alignParentRight="true"
android:text="CheckBox" />
</RelativeLayout>
Snap
Now 1 and 2 are checked and when you click the button at the bottom you see the selected text. I checked 1 and 2 manually. However it depends on the response ie True or False. Right now all veg items are true.
Note: The list displays only veg items

If you are using list-view and you want to check list-view item then you can use below code.
int len = mListView.getCount();
SparseBooleanArray checked = mListView.getCheckedItemPositions();
for (int i = 0; i < len; i++)
if (checked.get(i)){
..... // Your code whatever you want to do with selected item..
}
else{
....
}

Related

How do i add spinner inside listview row in android?

I am developing an app in this i have populate listview with json parser. Now i have to add local spinner array inside this listview single row.
How do i add locally spinner array inside this listview row. And also i want to get selected spinner values of listview. Following is my code please suggest me.
//activity
public class MyModifyPgmLvAddUserActivity1 extends AppCompatActivity {
private DBManager dbManager;
private ListView listView, listView1;
Toolbar toolbar;
private String TAG = MyModifyPgmLvAddUserAdapter.class.getSimpleName();
private ProgressDialog pDialog;
// private SimpleCursorAdapter adapter;
MyModifyPgmLvAddUserAdapter1 adapter;
static String RANK = "AsanaId";
static String COUNTRY = "Asananame";
static String POPULATION = "repetation";
ArrayList<PojoList> SubjectList = new ArrayList<PojoList>();
final static String[] mSpinnerItems = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
private static String url = "http://www.test.com/ypAndroid/api/getDefaultProgramlist";
String asananame, asanaid,duration, imageurl, imageversion, audiourl, audioversion, videourl, videoversion;
String sid;
boolean selected;
String id;
String[] subject = null;
String[] spinner = null;
String title;
long id1;
Button btnCreate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_modifypgm_lv_add_user);
btnCreate = (Button) findViewById(R.id.button_submit);
dbManager = new DBManager(this);
dbManager.open();
Intent i = getIntent();
id= i.getStringExtra("id");
subject = i.getStringArrayExtra("subject");
spinner = i.getStringArrayExtra("spinner");
title= i.getStringExtra("title");
id1= Long.parseLong(id);
SubjectList = new ArrayList<>();
listView = (ListView) findViewById(R.id.listview);
//Net Connection
ConnectivityManager conMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
if (netInfo == null){
AlertDialog.Builder alert = new AlertDialog.Builder(MyModifyPgmLvAddUserActivity1.this);
// new AlertDialog.Builder(MyModifyProgramEditDeleteActivity.this)
alert.setTitle(getResources().getString(R.string.app_name));
alert.setMessage(getResources().getString(R.string.no_internet));
alert.setPositiveButton("OK", null).show();
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//Do something here where "ok" clicked and then perform intent from activity context
Intent intent = new Intent(MyModifyPgmLvAddUserActivity1.this, MyYogaPosesSubMenuActivity.class);
MyModifyPgmLvAddUserActivity1.this.startActivity(intent);
}
});
alert.show();
}
else {
new MyModifyPgmLvAddUserActivity1.DownloadJSON().execute();
}
btnCreate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkButtonClick();
Intent modify_intent = new Intent(MyModifyPgmLvAddUserActivity1.this, MyModifySavedProgramActivity1.class);
modify_intent.putExtra("subject", spinner);
modify_intent.putExtra("spinner", subject);
modify_intent.putExtra("id", id);
modify_intent.putExtra("title", title);
startActivity(modify_intent);
}
});
}
private void checkButtonClick() {
ArrayList<String> list1= new ArrayList<>();
ArrayList<String> list2= new ArrayList<>();
// ArrayList<String> list3= new ArrayList<>();
PojoList pojo = null;
ArrayList<PojoList> countryList = adapter.SubjectListTemp;
for (int i = 0; i < countryList.size(); i++) {
pojo = countryList.get(i);
if (pojo.isSelected()) {
// responseText.append("\n" + country.getName());
list1.add(pojo.getAsanName());
// list2.add(convertArrayToString(subject));
list2.add(pojo.getAsanId());
// list2.add(convertArrayToString(spinner));
}
}
String [] aIds = list1.toArray(new String[list1.size()]);
String [] aNames = list2.toArray(new String[list2.size()]);
dbManager.update(id1, aIds, aNames);
// dbManager.insert(title, names, spinner);
// dbManager.set_datetime_next(id, names, spinner);
}
public static String[] convertStringToArray(String str){
String[] arr = str.split(strSeparator);
return arr;
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MyModifyPgmLvAddUserActivity1.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
String jsonStr = sh.makeServiceCall(url);
PojoList pojo;
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject o = new JSONObject(jsonStr);
JSONArray restaurants = o.getJSONArray("getdefaultprogramlist");
for (int k = 0; k < restaurants.length(); k++) {
JSONObject rating1 = restaurants.getJSONObject(k);
asanaid = rating1.getString("programid");
Log.d("TestJson asanaid", asanaid);
asananame = rating1.getString("programname");
Log.d("TestJson asananame", asananame);
for (int i = 0; i < restaurants.length(); i++) {
JSONObject restaurant = restaurants.getJSONObject(i);
JSONArray ratings = restaurant.getJSONArray("ProgramItem");
for (int j = 0; j < ratings.length(); j++) {
JSONObject rating = ratings.getJSONObject(j);
String stepnumber = rating.getString("AsanaId");
Log.d("TestJson stepnumber", stepnumber);
String stepdesc = rating.optString("Asananame");
Log.d("TestJson stepdesc", stepdesc);
String stepimg = rating.getString("duration");
Log.d("TestJson stepimg", stepimg);
String stepimgeversion = rating.getString("repetation");
Log.d("TestJson stepimgvrsion ", stepimgeversion);
// int sid = Integer.parseInt(convertArrayToString(mSpinnerItems));
pojo = new PojoList(stepnumber, stepdesc, selected, convertArrayToString(mSpinnerItems));
SubjectList.add(pojo);
System.out.println("Size of Entry list from Map: " + SubjectList.size());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void args) {
if (pDialog.isShowing())
pDialog.dismiss();
adapter = new MyModifyPgmLvAddUserAdapter1(MyModifyPgmLvAddUserActivity1.this, R.layout.my_yoga_poseslv_add_user_single_item, SubjectList);
listView.setAdapter(adapter);
}
}
public static String strSeparator = ",";
public static String convertArrayToString(String[] array){
String str = "";
for (int i = 0;i<array.length; i++) {
str = str+array[i];
// Do not append comma at the end of last element
if(i<array.length-1){
str = str+strSeparator;
}
}
return str;
}
}
//PojoList
public class PojoList {
String AsanName = null;
String AsanId = null;
boolean selected = false;
String sid = null;
String sarray = null;
boolean sSelected = false;
public PojoList(String Sname, String SFullForm, boolean selected, String Sarray) {
super();
this.AsanName = Sname;
this.AsanId = SFullForm;
this.selected = selected;
this.sarray = Sarray;
// this.sid = Sid;
}
public String getAsanName() {
return AsanName;
}
public void setAsanName(String code) {
this.AsanName = code;
}
public String getAsanId() {
return AsanId;
}
public void setAsanId(String id) {
this.AsanId = id;
}
#Override
public String toString() {
return AsanName + " " + AsanId ;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public String getId() {
return sarray;
}
public void setId(String sarray) {
this.sarray = sarray;
}
}
//adapter
public class MyModifyPgmLvAddUserAdapter1 extends ArrayAdapter<PojoList> {
public ArrayList<PojoList> MainList;
public ArrayList<PojoList> SubjectListTemp;
Context context;
private String[] mSpinnerItems = new String[]{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
// public ListAdapter.SubjectDataFilter subjectDataFilter ;
public MyModifyPgmLvAddUserAdapter1(Context context, int id, ArrayList<PojoList> subjectArrayList) {
super(context, id, subjectArrayList);
this.SubjectListTemp = new ArrayList<PojoList>();
this.SubjectListTemp.addAll(subjectArrayList);
this.MainList = new ArrayList<PojoList>();
this.MainList.addAll(subjectArrayList);
}
public class ViewHolder {
TextView SubjectName, aId;
TextView SubjectFullForm, aName;
CheckBox cb;
Spinner spinner;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.my_yoga_poseslv_add_user_single_item, null);
holder = new ViewHolder();
holder.aName = (TextView) convertView.findViewById(R.id.listview_tv);
holder.aId = (TextView) convertView.findViewById(R.id.listview_id);
holder.cb = (CheckBox) convertView.findViewById(R.id.listview_cb);
holder.spinner = (Spinner) convertView.findViewById(R.id.listview_spinner);
holder.cb.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v ;
PojoList pojo = (PojoList) cb.getTag();
Toast.makeText(getContext(),
"Clicked on Checkbox: " + cb.getText() +
"Clicked on Checkbox: "+
" is " + cb.isChecked() + "Id is : "+ pojo.getAsanName(),
Toast.LENGTH_LONG).show();
pojo.setSelected(cb.isChecked());
}
});
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(getContext(),
android.R.layout.simple_list_item_1, mSpinnerItems);
holder.spinner.setAdapter(spinnerAdapter);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
PojoList pojo = SubjectListTemp.get(position);
holder.aName.setText(pojo.getAsanName());
holder.cb.setText(pojo.getAsanId());
holder.cb.setChecked(pojo.isSelected());
holder.cb.setTag(pojo);
// holder.spinner.setSelection(Integer.parseInt(pojo.getId()));
holder.spinner.setSelected(pojo.isSelected());
return convertView;
}
}
//list row
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:background="#cccccc">
<Spinner
android:id="#+id/listview_spinner"
style="#style/AppTheme"
android:layout_width="42dp"
android:layout_height="40dp"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginEnd="21dp"
android:layout_marginRight="21dp" />
<CheckBox
android:id="#+id/listview_cb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:layout_marginTop="2dp"
android:layout_marginLeft="4dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:id="#+id/listview_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="17dp"
android:layout_marginStart="17dp"
android:text="TextView"
android:textSize="1sp"
android:visibility="invisible"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/listview_imgs"
android:layout_toEndOf="#+id/listview_imgs" />
<TextView
android:id="#+id/listview_id"
android:layout_width="wrap_content"
android:visibility="invisible"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/listview_spinner"
android:layout_alignRight="#+id/listview_spinner"
android:layout_alignTop="#+id/listview_imgs"
android:text="TextView" />
</RelativeLayout>
</LinearLayout>
I have created a basic project to show you how to setup a simple Spinner. This is my xml for the list row:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="center_vertical"
android:padding="20dp">
<TextView
android:id="#+id/row_item_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Spinner
android:id="#+id/row_item_spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:padding="2dp" />
This is the adapter for the listview:
public class BasicSpinnerAdapter extends BaseAdapter {
private ArrayList<String> mSpinnerItems;
private ArrayList<String> mData;
private Context mContext;
public BasicSpinnerAdapter(ArrayList<String> data, ArrayList<String> spinnerItems, Context context) {
mData = data;
mContext = context;
mSpinnerItems = spinnerItems;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public Object getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.row_item_spinner, null);
}
TextView textView = (TextView) view.findViewById(R.id.row_item_textview);
Spinner spinner = (Spinner) view.findViewById(R.id.row_item_spinner);
textView.setText(mData.get(position));
ArrayAdapter<String> adapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_spinner_item, mSpinnerItems);
spinner.setAdapter(adapter);
return view;
}
And this is my Activity, where I start it all:
public class SpinnerListviewActivity extends AppCompatActivity {
private ListView lvSpinner;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spinner_listview_activity);
lvSpinner = (ListView) findViewById(R.id.listview_spinner);
ArrayList<String> mData = new ArrayList<>();
mData.add("Test1");
mData.add("Test2");
mData.add("Test3");
mData.add("Test4");
ArrayList<String> mSpinnerData = new ArrayList<>();
mSpinnerData.add("1");
mSpinnerData.add("2");
mSpinnerData.add("3");
mSpinnerData.add("4");
BasicSpinnerAdapter adapter = new BasicSpinnerAdapter(mData, mSpinnerData, this);
lvSpinner.setAdapter(adapter);
}
}
The xml for my Activity:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/listview_spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
A screenshot of the Listview:
Hope this gives you an idea of how to setup a basic Spinner in a List row. Feel free to ask any questions!

How to get value from listview checkbox?

I am having a little trouble with listview, I want to get values of listview whose checkbox are selected when button is clicked. till now i have created a listview with checkboxes and fetched all the values from mysql but i am not able to get values of listview which are checked.
This is my class
public class ListViewMultipleSelectionActivity extends Activity{
Button button;
String myJSON;
private static final String TAG_NAME = "cat_name";
JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList;
ListView list1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
personList = new ArrayList<HashMap<String,String>>();
list1 = (ListView) findViewById(R.id.list);
button = (Button)findViewById(R.id.testbutton);
getlat();
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
public void getlat(){
class GetDataJSON extends AsyncTask<String, Void, String> {
public void onPreExecute() {
}
#Override
protected String doInBackground(String... params) {
InputStream inputStream = null;
String result = null;
try {
URL url = new URL("http://xxxxxxxxxxxx/category.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in=new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder("");
String line="";
while ((line = in.readLine()) != null)
{
sb.append(line).append("\n");
}
result = sb.toString();
}
assert inputStream != null;
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line).append("\n");
}
result = sb.toString();
} catch (Exception e) {
Log.i("tagconvertstr", "["+result+"]");
System.out.println(e);
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON = result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
protected void showList(){
try {
peoples = new JSONArray(myJSON);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String name = c.getString(TAG_NAME);
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_NAME,name);
personList.add(persons);
}
ListAdapter adapter = new SimpleAdapter(
ListViewMultipleSelectionActivity.this, personList, R.layout.result,
new String[]{TAG_NAME},
new int[]{R.id.name}
);
list1.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
list1.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="#+id/testbutton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Submit" />
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#id/testbutton"
android:layout_alignParentTop="true"/>
</RelativeLayout>
result.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<CheckBox
android:id="#+id/cbBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical" >
</CheckBox>
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:orientation="vertical"
android:layout_weight="1" >
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textStyle="bold"/>
</LinearLayout>
</LinearLayout>
i have implemented this on testbutton(Button) click please check
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
SparseBooleanArray checked = list1.getCheckedItemPositions();
ArrayList<String> selectedItems = new ArrayList<String>();
for (int i = 0; i < checked.size(); i++) {
int position = checked.keyAt(i);
if (checked.valueAt(i))
selectedItems.add((String) adapter.getItem(position));
}
String[] valuess = new String[selectedItems.size()];
for (int i = 0; i < selectedItems.size(); i++) {
valuess[i] = selectedItems.get(i);
}
Toast.makeText(ListViewMultipleSelectionActivity.this, String.valueOf(valuess), Toast.LENGTH_SHORT).show();
}
});
this is i am getting after click
E/-->>>>: [Ljava.lang.String;#ca01299
What you can do is creating a custom class to store these values along with a custom adapter that supports it. So whenever you click the button you can call the given function to retrieve the statuses of those items. Example architecture given below:
PS: Since I don't know what you want to do with checked values, I left you there with comments which you can change with your need.
MainActivity.java
package com.rencsaridogan.stackoverflow;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<ExampleClass> objects;
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
objects = new ArrayList<>();
for (int i = 0; i < 10; i++){
objects.add(new ExampleClass("Example Name " + i));
}
final ListView listView = (ListView) findViewById(R.id.listView);
final Button testButton = (Button) findViewById(R.id.testButton);
final ExampleAdapter exampleAdapter = new ExampleAdapter(this, R.layout.list_cell, objects);
listView.setAdapter(exampleAdapter);
exampleAdapter.notifyDataSetChanged();
testButton.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
getCheckedItems();
}
});
}
private void getCheckedItems(){
for (int i = 0; i < 10; i++) {
if (objects.get(i).isChecked()){
Log.i("MainActivity",i + " is checked");
/**
* Value is checked, do what you need to do here
*/
} else {
Log.i("MainActivity",i + " is NOT checked");
/**
* Value is NOT checked
*/
}
}
}
}
ExampleAdapter.java
package com.rencsaridogan.stackoverflow;
import android.annotation.SuppressLint;
import android.content.Context;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by rencsaridogan on 16/02/2017.
*/
public class ExampleAdapter extends ArrayAdapter<ExampleClass> {
ArrayList<ExampleClass> objects;
Listener listener;
Context context;
public ExampleAdapter(Context context, int resource, ArrayList<ExampleClass> objects) {
super(context, resource);
this.context = context;
this.objects = objects;
}
#Override public int getViewTypeCount() {
return super.getViewTypeCount();
}
#Override public int getCount() {
return objects.size();
}
#SuppressLint("InflateParams") #Override public View getView(int position, View convertView, #NonNull ViewGroup parent) {
if (convertView == null){
Log.i("ExampleAdapter","ConvertView inflated");
convertView = LayoutInflater.from(context).inflate(R.layout.list_cell, null, false);
}
Log.i("ExampleAdapter","Setting of values");
final ExampleClass data = objects.get(position);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.textView = (TextView) convertView.findViewById(R.id.textView);
viewHolder.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
viewHolder.textView.setText(data.getName());
viewHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
data.setChecked(isChecked);
}
});
return convertView;
}
public void setListener(Listener listener) {
this.listener = listener;
}
private class ViewHolder {
TextView textView;
CheckBox checkBox;
}
public ArrayList<ExampleClass> getObjects() {
return objects;
}
public void setObjects(ArrayList<ExampleClass> objects) {
this.objects = objects;
notifyDataSetChanged();
}
#Override public long getItemId(int position) {
return super.getItemId(position);
}
public interface Listener {
void onCheckedChanged(int position);
}
}
ExampleClass.java
package com.rencsaridogan.stackoverflow;
/**
* Created by rencsaridogan on 16/02/2017.
*/
public class ExampleClass {
String name;
boolean isChecked;
public ExampleClass(String name) {
this.name = name;
}
public ExampleClass(String name, boolean isChecked) {
this.name = name;
this.isChecked = isChecked;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isChecked() {
return isChecked;
}
public void setChecked(boolean checked) {
isChecked = checked;
}
}
Set checkbox object as tag to your row view that might be your 'convertView' in getView() method of your adapter.
Write on click listener on your row view.
3.Inside that click-listener to row view getTag from view that's parameter in onClick method and cast it to checkbox and then setChecked to true for that checkbox object.
code might look like this,
convertView.setTag(yourCheckBoxObject);
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
CheckBox cb = (CheckBox) v.getTag();
cb.setChecked(true);
}
});
Please refer this sight for more information Getting an issue while checking the dynamically generated checkbox through list view
In your Adapter there was one #override method called getView() in that method you will get the current item which you will clicked
holder.checkbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
CheckBox checkBox=(CheckBox) view;
String tagName="";
if(checkBox.isChecked()){
tagName=checkBox.getTag().toString();
deleteServices.add(tagName);
checkboxArrayList.add(checkBox);
}else {
checkboxArrayList.remove(checkBox);
tagName=checkBox.getTag().toString();
if(deleteServices.size()>0&&deleteServices.contains(tagName)){
deleteServices.remove(tagName);
}
});

How to show JSON objects in listview?

Main class
Using volley library to fetch JSON data from URL.
public class MyActivity extends Activity {
ListView listView;
List<Details> rowItems;
RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details2);
url = getIntent().getStringExtra("key");
if(savedInstanceState!=null){
Log.d("STATE",savedInstanceState.toString());
}
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jor = new JsonObjectRequest(url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray ja = response.getJSONArray("results");
ArrayList<Details> myModelList = new ArrayList<Details>();
Details mymodel = null;
for (int i = 0; i < ja.length(); i++) {
JSONObject jsonObject = ja.getJSONObject(i);
mymodel = new Details();
mymodel.id = Integer.parseInt(jsonObject.optString("id").toString());
mymodel.url = jsonObject.getString("resLink");
mymodel.resType = jsonObject.getString("resType");
mymodel.name = jsonObject.getString("resName");
myModelList.add(mymodel);
setData();
}
}catch(JSONException e){e.printStackTrace();}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley","Error");
}
}
);
requestQueue.add(jor);
}
private void setData() {
listView = (ListView) findViewById(R.id.list);
CustomListViewAdapter adapter = new CustomListViewAdapter(this,
R.layout.list_item, rowItems);
listView.setAdapter(adapter);
//listView.setOnItemClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
My CustomListViewAdapter claas is below
public class CustomListViewAdapter extends ArrayAdapter<Details> {
Context context;
public CustomListViewAdapter(Context context, int resourceId,
List<Details> items) {
super(context, resourceId, items);
this.context = context;
}
/*private view holder class*/
private class ViewHolder {
TextView txtTitle;
TextView txtDesc;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Details rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView.findViewById(R.id.desc);
holder.txtTitle = (TextView) convertView.findViewById(R.id.title);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.txtDesc.setText(rowItem.getResType());
holder.txtTitle.setText(rowItem.getName());
return convertView;
}
My Details class
public class Details extends Results {
String name;
String resType;
String url;
int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getResType() {
return resType;
}
public void setResType(String resType) {
this.resType = resType;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
* want to showthe data I received in list view*
my XML
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
list_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/icon"
android:paddingBottom="10dp"
android:textColor="#CC0033"
android:textSize="16dp" />
<TextView
android:id="#+id/desc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/title"
android:layout_toRightOf="#+id/icon"
android:paddingLeft="10dp"
android:textColor="#3399FF"
android:textSize="14dp" />
You are doing everything right but not passing your myModelList which contains the data and are passing the empty rowItems list. Once you fetch all data and create your myModelList, call
setData(myModelList);
And change your setData method as follows
private void setData(List<Details> mList) {
listView = (ListView) findViewById(R.id.list);
CustomListViewAdapter adapter = new CustomListViewAdapter(this,
R.layout.list_item, mList);
listView.setAdapter(adapter);
}
use following line in your adapter class getView()
Details rowItem = (Details) getItem(position);
instead of
Details rowItem = getItem(position);
Update your setData methode as you are not getting list to set data.
private void setData(List<Details> list) {
listView = (ListView) findViewById(R.id.list);
CustomListViewAdapter adapter = new CustomListViewAdapter(this,
R.layout.list_item, list);
listView.setAdapter(adapter);
}
Also change setData(); to setData(myModelList);
In adapter you are using List rowItems;
so code of onResponse method should be like as follows
JSONArray ja = response.getJSONArray("results");
rowItems = new ArrayList<Details>();
Details mymodel = null;
for (int i = 0; i < ja.length(); i++) {
JSONObject jsonObject = ja.getJSONObject(i);
mymodel = new Details();
mymodel.id = Integer.parseInt(jsonObject.optString("id").toString());
mymodel.url = jsonObject.getString("resLink");
mymodel.resType = jsonObject.getString("resType");
mymodel.name = jsonObject.getString("resName");
rowItems.add(mymodel);
}
setData();
To make the json parsing easy you can use Gson library as explained here
http://www.mysamplecode.com/2013/07/android-json-stream-data-parsing.html

Null Pointer Exception at Imageview in Custom List View

I have a custom list view with a TextView and three ImageViews. On click of image view I want to start a new activity and pass the data of specific position to next activity. But I am getting null pointer exception.
I have use this for refernce http://jmsliu.com/2444/click-button-in-listview-and-get-item-position.html
Here is my code. This is main Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_employees);
toolbar = (Toolbar) findViewById(R.id.app_bar);
toolbar.setTitle("Manage Employees");
nPregress = (ProgressBar) findViewById(R.id.toolbar_progress_bar);
nPregress.setVisibility(View.GONE);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mainList = (ListView) findViewById(R.id.manageemployeeList);
employee1 = new ArrayList<Pojo>();
tii = new ArrayList<String>();
SharedPreferences prefs = getSharedPreferences("MyPref4", MODE_PRIVATE);
Set<String> set1 = prefs.getStringSet("employeename", null);
if (set1 != null ) {
List<String> nameList = new ArrayList<String>(0);
nameList.addAll(set1);
for (int i = 0; i < set1.size(); i++) {
pojo = new Pojo();
pojo.setMgEmpName(nameList.get(i));
employee1.add(pojo);
Log.e("namemmee0", "" + nameList.get(i));
}
mainAdapter = new EmployeesAdapter(EmployeesActivity.this, employee1);
mainList.setAdapter(mainAdapter);
} else {
new NetCheck().execute();
}
new NetCheck().execute();
emp_edit = (ImageView) findViewById(R.id.imgedit);
emp_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View parentRow = (View) v.getParent();
mainList = (ListView) parentRow.getParent();
final int position = mainList.getPositionForView(parentRow);
String emp_name = employee1.get(position).getMgEmpName().toString();
Intent i = new Intent(EmployeesActivity.this, EditEmployee.class);
i.putExtra("empname", emp_name);
startActivity(i);
}
});
}
I am getting exception at this line
emp_edit.setOnClickListener(new View.OnClickListener()
How can i do this? Please help me.
This is my Adapter. I have tried onClickListener in adpter also But i am not gtting proper data in next activity.. I get same value even if i select different list view items
public class EmployeesAdapter extends BaseAdapter {
TextView categoryName;
Pojo pojo;
private Context activity1;
ArrayList<Pojo> data1;
private ArrayList<Pojo> arraylist1 = null;
public static LayoutInflater inflater;
ImageView edit, delete, historyy;
String del_empid;
public EmployeesAdapter(Context ctx, ArrayList<Pojo> employee1) {
// TODO Auto-generated constructor stub
activity1 = ctx;
data1 = employee1;
inflater = (LayoutInflater) activity1
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.arraylist1 = new ArrayList<Pojo>();
this.arraylist1.addAll(data1);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data1.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return data1.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = convertView;
v = inflater.inflate(R.layout.manage_emp_list, parent, false);
pojo = data1.get(position);
categoryName = (TextView) v.findViewById(R.id.employeeName);
categoryName.setText(pojo.getMgEmpName());
edit = (ImageView) v.findViewById(R.id.imgedit);
delete = (ImageView) v.findViewById(R.id.imgdelete);
historyy = (ImageView) v.findViewById(R.id.imgHistory);
edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(activity1, EditEmployee.class);
intent.putExtra("empname", "" + pojo.getMgEmpName());
intent.putExtra("empmobile", "" + pojo.getMgEmpContact());
intent.putExtra("empemail", "" + pojo.getMgEmpEmail());
intent.putExtra("empappcost", "" + pojo.getMgEmpAppCost());
activity1.startActivity(intent);
}
});
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
del_empid = pojo.getMgEmp_id();
new NetCheck().execute();
}
});
historyy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(activity1, MainActivity.class);
activity1.startActivity(intent);
}
});
return v;
}
manage_emp_list of the custom list view
<?xml version="1.0" encoding="utf-8"?>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/employeeName"
android:textColor="#000000"
android:textSize="18dp"
android:padding="5dp"
android:layout_marginLeft="5dp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imgdelete"
android:src="#drawable/delete32"
android:layout_marginRight="12dp"
android:layout_marginEnd="12dp"
android:layout_alignBottom="#+id/employeeName"
android:layout_toLeftOf="#+id/imgedit"
android:layout_toStartOf="#+id/imgedit"
android:clickable="true"
android:onClick="delete_empoyee"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imgedit"
android:layout_marginRight="15dp"
android:layout_marginEnd="15dp"
android:src="#drawable/edit32"
android:layout_alignTop="#+id/imgdelete"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:clickable="true"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imgHistory"
android:src="#drawable/history32"
android:clickable="true"
android:onClick="employee_history"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/imgdelete"
android:layout_toStartOf="#+id/imgdelete"
/>
Try this, There may be position mismatch when store it locally
edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(activity1, EditEmployee.class);
intent.putExtra("empname", "" + data1.get(position).getMgEmpName());
intent.putExtra("empmobile", "" + data1.get(position).getMgEmpContact());
intent.putExtra("empemail", "" + data1.get(position).getMgEmpEmail());
intent.putExtra("empappcost", "" + data1.get(position).getMgEmpAppCost());
activity1.startActivity(intent);
}
});
Your getView() method should look like this in your adapter:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
pojo = data1.get(position);
ViewHolder holder;
if (pojo != null) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.manage_emp_list, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.categoryName.setText(pojo.getMgEmpName());
//holder.edit.setOnClickListener()...
//holder.delete.setOnclickListener()...
}
return convertView;
}
And add a static class in to your Adapter:
static class ViewHolder {
TextView categoryName;
ImageView edit;
ImageView delete;
ImageView historyy;
public ViewHolder(View view) {
categoryName = (TextView) v.findViewById(R.id.employeeName);
edit = (ImageView) v.findViewById(R.id.imgedit);
delete = (ImageView) v.findViewById(R.id.imgdelete);
historyy = (ImageView) v.findViewById(R.id.imgHistory);
}
}

How to get checkbox state in a gridview

i need to get the check-box state from a grid-view when clicking on a button
i tried many things but the state is always "false"
here is my code
this is the adapter
public class CustomSuggestFriends extends ArrayAdapter<Items_FriendsRequest> {
Context context;
dbManage objDB;
Items_FriendsRequest Items_SuggestFriends;
List<Items_FriendsRequest>items;
int Position;
SharedPreferences SharedP;
String user_id="1002", secret_id = "2143054018";
String u_id="1025", ut_ = "1";
public CustomSuggestFriends(Context context, int textViewResourceId,
List<Items_FriendsRequest> objects) {
super(context, textViewResourceId, objects);
this.context = context;
}
private class viewHolder {
private ImageView userImage;
private TextView userName;
private CheckBox checkbox;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
viewHolder holder = null;
ImageLoader_Crop imageLoader_Crop;
Items_SuggestFriends = getItem(position);
Position = position;
objDB = new dbManage(getContext());
items = objDB.select_SuggestFriends();
objDB.CloseDataBase();
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
imageLoader_Crop = new ImageLoader_Crop(context.getApplicationContext());
if (convertView == null) {
convertView = inflater.inflate(R.layout.items_suggestdriends, null);
holder = new viewHolder();
holder.userImage = (ImageView) convertView
.findViewById(R.id.Items_SuggestFriends_userImage);
holder.userName = (TextView) convertView
.findViewById(R.id.Items_SuggestFriends_NameTXT);
holder.checkbox = (CheckBox) convertView
.findViewById(R.id.Items_SuggestFriends_checkBox);
holder.checkbox.setTag(position);
holder.checkbox.setChecked(items.get(position).isSelected());
holder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (Integer) buttonView.getTag(); // Here we get the position that we have set for the checkbox using setTag.
items.get(getPosition).setSelected(buttonView.isChecked()); // Set the value of checkbox to maintain its state.
Log.v("Changed",items.get(getPosition).getId_()+"");
}
});
convertView.setTag(holder);
} else {
holder = (viewHolder) convertView.getTag();
}
holder.userName.setText(Items_SuggestFriends.getName_());
String SuggestF = Items_SuggestFriends.getSuggestFriendsSEND();
if (SuggestF.equals("0")) {
holder.checkbox.setVisibility(View.VISIBLE);
} else if (SuggestF.equals("1")) {
holder.checkbox.setVisibility(View.GONE);
}
String imageURL = "";
imageURL = functionspackage.Constants.server_file + "1/s/"
+ Items_SuggestFriends.getId_() + "."
+ Items_SuggestFriends.getRand_() + ".jpg";
holder.userImage.setTag(imageURL);
imageLoader_Crop.DisplayImage(imageURL, context, holder.userImage);
return convertView;
}
}
this is my class its got a button called send
and in this button i need to get the ids of what is cheked
public class SuggestFriends extends Activity {
int count;
dbManage objDB;
SharedPreferences SharedP;
String user_id, secret_id = "";
public static String u_id, ut_ = "";
Button send, cancel;
List<Items_FriendsRequest> SuggestFriendsItems;
GridView gridView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.displayphoto_from_album);
initialise_View();
here i need to get the values but its always false!!!!
send.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
count = gridView.getCount();
objDB = new dbManage(SuggestFriends.this);
SuggestFriendsItems = objDB.select_SuggestFriends();
objDB.CloseDataBase();
SparseBooleanArray sparseBooleanArray = gridView
.getCheckedItemPositions();
// add the id of the ones that been checked . . to string with
// (,)
for (int i = 0; i < count; i++) {
if(sparseBooleanArray.valueAt(i) == true) {
Log.e(sparseBooleanArray.get(i)+"",SuggestFriendsItems.get(i).getId_()+"");
} else if (!sparseBooleanArray.get(i)) {
Log.e(sparseBooleanArray.get(i) +"",SuggestFriendsItems.get(i).getId_()+"");
gridView.getItemAtPosition(i);
}
}
}
});
SharedP = getSharedPreferences(functionspackage.Constants.SharedP_name,
0);
user_id = SharedP.getString(functionspackage.Constants.SharedP_user_id,
null);
secret_id = SharedP.getString(
functionspackage.Constants.SharedP_secret_id, null);
if (getIntent().hasExtra(functionspackage.Constants.Extra_Uid)) {
u_id = getIntent().getStringExtra(
functionspackage.Constants.Extra_Uid);
}
if (getIntent().hasExtra(functionspackage.Constants.Extra_ut)) {
ut_ = getIntent().getStringExtra(
functionspackage.Constants.Extra_ut);
}
SuggestFriends_AsyncTask Async = new SuggestFriends_AsyncTask();
Async.execute(user_id, secret_id, u_id, ut_);
}
// ///////////////////////////////////////////////////////////////
// ///////////////////////////////////////////////////////////////
// ///////////////////////////////////////////////////////////////
String response = "";
class SuggestFriends_AsyncTask extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
response = "";
response = functionspackage.methodes.HTTP_fileInf_OPhotos(
functionspackage.Constants.server_Web_Profiles
+ "/suggest/" + params[3] + "/" + params[2],
params[0], params[1], 0);
functionspackage.methodes.install_JSON_SuggestFriends(
SuggestFriends.this, response);
objDB = new dbManage(SuggestFriends.this);
SuggestFriendsItems = objDB.select_SuggestFriends();
objDB.CloseDataBase();
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
CustomSuggestFriends adapterSuggestFriends = new CustomSuggestFriends(
SuggestFriends.this, R.layout.items_suggestdriends,
SuggestFriendsItems);
gridView.setAdapter(adapterSuggestFriends);
gridView.setChoiceMode(GridView.CHOICE_MODE_MULTIPLE);
}
}
// ///////////////////////////////////////////////////////////////
// ///////////////////////////////////////////////////////////////
// ///////////////////////////////////////////////////////////////
private void initialise_View() {
gridView = (GridView) findViewById(R.id.DisplayPhoto_gridView);
gridView.setNumColumns(3);
gridView.setBackgroundColor(Color.BLACK);
send = (Button) findViewById(R.id.SendSuggestBotton);
cancel = (Button) findViewById(R.id.CancelsuggestFrindes);
}
}
this is the log
Use a Sparse Boolean Array
Check this link here
https://groups.google.com/forum/?fromgroups#!topic/android-developers/No0LrgJ6q2M
Check Romain Guy Solution. Use GridView instead of Listview.
Similar to the one answered here. Instead of listview use gridview.
in gridview checkbox is unchecked while scrolling gridview up and down
Heres' another example. Same use gridview instead of Listview
How to change the text of a CheckBox in listview?
Here's the complete example
public class MainActivity extends Activity implements
AdapterView.OnItemClickListener {
int count;
private CheckBoxAdapter mCheckBoxAdapter;
String[] GENRES = new String[] {
"Action", "Adventure", "Animation", "Children", "Comedy",
"Documentary", "Drama",
"Foreign", "History", "Independent", "Romance", "Sci-Fi",
"Television", "Thriller"
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final GridView listView = (GridView) findViewById(R.id.lv);
// listView.setItemsCanFocus(false);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(this);
mCheckBoxAdapter = new CheckBoxAdapter(this, GENRES);
listView.setAdapter(mCheckBoxAdapter);
Button b= (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
StringBuilder result = new StringBuilder();
result.append("Checked at position");
result.append("\n");
for(int i=0;i<mCheckBoxAdapter.mCheckStates.size();i++)
{
if(mCheckBoxAdapter.mCheckStates.get(i)==true)
{
result.append(mCheckBoxAdapter.mCheckStates.get(i)+" at"+i);
result.append("\n");
}
}
Toast.makeText(MainActivity.this, result, 10000).show();
}
});
}
public void onItemClick(AdapterView parent, View view, int
position, long id) {
mCheckBoxAdapter.toggle(position);
}
class CheckBoxAdapter extends ArrayAdapter implements CompoundButton.OnCheckedChangeListener
{ private SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView tv1,tv;
CheckBox cb;
String[] gen;
CheckBoxAdapter(MainActivity context, String[] genres)
{
super(context,0,genres);
mCheckStates = new SparseBooleanArray(genres.length);
mInflater = (LayoutInflater)MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
gen= genres;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return gen.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
vi = mInflater.inflate(R.layout.checkbox, null);
tv= (TextView) vi.findViewById(R.id.textView1);
cb = (CheckBox) vi.findViewById(R.id.checkBox1);
tv.setText("Name :"+ gen [position]);
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
cb.setOnCheckedChangeListener(this);
return vi;
}
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);
}
}
}
activit_main.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<GridView
android:id="#+id/lv"
android:layout_width="wrap_content"
android:numColumns="2"
android:layout_height="wrap_content"
android:layout_above="#+id/button1"/>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Button" />
</RelativeLayout>
checkbox.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="15dp"
android:layout_marginTop="34dp"
android:text="TextView" />
<CheckBox
android:id="#+id/checkBox1"
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/textView1"
android:layout_marginRight="22dp"
android:layout_marginTop="23dp" />
</RelativeLayout>
Snap shot
There is a lot of unecessary code in you question in my opinion (way better than too little, though), try change:
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (Integer) buttonView.getTag(); // Here we get the position that we have set for the checkbox using setTag.
// -- buttonView.isChecked() changed to isChecked -- //
items.get(getPosition).setSelected(isChecked); // Set the value of checkbox to maintain its state.
Log.v("Changed",items.get(getPosition).getId_()+"");
}
If that does not work please show clearly where you read the false value and expect true.

Categories

Resources