0

I am creating an list view with dynamically added checkboxes. However i want to add a onClickListener to it so when i change the state of a certain checkbox, i do something. However i cannot seem to find out how to create Uniqe ID's from an array.

this is my code:

public class SingleContactActivity extends Activity implements
    OnCheckedChangeListener {
private int Array_Count = 0;
private String url = "http://www.EXAMPLE.com";
private JSONArray items = null;
private String product;
private String id;
private String store;
private String state;
private String uniqeID;
ArrayList<HashMap<String, String>> listitems;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_single_contact);
    listitems = new ArrayList<HashMap<String, String>>();
    // getting intent data

    // Get JSON values from previous intent
    new downloadJsonitems().execute();
}

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    // TODO Auto-generated method stub

}

private class downloadJsonitems extends AsyncTask<Void, Void, Void> {
    LinearLayout my_layout = (LinearLayout) findViewById(R.id.test);
    LinearLayout my_checked_layout = (LinearLayout) findViewById(R.id.checked);

    @Override
    protected Void doInBackground(Void... arg0) {
        ServiceHandler sh = new ServiceHandler();
        url = url + "1";
        Log.i("pref", "url =" + url);
        String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
        JSONObject jsonObj;
        try {
            jsonObj = new JSONObject(jsonStr);
            Log.i("pref", "json =" + jsonObj);
            items = jsonObj.getJSONArray("items");
            for (int x = 0; x < items.length(); x++) {
                JSONObject lists = items.getJSONObject(x);
                id = lists.getString("primaryKey");
                store = lists.getString("store");
                product = lists.getString("items");
                state = lists.getString("state");
                uniqeID = lists.getString("uniqeID");
                HashMap<String, String> contacts = new HashMap<String, String>();
                contacts.put("id", id);
                contacts.put("store", store);
                contacts.put("product", product);
                contacts.put("state", state);
                contacts.put("cbid", uniqeID);
                Log.i("pref", "" + listitems);
                listitems.add(contacts);
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        for (int n = 0; n < listitems.size(); n++) {
            CheckBox cb = new CheckBox(getApplicationContext());
            cb.setId(Integer.parseInt(listitems.get(n).get("cbid")));
            cb.setText(listitems.get(n).get("product"));
            cb.setTextColor(Color.BLACK);
            if (listitems.get(n).get("state").toString().equals("true")) {
                cb.setChecked(true);
                my_checked_layout.addView(cb);
                cb.setBackgroundColor(Color.argb(200, 8, 242, 2));
                cb.setTextColor(Color.parseColor("#CFCFCF"));
            } else {
                cb.setChecked(false);
                cb.setBackgroundColor(Color.argb(100, 5, 214, 0));
                cb.setTextColor(Color.parseColor("#F7F7F7"));
                my_layout.addView(cb);
            }
        }
        Intent in = getIntent();
        String name = in.getStringExtra(MainActivity.TAG_FIRSTNAME);
        String email = in.getStringExtra(MainActivity.TAG_EMAIL);
        String list = in.getStringExtra(MainActivity.TAG_LIST);
        String[] seperatedString = list.split(", ");
        // Displaying all values on the screen
        TextView lblName = (TextView) findViewById(R.id.name_label);
        TextView lblEmail = (TextView) findViewById(R.id.email_label);
        // Array_Count=seperatedString.length;

        LinearLayout my_layout = (LinearLayout) findViewById(R.id.test);

        /*
         * for (int i = 0; i < Array_Count; i++) { TableRow row =new
         * TableRow(null); row.setId(i); row.setLayoutParams(new
         * LayoutParams
         * (LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT)); CheckBox
         * checkBox = new CheckBox(getActivity());
         * checkBox.setOnCheckedChangeListener(this); checkBox.setId(i);
         * checkBox.setText(seperatedString[i]); row.addView(checkBox);
         * my_layout.addView(row); }
         */
        lblName.setText(name);
        lblEmail.setText(email);
    }

The following is my XML:

<?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"
  android:padding="10dp">
  <!-- Name Label -->
  <TextView android:id="@+id/name_label"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="25dip"
        android:textStyle="bold"
        android:paddingTop="10dip"
        android:paddingBottom="10dip"
        android:textColor="#43bd00"/> <!--  green -->
  <!-- Email Label -->

  <TextView
  android:id="@+id/email_label"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:textColor="#EB0505" /> <!-- red -->

  <!-- Mobile Label -->

  <TextView
  android:id="@+id/mobile_label"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:textColor="#E5FF00" 
  android:textStyle="bold" 
  android:text="Empty, Mobile_label"/> <!-- yellow -->

 <TextView
 android:id="@+id/list_label"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:textColor="#FF00FF" /> <!--  pink -->

 <LinearLayout
 android:id="@+id/test"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:orientation="vertical" />

 <LinearLayout
 android:id="@+id/checked"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:orientation="vertical" >

 </LinearLayout>

</LinearLayout>

What i thought would work is just add a number behind the id's

so my could would like like this:

Checkbox cb[n] = new Checkbox(getApplicationContext());
cb[n].setId(...);
cb[n].onClickListener() = new OnClickListener(){
//TODO add unimplemented code
}

But this didn't seem to work out... Any suggestions?

1
  • I think listitems is an ArrayList, or? But what is the item inside? Commented Jun 5, 2014 at 9:58

2 Answers 2

1

For Checkboxes, use OnCheckedChangeListener, not OnClickListener. Also, for ListView, use a ListAdapter, so that you can reuse the views if the user scrolls through the list instead of creating Views for every list item.

Here some sample code:

    private class MyArrayAdapter extends ArrayAdapter<Product>{

    private MyOnCheckedChangeListener listener;

    public MyArrayAdapter(Context context, int resource) {
        super(context, resource);
        this.listener = new MyOnCheckedChangeListener();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        //super call to create / recycle the view
        View view = super.getView(position, convertView, parent);

        //set the checkbox and text
        CheckBox checkBox = (CheckBox) view.findViewById(R.id.list_checkbox);

        //set the id of the item in the tag of the checkbox
        checkBox.setTag(getItemId(position));
        checkBox.setOnCheckedChangeListener(listener);

        TextView textView = (TextView) view.findViewById(R.id.list_textView);
        textView.setText(getItem(position).getText());

    }

    @Override
    public long getItemId(int position) {
        //use the id of the Product as the ItemId
        return getItem(position).getId();
    }
}


private class MyOnCheckedChangeListener implements CompoundButton.OnCheckedChangeListener{

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        //retrieve the id of the item from the tag of the checkbox
        doSomething((Long) buttonView.getTag());
    }


}

In the onCreate of your ListView, you have to set the adapter to it:

ArrayAdapter<Product> adapter = new MyArrayAdapter(this, R.layout.list_item);
adapter.addAll(listOfProducts);
listView.setAdapter(adapter);

The layout of the list item:

<?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">

    <CheckBox android:id="@+id/list_checkbox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"/>

    <TextView android:id="@+id/list_textView"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_toLeftOf="@id/list_checkbox"/>

</RelativeLayout>

Like this, you don't have to create the Views for every item yourself, and you can also add an remove items from the list easily through the adapter.

Here's some further reading about ListViews, including examples: http://www.vogella.com/tutorials/AndroidListView/article.html

Sign up to request clarification or add additional context in comments.

3 Comments

So what you are saying is that i should just make a change listener that listens to the ID of the check i press in the view?
For short, yes. But I'll add a better solution that uses an ArrayAdapter for the ListView soon.
thanks for your answer, however this does not work for me, as i have to set the checkbox in different lists (order by checked or not) i have updated my code so it is more clear. on how the intel is gathered
0

Tinkle showed me the right way.. here is what does the trick for those struggling with the same issue

Private boolean checkstate;
for (int n = 0; n < listitems.size(); n++) {
    CheckBox cb = new CheckBox(getApplicationContext());
    cb.setId(Integer.parseInt(listitems.get(n).get("cbid")));
    cb.setText(listitems.get(n).get("product"));
    cb.setTextColor(Color.BLACK);
    if (listitems.get(n).get("state").toString().equals("true")) {
        cb.setChecked(true);
        my_checked_layout.addView(cb);
        cb.setBackgroundColor(Color.argb(200, 8, 242, 2));
        cb.setTextColor(Color.parseColor("#CFCFCF"));
        checkstate = true;
    } else {
        cb.setChecked(false);
        cb.setBackgroundColor(Color.argb(100, 5, 214, 0));
        cb.setTextColor(Color.parseColor("#F7F7F7"));
        checkstate = false;
        my_layout.addView(cb);
    }
    cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {

    if (checkstate == false) {
        Log.i("pref ", "button " + buttonView.getId()
                + "is not enabled");

    checkstate = true;
    Log.i("pref =", "" + checkstate);
    }else {
        Log.i("pref", "button is checked");
        checkstate = false;
    }
    } 
});
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.