1

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

enter image description here

Jehad
  • 472
  • 2
  • 10
  • 24

2 Answers2

3

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

enter image description here

Community
  • 1
  • 1
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
0

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.

cYrixmorten
  • 7,110
  • 3
  • 25
  • 33
  • so SparseBooleanArray sparseBooleanArray = gridView .getCheckedItemPositions(); is the place you get all false values? – cYrixmorten Sep 29 '13 at 11:38