在Android中获取动态创建的复选框的值

时间:2016-12-22 10:58:49

标签: java android checkbox dynamic

基于数据库值我正在创建文本字段,单选按钮,复选框。对于复选框,我不知道如何获取相应问题的选定复选框值。

user view page image

我的代码是..

    package com.example.technical14.myapplication;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.annotation.UiThread;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main2Activity extends Activity {


    private static final String Latest_Products = "Questions";
    JSONArray productsArray = null;

    StringBuilder result;

    public static final int CONNECTION_TIMEOUT = 10000;
    public static final int READ_TIMEOUT = 15000;

    bean b = null;

    LinearLayout lView = null;
    private List<EditText> le = null;
    HashMap<String, bean> hm = null;
    private Button b1 = null;
    private List<RadioGroup> lrg = null;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  new Asyncchk().execute();

    }


    private class Asyncchk extends AsyncTask<String, String, StringBuilder> {
        ProgressDialog pdLoading = new ProgressDialog(Main2Activity.this);
        HttpURLConnection conn;
        URL url = null;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            //this method will be running on UI thread
            pdLoading.setMessage("\tLoading...");
            pdLoading.setCancelable(false);
            pdLoading.show();

        }

        @Override
        protected StringBuilder doInBackground(String... param) {

            try {

                // Enter URL address where your php file resides
                url = new URL("http://192.168.1.33/app/alldata.php");

            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                Toast.makeText(getApplicationContext(), "URL Exception", Toast.LENGTH_LONG).show();

                e.printStackTrace();


            }
            try {
                // Setup HttpURLConnection class to send and receive data from php and mysql
                conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(READ_TIMEOUT);
                conn.setConnectTimeout(CONNECTION_TIMEOUT);
                conn.setRequestMethod("POST");

                // setDoInput and setDoOutput method depict handling of both send and receive
                conn.setDoInput(true);
                conn.setDoOutput(true);



                // Append parameters to URL
                Uri.Builder builder = new Uri.Builder()
                        .appendQueryParameter("user_id", "user_id")
                        .appendQueryParameter("dpt_id", "dptid");
                String query = builder.build().getEncodedQuery();

                // Open connection for sending data
                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
                writer.write(query);
                writer.flush();
                writer.close();
                os.close();
                conn.connect();

            } catch (IOException e1) {
                // TODO Auto-generated catch block
                Log.e("error","error");
                e1.printStackTrace();


            }

            try {

                int response_code = conn.getResponseCode();

                // Check if successful connection made
                if (response_code == HttpURLConnection.HTTP_OK) {

                    // Read data sent from server
                    InputStream input = conn.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(input));

                     result = new StringBuilder();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    String next1;
                    while ((next1 = bufferedReader.readLine()) != null) {

                        result.append(next1 + "\n");

                    }


                }

            } catch (IOException e) {

                e.printStackTrace();


            }  finally {
                conn.disconnect();
            }

            return result;

        }

        @Override
        protected void onPostExecute(StringBuilder s) {
            super.onPostExecute(s);


            try{
                JSONArray login;
                JSONObject obj=new JSONObject(s.toString());

                hm = new HashMap<String, bean>();
                le = new ArrayList<EditText>();
                lrg = new ArrayList<RadioGroup>();

                if(s.toString().contains("Result")) {
                    login = obj.getJSONArray("Result");


                    int cbid=1;
                    int cbid1=10000;
                    lView = new LinearLayout(Main2Activity.this);
                    for(int i=0;i<login.length();i++)
                    {

                        JSONObject c = login.getJSONObject(i);

                        Log.e("length",c.toString());

                        productsArray = c.getJSONArray(Latest_Products);

                        for (int j = 0; j < productsArray.length(); j++) {
                            b = new bean();

                            JSONObject cc = productsArray.getJSONObject(j);



                            if(cc.getString("q_type").equalsIgnoreCase("1")){

                                b.setQno(j);
                                b.setQtype(1);
                                b.setQues(cc.getString("question"));
                                TextView t1 = new TextView(Main2Activity.this);
                                t1.setText(cc.getString("question"));

                                EditText e1 = new EditText(Main2Activity.this);
                                e1.setWidth(350);

                                lView.addView(t1);
                                lView.addView(e1);

                                lView.setOrientation(LinearLayout.VERTICAL);

                                le.add(e1);

                                String qno =Integer.toString(j);

                                hm.put(qno, b);

                            }

                            else if (cc.getString("q_type").equalsIgnoreCase("2")) {

                                b.setQno(j);
                                b.setQtype(2);
                                b.setQues(cc.getString("question"));
                                TextView t1 = new TextView(Main2Activity.this);
                                t1.setText(cc.getString("question"));

                                RadioGroup rg = new RadioGroup(Main2Activity.this);
                                final RadioButton[] rb = new RadioButton[2];
                                rg.setOrientation(LinearLayout.HORIZONTAL);


                                rb[0] = new RadioButton(Main2Activity.this);
                                rb[1] = new RadioButton(Main2Activity.this);
                                rb[0].setText(cc.getString("q_opt1"));
                               // rb[0].setId(cbid+100);

                                rb[1].setText(cc.getString("q_opt2"));
                               // rb[1].setId(cbid1+101);

                                rg.addView(rb[0]);
                                rg.addView(rb[1]);


                                lrg.add(rg);

                                lView.addView(t1);
                                lView.addView(rg);

                                lView.setOrientation(LinearLayout.VERTICAL);
                                String qno =Integer.toString(j);
                                hm.put(qno, b);
                                cbid++;
                                cbid1++;
                            }



                            else if (cc.getString("q_type").equalsIgnoreCase("3")) {

                                b.setQno(j);
                                b.setQtype(3);
                                b.setQues(cc.getString("question"));
                                TextView t1 = new TextView(Main2Activity.this);
                                t1.setText(cc.getString("question"));

                                CheckBox[] cb = new CheckBox[2];

                                CheckBox c1 = new CheckBox(Main2Activity.this);
                                CheckBox c2 = new CheckBox(Main2Activity.this);
                                CheckBox c3 = new CheckBox(Main2Activity.this);



                                c1.setText(cc.getString("q_opt1"));

                                c2.setText(cc.getString("q_opt2"));

                                c3.setText(cc.getString("q_opt3"));

                                lView.addView(t1);
                                lView.addView(c1);
                                lView.addView(c2);
                                lView.addView(c3);

                                lView.setOrientation(LinearLayout.VERTICAL);
                                String qno =Integer.toString(j);
                                hm.put(qno, b);
                            }


                        }


                    }

                }


            }catch (JSONException e) {
                e.printStackTrace();

            }

            pdLoading.dismiss();

            b1 = new Button(Main2Activity.this);
            b1.setText("Send Mail");
            lView.addView(b1);


            setContentView(lView);

            b1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    HashMap<String,String> cc = checkdata(hm);
                    Sendmail(cc);
                }
            });
        }

    }


    public HashMap<String, String> checkdata(HashMap h) {

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

        HashMap<String, bean> rh = h;

        int l = lrg.size();
        String ll = Integer.toString(l);
        Log.e("lllllleeeeeeeeee", ll);

        int q = 0;
        int q1 = 0;
        int r = 0;

        for (Map.Entry<String, bean> ent : rh.entrySet()) {

            String k1 = ent.getKey();

            bean bb = ent.getValue();


            //Toast.makeText(getApplicationContext(), bb.getQues(), Toast.LENGTH_LONG).show();
            if (bb.getQtype() == 1) {

                String aa = le.get(q).getText().toString();
                Log.e("qtype", aa);
                //Toast.makeText(getApplicationContext(), aa, Toast.LENGTH_LONG).show();
                ss.put(bb.getQues(), aa);
                q++;
            } else if (bb.getQtype() == 2) {

                int bb1 = lrg.get(q1).getCheckedRadioButtonId();

                String qno =Integer.toString(bb1);
                Toast.makeText(getApplicationContext(),qno,Toast.LENGTH_SHORT).show();

                RadioButton rt = (RadioButton) findViewById(bb1);
                //Toast.makeText(getApplicationContext(), rt.getText().toString(), Toast.LENGTH_LONG).show();
                ss.put(bb.getQues(), rt.getText().toString());
                q1++;

            }


        }

        return ss;
    }




    public void Sendmail(HashMap s) {

        HashMap<String, String> sss = s;

        String[] toppings = new String[sss.size()];

        int size1 = 0;

        for (String key : sss.keySet()) {

            toppings[size1] = key + "\n" + sss.get(key) + "\n";
            System.out.println("key: " + key + " value: " + sss.get(key));


            size1++;
        }

        StringBuilder builder = new StringBuilder();
        for (String s3 : toppings) {
            builder.append(s3);
        }
        String mbody = builder.toString();


        Intent i = new Intent(Intent.ACTION_SEND);
        i.setType("message/rfc822");
        i.putExtra(Intent.EXTRA_EMAIL, "xyz@gmail.com");
        i.putExtra(Intent.EXTRA_SUBJECT, "Task Activity");
        i.putExtra(Intent.EXTRA_TEXT, mbody);
        try {
            startActivity(i);
        } catch (android.content.ActivityNotFoundException ex) {
            Toast.makeText(Main2Activity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
        }


    }





}

提前致谢。

2 个答案:

答案 0 :(得分:0)

您可以通过调用checkBox.isChecked()获取复选框值,该值将返回true或false。 //编辑: 所以,在代码中你可以添加如下内容:

CheckBox c1 = new CheckBox(Main2Activity.this);
CheckBox c2 = new CheckBox(Main2Activity.this);
CheckBox c3 = new CheckBox(Main2Activity.this);
//API LEVEL 17 REQUIRED
c1.setId(View.generateViewId());
c2.setId(View.generateViewId());
c3.setId(View.generateViewId());

c1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
            //Here you can track if c1 was checked by using isChecked value
    }
});

或者,如前所述,您只需调用c1.isChecked()即可获取复选框的值。

答案 1 :(得分:0)

建议:不是通过JSON配对解码,而是使用GSON并将其转换为对象列表然后呈现视图

替代解决方案:您可以根据列表中的问题类型使用RecyclerView和Plot View使用不同的持有者,并将数据存储到列表位置

现在来问你的问题:我不知道如何获得相应问题的选中复选框值

您可以获取子计数并将其循环以获取父布局中的所有视图,

从您的hashmap中检查哪个问题...

检查这是否是CheckBox的实例并获取Checked Status和text(我假设您需要发送带问题的答案)

int childCount=lView.getChildCount();



for(int i=0;i<childCount;i++)
{
    Object object=lView.getChildAt(i);

    if(object instanceof TextView){
        //TextView instance
        //Your Question find it from your hashmap

    }

    if(object instanceof CheckBox){
        //CheckBox instance
        ((CheckBox)object).isChecked();
        ((CheckBox)object).getText();
        //as per your requirement
    }


    if(object instanceof RadioButton) {
        //RadioButton instance
    }

    .
    .
    .

}