简体   繁体   中英

How to Get the value of selected checkbox item in android?

I am developing quiz like application (multiple choice question) that receives the question from the server and send the answer collection to server button click. For this I have used ListView that consist TextView for the question and four checkbox items for 4 choices. I have successfully written code to receive the question with choices from the server. But now I could not figure out how to get the value of particular selected checkbox items among 4 choicebox for every question??

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.multiple.MainActivity" 
    >
    <!--android:background="@drawable/back"-->

 <TextView
     android:id="@+id/textview"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:text="@string/Title"
     android:background="@color/white"
     android:textColor="@color/col"
     android:gravity="center"
     android:textSize="30sp"
     />

   <ListView
       android:id="@+id/list"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:layout_below="@+id/textview"
       android:layout_marginBottom="40sp"
       />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/finish"
        android:id="@+id/button"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        />


</RelativeLayout>

list.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.multiple.MainActivity" 
    >
    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textStyle="bold"
        android:text="@string/Large"
        />
        <!--android:textColor="@color/white"-->
    <CheckBox
        android:id="@+id/checkBox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="30dp"
        android:layout_marginStart="30dp"
        android:layout_below="@+id/textView1"
        android:text="@string/Checkbox"
        android:textSize="25sp"
        android:background="@color/white"
        android:textColor="@color/lightblue"
        android:focusable="false"
        />

    <CheckBox
        android:id="@+id/checkBox2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="30dp"
        android:layout_marginStart="30dp"
        android:layout_below="@+id/checkBox1"       
        android:text="@string/Checkbox"
        android:textColor="@color/lightblue"
        android:textSize="25sp"
        android:focusable="false"
        />
    <CheckBox
        android:id="@+id/checkBox3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="30dp"
        android:layout_marginStart="30dp"
        android:layout_below="@+id/checkBox2"
        android:textColor="@color/lightblue"
        android:text="@string/Checkbox"
        android:textSize="25sp"
        android:focusable="false"
        />
    <CheckBox
        android:id="@+id/checkBox4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/checkBox3"
        android:layout_marginLeft="30dp"
        android:layout_marginStart="30dp"
        android:text="@string/Checkbox"
        android:textColor="@color/lightblue"
        android:textSize="25sp"
        android:focusable="false"
        />
</RelativeLayout>

MainActivity.java

package com.multiple;

import android.app.*;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.*;
import android.widget.AdapterView.*;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;


public class MainActivity extends Activity
{

    private ListView listview;
    private Button finishbtn;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        List<HashMap<String, String>> collect = new ArrayList<HashMap<String, String>>();
        listview = (ListView) findViewById(R.id.list);
        finishbtn= (Button)findViewById(R.id.button);

        populate p = new populate();

        try {
            collect = p.execute().get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    String[] str = new String[]{"first", "second", "third", "fourth", "fifth"};
        int[] val = new int[]{R.id.textView1, R.id.checkBox1, R.id.checkBox2, R.id.checkBox3, R.id.checkBox4};
        SimpleAdapter adapter = new SimpleAdapter(this, collect, R.layout.list, str, val);
        listview.setAdapter(adapter);

    listview.setOnClickListener(new ListView.OnClickListener()
    {

        @Override
        public void onClick(View v) {

        }
    });

}

    public class populate extends AsyncTask< String, Void,List<HashMap<String,String>> >
        {
            public List<HashMap<String,String>>  doInBackground(String... urls)
            {
                List<HashMap<String,String>> collect= new ArrayList<HashMap<String, String>>();
                    try
                    {


                        HttpClient client = new DefaultHttpClient();
                        HttpGet post = new HttpGet("http://192.168.10.116/file.json");
                        HttpResponse res= client.execute(post);
                        HttpEntity entity = res.getEntity();

                        String response = EntityUtils.toString(entity);



                        JSONObject obj = new JSONObject(response);
                        JSONArray jsonArray = obj.optJSONArray("multiple");

                            Log.i("size of the array",String.valueOf(jsonArray.length()));

                       ArrayList<JSONObject>  array = new ArrayList<JSONObject>();

                        for(int i=0; i < jsonArray.length(); i++)
                        {
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            array.add(jsonObject);

                        }

                        for(int i=0;i<array.size();i++){
                            JSONObject jsonObject = array.get(i);
                            String question = jsonObject.optString("question").toString();
                            String c1 = jsonObject.optString("choice1").toString();
                            String c2 = jsonObject.optString("choice2").toString();
                            String c3 = jsonObject.optString("choice3").toString();
                            String c4 = jsonObject.optString("choice4").toString();

//                            Log.i("asdfas",question);
//                            Log.i("second",c1);
//                            Log.i("third",c2);
//                            Log.i("fourth",c3);
//                            Log.i("fifth",c4);

                            HashMap<String,String>  map = new HashMap<String, String>();

                            map.put("first",question);
                            map.put("second",c1);
                            map.put("third",c2);
                            map.put("fourth",c3);
                            map.put("fifth",c4);

                            collect.add(map);
                        }


    }

                    catch(IOException ex){}

                    catch(JSONException ex){}

                return  collect;
            }


        }
}

For simplicity I have also stored the image of my app Application layout

Listview doesn't support onclicklistener. use onitemclicklistener as below

listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
{
CheckBox checkbox1 = (CheckBox) view.findViewByid(R.id.checkbox1);
CheckBox checkbox2 = (CheckBox) view.findViewByid(R.id.checkbox2);
CheckBox checkbox3 = (CheckBox) view.findViewByid(R.id.checkbox3);
CheckBox checkbox4 = (CheckBox) view.findViewByid(R.id.checkbox4);
if(checkbox1 .isChecked())
      String checked = checkbox1.getText().tostring()
if(checkbox2 .isChecked())
      String checked = checkbox2.getText().tostring()
if(checkbox3 .isChecked())
      String checked = checkbox3.getText().tostring()
if(checkbox4 .isChecked())
      String checked = checkbox4.getText().tostring()
            }
        });
listView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub
            str = "";
            str = (SimpleAdapter.adp_Str).get(arg2).toString();

        }

in your Adapter class declare str[] to static str[] });

First find that if the checkbox is checked or not by isChecked() and then get the values in a String .

String answer; 

if(mycheckbox.isChecked())
{
       answer=mycheckbox.getText().toString();
}

And if your questions support only one answer you can use RadioButton for that purpose. Link about RadioButton

http://www.mkyong.com/android/android-radio-buttons-example/

I presume you are going to collect the answers when you press the finish button. 1)You would need to iterate through your relative layouts inside the listview and then iterate through the checkboxes within the relative layout and store the value by using the isChecked() condition corresponding to every checkbox and fetch the corresponding value.

You should implement this within your finish button onclick listener.

int count = listview.getAdapter().getCount();
for(int i=0;i<count;i++){
   RelativeLayout relLayout = listview.getChildAt(i);
   for(int i=0;i< relLayout.getChildCount();i++){
      View v = relLayout.getChildAt(i);
      if(v instanceof CheckBox){
          CheckBox c = (CheckBox)v;
          if(c.isChecked()){
              String c = c.getText().tostring();
              //Add value to answers array or do processing
          }
      }
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM