Based on the Database Values i was creating Text field , Radio button, Checkboxes..For checkboxes i don't know how to get selected checkbox Values for corresponding Question.
My Code is..
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();
}
}
}
Thanks in Advance.
You can get checkbox value by calling checkBox.isChecked() which will return true or false. //Edit: So, in code u can add something like this:
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
}
});
or, as wrote before, you can just call c1.isChecked() to get the value of the checkbox.
Suggestion : Instead Of Decoding it via JSON paring you can use GSON and convert it into List of Object then render view
Alternative Solution : You can use RecyclerView and Plot View according to your Question Type in List with different Holders, and store data to your list position wise
Now come to your Problem : i don't know how to get selected checkbox Values for corresponding Question
You can get Child count and loop it to get all views inside your parent layout,
Check Which Question is this from your hashmap...
Check if this is instance of CheckBox and get the Checked Status and text ( I am assuming you need to send answer with question )
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
}
.
.
.
}
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.