2016-12-22 23 views
0

データベースの値に基づいて、テキストフィールド、ラジオボタン、チェックボックスを作成していました。チェックボックスを選択するには選択されたチェックボックスを取得する方法がわかりません。Androidで動的に作成されたチェックボックスの値を取得する

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, "[email protected]"); 
     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(); 
     } 


    } 





} 

おかげです。

+1

ここにあなたのコードを分けていただけますか?質問を投稿する必要がありますか? – NilayDani

+0

1つのオプションは、各ビューのあなたのIDにタグを付けることです – Nithinlal

+0

#thanksは肯定応答#NilayDani私のコードを更新しました! plzはそれを通ります –

答えて

0

trueまたはfalseを返すcheckBox.isChecked()を呼び出すと、チェックボックスの値を取得できます。 //編集:

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を呼び出すことができます。 ので、コードにuがこのような何かを追加することができます。

0

提案:代わりに、あなたは、ビューのレンダリングGSONを使用すると、オブジェクトのリストに変換することができますペアリングJSONを経由して、それを復号化する

代替ソリューション:あなたは、あなたの質問の種類に応じてRecyclerViewを使用してViewをプロットすることができますあなたのリストの位置に別の保有者、およびストアデータと一覧に賢明

は、今すぐあなたの問題に来る:私は質問

あなたに対応するために選択したチェックボックスの値を取得する方法がわかりませんこのチェックボックスのインスタンスであるかどうかを確認

...子供はあなたのハッシュマップからあなたの親のレイアウト内のすべてのビュー、質問はこれです

チェックを得るためにそれをカウントし、ループ取得し、チェックステータスとテキストを取得することができます(

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 
    } 

    . 
    . 
    . 

} 
関連する問題