获取动态创建的复选框的值

时间:2014-03-12 07:24:00

标签: android-fragments

在此im从数据库中获取数据,即问题和答案,因此数据库中的答案数量等于动态创建的复选框的数量,我希望当用户选中复选框时,该复选框的值必须是我保存在sqlite数据库中

公共类Multiselect扩展了Fragment     {

TextView ques;

DefaultHttpClient httpclient;
HttpPost httppost;
HttpResponse httpResponse;
HttpEntity httpEntity;
HttpResponse response;
HttpEntity entity;
InputStream is = null;
String result = null;
StringBuilder sb=null;
BufferedReader reader;
JSONArray jArray;

String line;
String question;
String answer;
int questionno;
int i;

View view;
Context context;
int id=1;
CheckBox checkboxbutton;



final CheckBox[] checkboxbuttons = new CheckBox[50];

LinearLayout l;
//DatabaseMultiselect db;  

String text;

public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
}

public void onActivityCreated(Bundle savedInstanceState) 
{
    super.onActivityCreated(savedInstanceState);


}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
{

    view = inflater.inflate(R.layout.multiselect, container, false);
    l=(LinearLayout)view.findViewById(R.id.l1);
    /*String l1=l.toString();
    String strtext=getArguments().getString("next");
    Log.e("str",strtext);*/
    StrictMode.enableDefaults();
    ques=(TextView)view.findViewById(R.id.quesmultiselect);
    //db=new DatabaseMultiselect(getActivity());
//  db.open();
    getMultiselect();
    getAnswer(container);
    Log.e("id",""+id);
    Log.e("count",""+l.getChildCount());



  return view;
}





void getMultiselect()
{
    try
    {           
        httpclient=new DefaultHttpClient();
       // httppost= new HttpPost("http://10.0.2.2/multiselectandroid.php"); 
        httpResponse = httpclient.execute(httppost); 
        httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();
    }
    catch(Exception e)
    {
        Log.e("log_tag", "Error in http connection"+e.toString());
        ques.setText("error!!");
    }

        //convert response to string
    try
    {
        reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
        sb = new StringBuilder();
        sb.append(reader.readLine() + "\n");

        while ((line = reader.readLine()) != null) 
        {
            sb.append(line + "\n");
        }
        is.close();
        result=sb.toString();
    }
    catch(Exception e)
    {
        Log.e("log_tag", "Error converting result "+e.toString());
    }
    //paring data
    try
    {

        jArray = new JSONArray(result);
        JSONObject json_data=null;
        for(i=0;i<jArray.length();i++)
        {
            json_data = jArray.getJSONObject(i);
            questionno=json_data.getInt("question_no");
            question=json_data.getString("question");
            Log.e("question",question);
            //s=s+""+question;

        }
        ques.setText(question);
    }
    catch(JSONException excep)
    {
        excep.printStackTrace();
        //Toast.makeText(getBaseContext(), "Error", Toast.LENGTH_LONG).show();
    }
    catch (ParseException excep)
    {
        excep.printStackTrace();
    }



}





void getAnswer(ViewGroup container)
{

    try
    {           
        httpclient=new DefaultHttpClient();
        httppost= new HttpPost("http://10.0.2.2/multiselectanswer.php?questionno="+questionno); 
        httpResponse = httpclient.execute(httppost); 
        httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();
    }
    catch(Exception e)
    {
        Log.e("log_tag", "Error in http connection"+e.toString());
        ques.setText("error!!");
    }

        //convert response to string
    try
    {
        reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
        sb = new StringBuilder();
        sb.append(reader.readLine() + "\n");

        while ((line = reader.readLine()) != null) 
        {
            sb.append(line + "\n");
        }
        is.close();
        result=sb.toString();
    }
    catch(Exception e)
    {
        Log.e("log_tag", "Error converting result "+e.toString());
    }
    //pairing data
    try
    {
        jArray = new JSONArray(result);
        JSONObject json_data=null;
        for(i=0;i<jArray.length();i++)
        {
            json_data = jArray.getJSONObject(i);
            answer=json_data.getString("answer");
            checkboxbuttons[i]  = new CheckBox(container.getContext());
            checkboxbuttons[i].setId(id);

            l.addView(checkboxbuttons[i]);
            checkboxbuttons[i].setText(answer);
            checkboxbuttons[i].setTextColor(Color.RED);
            int rid=checkboxbuttons[i].getId();
            Log.e("rid",""+rid);
            id++;
           }




           /* if(id.getCheckedRadioButton==true)
            {
                String selected=chk;
                Log.e("select",selected);
            }*/


        }

    catch(JSONException excep)
    {
        excep.printStackTrace();
        //Toast.makeText(getBaseContext(), "Error", Toast.LENGTH_LONG).show();
    }
    catch (ParseException excep)
    {
        excep.printStackTrace();
    }

}
}

1 个答案:

答案 0 :(得分:0)

public class Multiselect extends Fragment 
{
    //Declaring variables
    TextView ques;
    TextView condition;
    TextView sectionidtext;
    TextView instructions;
    String instructionset;
    int question_no;
    String question1;
    String surveyName;
    String selectedQues;
    String username;
    int min_answers;
    int max_answers;
    int id=1;
    DatabaseHandler db;
    String rating=null;
    View view;
    final CheckBox[] answercheckbox = new CheckBox[50];
    LinearLayout answersettinglayout;
    String answertext;
    int count=0;
    String limit;
    String sectionids;
    String date=null;
    String time=null;
    String tablename="multiselect";
    String input_answer=null;
    String userid;

    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);

        //Getting Question number,user name,survey name,questionnaire name and user id value
        Bundle mulitselectBundle=getArguments();
        question_no=mulitselectBundle.getInt("questionnum");
        surveyName=mulitselectBundle.getString("surveyname");
        selectedQues=mulitselectBundle.getString("quesname");
        username=mulitselectBundle.getString("username");
        userid=mulitselectBundle.getString("userid");

        Log.e("mulitselect"," "+question_no);
        Log.e("mulitselect",surveyName);
        Log.e("mulitselect",selectedQues);
        Log.e("mulitselect",username);
        Log.e("mulitselect",userid);
    }

    public void onActivityCreated(Bundle savedInstanceState) 
    {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
    {
        view = inflater.inflate(R.layout.multiselect, container, false);

        //Getting id of Linear Layout for answers
        answersettinglayout=(LinearLayout)view.findViewById(R.id.answersetting);

        //Getting id of text view for question
        ques=(TextView)view.findViewById(R.id.quesmultiselect);

        //Getting id of textview for conditions
        condition=(TextView)view.findViewById(R.id.conditionmulti);

        //Getting id of textview for section id
        sectionidtext=(TextView)view.findViewById(R.id.sectionidmultiselect);

        //Getting id of text view for instructions display
        instructions=(TextView)view.findViewById(R.id.instructionmultiselect);

        //Create object of database
        db=new DatabaseHandler(getActivity());

        //Function call
        retrieveQuestion();
        getAnswer(container);
        getcheckedCheckBoxes();

        return view;
    }

    void retrieveQuestion()
    {
        //Open database
        db.open();

        Log.e("inside","retrieve question");

        //Fetching value of question and section id
        Cursor questioncursor=db.getQuestion(username,surveyName,selectedQues,question_no);

        int length=questioncursor.getCount();
        Log.e("length",""+length);

        //Getting question and section id
        if(questioncursor.moveToFirst())
        {
            //Getting column number
            int indexquestion=questioncursor.getColumnIndex("question");
            Log.e("index",""+indexquestion);

            //Getting value of question and section id
            question1= questioncursor.getString(indexquestion);
            sectionids=questioncursor.getString(questioncursor.getColumnIndex("ques_id"));

            //Setting question
            ques.setText(question1);
            Log.e("question",question1);

            //Setting section id
            sectionidtext.setText("Q."+sectionids);
        }
        //Closing cursor
        questioncursor.close();
    }

    void getAnswer(ViewGroup container)
    {
        //Open database
        db.open();

        Log.e("inside","answer question");

        //Fetching answers
        Cursor answergettingcursor=db. getAnswer(username,surveyName,selectedQues,question_no);

        //Declaring variable
        int i=0;    

        //Getting answer value
        while(answergettingcursor.moveToPosition(i))
        {
            //Getting column number
            int indexanswer=answergettingcursor.getColumnIndex("answer");

            //creating check boxes
            answercheckbox[i]  = new CheckBox(container.getContext());

            //Setting id of check boxes
            answercheckbox[i].setId(id);

            //Adding check boxes in layout
            answersettinglayout.addView(answercheckbox[i]);

            //Setting answer value
            answercheckbox[i].setText(answergettingcursor.getString(indexanswer));

            //Setting text color
            answercheckbox[i].setTextColor(Color.RED);

            int rid=answercheckbox[i].getId();
            Log.e("rid",""+rid);

            //Incrementing value
            id++;
            i++;        
        } 
        //Closing cursor
        answergettingcursor.close();
    }

    void getcheckedCheckBoxes()
    {
        Log.e("id",""+id);
        Log.e("count",""+answersettinglayout.getChildCount());

        //Fetching value of minimum and maximum characters
        Cursor checkcondition=db.getmultiselecttabledata(username, surveyName, selectedQues, question_no);

        //For Conditions
        if(checkcondition.moveToFirst())
        {
            //Getting column number
            int indexmin_answers=checkcondition.getColumnIndex("min_answers");
            int indexmax_answers=checkcondition.getColumnIndex("max_answers");
            Log.e("indexanswer",""+indexmin_answers);
            Log.e("indexanswer1",""+indexmax_answers);

            //Getting value of minimum and maximum characters and instructions 
            min_answers=checkcondition.getInt(indexmin_answers);
            max_answers=checkcondition.getInt(indexmax_answers);
            instructionset=checkcondition.getString(checkcondition.getColumnIndex("instructions"));
            Log.e("texttableview",""+min_answers);
            Log.e("texttableview",""+max_answers);

            //Setting value of instructions
            instructions.setText(instructionset);

            //For answers 
            for(int k=0;k<answersettinglayout.getChildCount();k++)
            {
                //Whether check box checked or not
                answercheckbox[k].setOnClickListener(new OnClickListener()
                {
                    public void onClick(View v)
                    {
                        //If check box checked
                        if(((CheckBox) v).isChecked())
                        {
                            //Incrementing value of count
                            count++;
                            Log.e("count",""+count);

                            //Getting value of checked check box
                            answertext=((CheckBox) v).getText().toString();
                            Log.e("checkbox",""+answertext);

                            //Checking min and max character conditions
                            if(count>=min_answers)
                            {
                                if(count>max_answers)
                                {
                                    //Setting text
                                    condition.setText("Selected answers exceeds maximum length");

                                    //Setting text color
                                    condition.setTextColor(Color.RED);

                                    //Setting value of limit
                                    limit="max";
                                }
                                else
                                {
                                    //Setting text
                                    condition.setText("");

                                    //Setting value of limit
                                    limit="proper";
                                }
                            }
                            else
                            {
                                //Setting text
                                condition.setText("Please select more answers");

                                //Setting text color
                                condition.setTextColor(Color.RED);

                                //Setting value of limit
                                limit="min";
                            }
                            //Inserting answers
                            db.insertAnswer(userid,username,surveyName,selectedQues,question_no,question1,answertext,rating,input_answer,limit,date,time,sectionids,tablename);                     

                        }
                        //if unchecked check box
                        else
                        {   
                            //Decreasing count value
                            count--;
                            Log.e("count",""+count);

                            //Getting value of checked check box
                            answertext=((CheckBox) v).getText().toString();
                            Log.e("checkboxdelete",""+answertext);

                            //Deleting unchecked check box value
                            db.deleteQuesMultiselect(userid,username, surveyName, selectedQues, question_no,answertext);

                            //Checking min and max character conditions
                            if(count>=min_answers)
                            {
                                if(count>max_answers)
                                {
                                    //Setting text
                                    condition.setText("Selected answers exceeds maximum length");

                                    //Setting text color
                                    condition.setTextColor(Color.RED);
                                }

                                else
                                {
                                    //Setting text
                                    condition.setText("");
                                }
                            }
                            else
                            {
                                //Setting text
                                condition.setText("Please select more answers");

                                //Setting text color
                                condition.setTextColor(Color.RED);
                            }
                        } 
                    }
                });
            }
            //Closing cursor
            checkcondition.close();
        }
    }
}