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

Android fragments 获取动态创建的复选框的值,android-fragments,Android Fragments,在这种情况下,我从数据库中获取数据,即问题和答案,相应地,数据库中的答案数等于动态创建的复选框数,我希望当用户选中复选框时,该复选框的值必须保存在sqlite数据库中 公共类Multiselect扩展片段 { TextView; 默认httpclient httpclient; HttpPost-HttpPost; HttpResponse HttpResponse; HttpEntity HttpEntity; HttpResponse响应; http实体; InputStream=null;

在这种情况下,我从数据库中获取数据,即问题和答案,相应地,数据库中的答案数等于动态创建的复选框数,我希望当用户选中复选框时,该复选框的值必须保存在sqlite数据库中

公共类Multiselect扩展片段 {

TextView;
默认httpclient httpclient;
HttpPost-HttpPost;
HttpResponse HttpResponse;
HttpEntity HttpEntity;
HttpResponse响应;
http实体;
InputStream=null;
字符串结果=null;
StringBuilder sb=null;
缓冲读取器;
杰索纳雷·贾雷;
弦线;
字符串问题;
字符串回答;
无疑问;
int i;
视图;
语境;
int-id=1;
复选框复选框按钮;
最终复选框[]复选框按钮=新复选框[50];
线性布局;
//数据库多选数据库;
字符串文本;
创建时的公共void(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
已创建ActivityState上的公共无效(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
}
@凌驾
CreateView上的公共视图(布局、充气机、视图组容器、捆绑包保存状态)
{
视图=充气机。充气(R.layout.multiselect,container,false);
l=(LinearLayout)view.findViewById(R.id.l1);
/*字符串l1=l.toString();
字符串strtext=getArguments().getString(“下一步”);
Log.e(“str”,strtext)*/
StrictMode.enableDefaults();
ques=(TextView)view.findViewById(R.id.quesmultiselect);
//db=新数据库MultiSelect(getActivity());
//db.open();
getMultiselect();
getAnswer(容器);
Log.e(“id”和“+id”);
Log.e(“count”和“+l.getChildCount());
返回视图;
}
void getMultiselect()
{
尝试
{           
httpclient=新的DefaultHttpClient();
//httppost=新的httppost(“http://10.0.2.2/multiselectandroid.php"); 
httpResponse=httpclient.execute(httppost);
httpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
}
捕获(例外e)
{
e(“Log_标记”,“http连接错误”+e.toString());
ques.setText(“错误!!”);
}
//将响应转换为字符串
尝试
{
reader=新的BufferedReader(新的InputStreamReader(is,“iso-8859-1”),8);
sb=新的StringBuilder();
sb.append(reader.readLine()+“\n”);
而((line=reader.readLine())!=null)
{
sb.追加(第+行“\n”);
}
is.close();
结果=sb.toString();
}
捕获(例外e)
{
Log.e(“Log_标记”,“错误转换结果”+e.toString());
}
//配对数据
尝试
{
jArray=新的JSONArray(结果);
JSONObject json_data=null;
对于(i=0;i
public类Multiselect扩展片段
{
//声明变量
文本视图;
文本视图条件;
text视图sectionidtext;
文本视图指令;
字符串起始;
国际问题(无);
字符串问题1;
字符串surveyName;
字符串选择问题;
字符串用户名;
int min_答案;
int max_答案;
int-id=1;
数据库处理程序数据库;
字符串评级=空;
视图;
最终复选框[]应答复选框=新复选框[50];
线性布局回答设置布局;
字符串应答文本;
整数计数=0;
字符串限制;
字符串段ID;
字符串日期=空;
字符串时间=空;
字符串tablename=“multiselect”;
字符串输入\ u应答=null;
字符串用户标识;
创建时的公共void(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//获取问题编号、用户名、调查名称、问卷名称和用户id值
Bundle mulitselectBundle=getArguments();
问题编号=mulitselectBundle.getInt(“问题编号”);
surveyName=mulitselectBundle.getString(“surveyName”);
selectedQues=mulitselectBundle.getString(“quesname”);
username=mulitselectBundle.getString(“用户名”);
userid=mulitselectBundle.getString(“userid”);
Log.e(“mulitselect”,“问题编号”);
Log.e(“mulitselect”,surveyName);
Log.e(“mulitselect”,selectedQues);
Log.e(“mulitselect”,用户名);
Log.e(“mulitselect”,userid);
}
已创建ActivityState上的公共无效(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
}
@凌驾
CreateView上的公共视图(布局、充气机、视图组容器、捆绑包保存状态)
{
视图=充气机。充气(R.layout.multiselect,container,false);
//获取答案的线性布局id
answersettinglayout=(LinearLayout)view.findViewById(R.id.answersetting);
//正在获取问题的文本视图id
ques=(TextView)view.findViewById(R.id.quesmultiselect);
//正在获取条件的textview的id
条件=(TextView)view.findViewById(R.id.conditionmulti);
//正在获取节id的textview的id
sectionidtext=(TextView)view.findViewById(R.id.sectionidmultiselect);
//获取用于显示说明的文本视图的id
指令=(TextView)view.findViewById(R.id.instructionmultiselect);
//创建数据库的对象
db=新的DatabaseHandler(getActivity());
//函数调用
检索问题();
getAnswer(容器);
getCheckedCheckBox();
返回视图;
}
void retrieveQuestion()
{
//开放数据库
db.open();
Log.e(“内部”、“检索问题”);
//获取问题和节id的值
Cursor questioncursor=db.getQuestion(用户名、调查名称、所选问题、问题编号);
int length=questioncursor.getCount();
Log.e(“长度”,“长度+长度”);
//获取问题和节id
if(questioncursor.moveToFirst())
{
//获取列号
int indexquestion=questioncursor.getColumnIndex(“问题”);
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();
    }

}
}
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();
        }
    }
}