I have a RadioGroup in which I have 5 RadioButton's. Also I have a button next. On click of next button the text of radiobuttons changes. It all works fine but some of the radio buttons are not selected. This is my xml file
public class SampleTestQuestionsActivity extends AppCompatActivity {
String totalques, timee, namee, idd;
String strServerResponse;
ProgressDialog nDialog;
ConnectionDetector cd;
Pojo pojo;
SamplePaperPojo samplePaperPojo;
RadioButton s_rb_1, s_rb_2, s_rb_3, s_rb_4, s_rb_5;
RadioGroup s_rbgrp;
private Toolbar toolbar;
TextView s_section, s_time, s_question;
Button s_submit, s_next, s_previous;
private CountDownTimer countDownTimer;
private boolean timerHasStarted = false;
long startTime;
private final long interval = 1 * 1000;
final Context context = this;
ArrayList<String> al_que_title;
ArrayList<String> al_que_id;
ArrayList<String> al_ans1;
ArrayList<String> al_ans2;
ArrayList<String> al_ans3;
ArrayList<String> al_ans4;
ArrayList<String> al_ans5;
ArrayList<String> al_correct;
ArrayList<String> al_exp;
ArrayList<String> al_desc;
String submitQuestionId;
ArrayList<SamplePaperPojo> sampleTest;
RadioButton selectedRbButton;
public static int inc = 0;
String correctAns;
ArrayList<String> selectedAns;
int selectedpos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample_test_questions);
toolbar = (Toolbar) findViewById(R.id.app_bar);
toolbar.setTitle("Sample Tests");
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
al_que_title = new ArrayList<String>();
al_que_id = new ArrayList<String>();
al_ans1 = new ArrayList<String>();
al_ans2 = new ArrayList<String>();
al_ans3 = new ArrayList<String>();
al_ans4 = new ArrayList<String>();
al_ans5 = new ArrayList<String>();
al_correct = new ArrayList<String>();
al_exp = new ArrayList<String>();
al_desc = new ArrayList<String>();
selectedAns = new ArrayList<String>();
Intent i =getIntent();
namee = i.getStringExtra("test_name");
totalques = i.getStringExtra("test_ques");
timee = i.getStringExtra("test_time");
idd = i.getStringExtra("test_id");
sampleTest = new ArrayList<SamplePaperPojo>();
Log.e("test_id", ""+idd);
Long ti = Long.valueOf(timee);
startTime = 1000*ti;
s_section = (TextView) findViewById(R.id.sampleSectionName);
s_time = (TextView) findViewById(R.id.sampleTimer);
s_question = (TextView) findViewById(R.id.sampleQuestion);
s_submit = (Button) findViewById(R.id.sampleSubmitAnswer);
s_next = (Button) findViewById(R.id.sampleNext);
s_previous = (Button) findViewById(R.id.samplePrevious);
s_rbgrp = (RadioGroup) findViewById(R.id.s_rbgrp);
s_rb_1 = (RadioButton) findViewById(R.id.SA);
s_rb_2 = (RadioButton) findViewById(R.id.SB);
s_rb_3 = (RadioButton) findViewById(R.id.SC);
s_rb_4 = (RadioButton) findViewById(R.id.SD);
s_rb_5 = (RadioButton) findViewById(R.id.SE);
countDownTimer = new MyCountDownTimer(startTime, interval);
s_time.setText(s_time.getText() + String.valueOf(startTime / 1000));
new NetCheck().execute();
s_next.setVisibility(View.GONE);
s_previous.setVisibility(View.GONE);
s_submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int index_selected = s_rbgrp.indexOfChild(s_rbgrp
.findViewById(s_rbgrp.getCheckedRadioButtonId()));
// get selected radio button from radioGroup
int selectedId = s_rbgrp.getCheckedRadioButtonId();
if (selectedId==-1){
AlertDialog alertDialog = new AlertDialog.Builder(
SampleTestQuestionsActivity.this).create();
alertDialog.setMessage("Please select atleast one answer.");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
s_next.setVisibility(View.VISIBLE);
}
});
s_next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
submitQuestionId = al_que_id.get(inc).toString();
s_rb_1.setTextColor(Color.parseColor("#000000"));
s_rb_2.setTextColor(Color.parseColor("#000000"));
s_rb_3.setTextColor(Color.parseColor("#000000"));
s_rb_4.setTextColor(Color.parseColor("#000000"));
s_rb_5.setTextColor(Color.parseColor("#000000"));
int selectedId = s_rbgrp.getCheckedRadioButtonId();
selectedRbButton = (RadioButton) findViewById(selectedId);
selectedRbButton.setChecked(false);
inc = inc + 1;
s_question.setText("" + al_que_title.get(inc).toString());
s_rb_1.setText("" + al_ans1.get(inc).toString());
s_rb_2.setText("" + al_ans2.get(inc).toString());
s_rb_3.setText("" + al_ans3.get(inc).toString());
s_rb_4.setText("" + al_ans4.get(inc).toString());
s_rb_5.setText("" + al_ans5.get(inc).toString());
s_next.setVisibility(View.GONE);
}
});
}
private class NetCheck extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
nDialog = new ProgressDialog(SampleTestQuestionsActivity.this);
nDialog.setMessage("Loading..");
nDialog.setTitle("Please Wait");
nDialog.setIndeterminate(false);
nDialog.setCancelable(true);
nDialog.show();
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.e("Post exec calleld", "dfds");
nDialog.dismiss();
s_question.setText("" + al_que_title.get(inc).toString());
s_rb_1.setText("" + al_ans1.get(inc).toString());
s_rb_2.setText("" + al_ans2.get(inc).toString());
s_rb_3.setText("" + al_ans3.get(inc).toString());
s_rb_4.setText("" + al_ans4.get(inc).toString());
s_rb_5.setText("" + al_ans5.get(inc).toString());
countDownTimer.start();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
cd = new ConnectionDetector(getApplicationContext());
if (!cd.isConnectingToInternet()) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(
new Runnable() {
#Override
public void run() {
AlertDialog alertDialog = new AlertDialog.Builder(
SampleTestQuestionsActivity.this).create();
alertDialog.setMessage("Error connecting to internet.");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
}
);
}
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpRequest = new HttpPost(
"http://url");
httpRequest.setHeader("Content-Type", "application/json");
SharedPreferences preff = getSharedPreferences(
"MyPref", MODE_PRIVATE);
String userid = preff.getString("id", null);
Log.e("Student id", "" + userid);
JSONObject json = new JSONObject();
json.put("mocktest_id", idd);
json.put("section_id", 1);
Log.e("JSON Object", json.toString());
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding("UTF-8");
se.setContentType("application/json");
httpRequest.setEntity(se);
HttpResponse httpRes = httpClient.execute(httpRequest);
java.io.InputStream inputStream = httpRes.getEntity()
.getContent();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader reader = new BufferedReader(inputStreamReader);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
inputStream.close();
strServerResponse = sb.toString();
Log.e("Server Response", "" + strServerResponse.toString());
if (strServerResponse != null) {
try {
JSONArray arr1 = new JSONArray(strServerResponse);
JSONObject jsonObj1 = arr1.getJSONObject(0);
samplePaperPojo = new SamplePaperPojo();
for (int i = 0; i < arr1.length(); i++) {
JSONObject jobjj11 = arr1
.getJSONObject(i);
String qq_id = jobjj11.optString("id");
String qq_title = jobjj11.optString("title");
String qq_des = jobjj11.optString("description");
String ans_a = jobjj11.optString("ans_a");
String ans_b = jobjj11.optString("ans_b");
String ans_c = jobjj11.optString("ans_c");
String ans_d = jobjj11.optString("ans_d");
String ans_e = jobjj11.optString("ans_e");
String right_ans = jobjj11.optString("right_ans");
String explanation = jobjj11.optString("explanation");
samplePaperPojo.setSampleQuesId(qq_id);
samplePaperPojo.setSampleQuesTitle(qq_title);
samplePaperPojo.setSampleAns1(ans_a);
samplePaperPojo.setSampleAns2(ans_b);
samplePaperPojo.setSampleAns3(ans_c);
samplePaperPojo.setSampleAns4(ans_d);
samplePaperPojo.setSampleAns5(ans_e);
samplePaperPojo.setSampleRightAns(right_ans);
samplePaperPojo.setSampleQuesDescription(qq_des);
samplePaperPojo.setSampleExplaination(explanation);
sampleTest.add(samplePaperPojo);
al_que_id.add(qq_id);
al_que_title.add(qq_title);
al_ans1.add(ans_a);
al_ans2.add(ans_b);
al_ans3.add(ans_c);
al_ans4.add(ans_d);
al_ans5.add(ans_e);
al_correct.add(right_ans);
al_exp.add(explanation);
al_desc.add(qq_des);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler",
"Couldn't get any data from the url");
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
}
The radio button which I previously selected is not selected when the text is changed after i click on next button. Please help
You should replace:
int selectedId = s_rbgrp.getCheckedRadioButtonId();
selectedRbButton = (RadioButton) findViewById(selectedId);
selectedRbButton.setChecked(false);
with:
s_rbgrp.clearCheck();
Related
I am making android application and I am parsing data from Asp.NET services and When I call service more than 4 times it doesn't return response, I didn't get data from it and after waiting about 10 minutes services working and I can get data from it. I am trying 2 weeks and I didn't solve it. please Help me.. Code is the below
public class SonrakiActivity extends Activity {
Bundle get_data;
int bas_i;
TextView txt, text2;
// Button secretbtn;
String Type;
int TypeID;
int GrpID;
int id;
int sorusayisi = 0;
int cevaplanan = 0;
boolean hata = false;
int akis_soru_sorusayisi = 0;
String last_Type_inmethod;
Bundle data_gonder;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sonraki_olay);
txt = (TextView) findViewById(R.id.textView1);
get_data = getIntent().getExtras();
bas_i = get_data.getInt("data_sonraki_soru_id");
data_gonder = new Bundle();
gonder();
}
public void gonder() {
try {
new Thread(new Runnable() {
#Override
public void run() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://78.186.62.169:8210/AnketServis.asmx/Question");
httppost.setHeader("Content-type", "application/json");
httppost.setHeader("Accept", "application/json");
JSONObject jsonparameter = new JSONObject();
final GlobalClass globalVariable_soru = (GlobalClass) getApplicationContext();
try {
int type_id = Akis_TypeID();
int grp_id = Akis_GrpID();
Log.i("Akis_TypeID()", "" + type_id);
Log.i("Akis_GrpID()", "" + grp_id);
jsonparameter.put("ID", type_id);
jsonparameter.put("GrpID", grp_id);
httppost.setEntity(new StringEntity(jsonparameter
.toString(), "UTF-8"));
Log.i("httppost", "" + httppost);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String responseText = EntityUtils.toString(entity);
Log.i("#responceQuestion_Soru", "" + responseText);
try {
JSONObject returndata = new JSONObject(responseText);
JSONArray jsonMainNode = returndata
.optJSONArray("d");
int lengthJsonArr = jsonMainNode.length();
Log.i("#lengthJsonQuestion_Soru", ""
+ lengthJsonArr);
sorusayisi = lengthJsonArr;
// Quetion_ID
final int question_id = Akis_TypeID();
Log.i("Question_id_Soru", "" + question_id);
for (int i = 0; i < sorusayisi; i++) {
if (i == sorusayisi)
break;
JSONObject jsonChildNode = jsonMainNode
.getJSONObject(i);
try {
final String Text = jsonChildNode
.optString("Text");
globalVariable_soru.setSorumuz(Text);
Log.i("Log_banner_Text", "" + Text);
final int cevap_id = jsonChildNode
.optInt("CevapID");
final List<String> answer = Cevaplar(cevap_id);
Log.i("Answers", "" + answer);
Log.i("Log_banner_ID", "" + cevap_id);
final int cevap_sayisi = jsonChildNode
.optInt("CevapSayisi");
Log.i("Log_cevap_sayisi", "" + cevap_sayisi);
if (i == 0) {
txt.post(new Runnable() {
#Override
public void run() {
try {
final RelativeLayout lm = (RelativeLayout) findViewById(R.id.genelLayout);
txt.setText(Text);
if (cevap_sayisi == 2) {
Button btn1 = new Button(
getApplicationContext());
btn1.setBackgroundResource(R.drawable.stylebutton_iyi);
btn1.setText(answer
.get(0));
btn1.setTextSize(30);
btn1.setTextColor(Color.BLACK);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(
View v) {
// TODO
// Auto-generated
// method stub
Cevapla(1,
question_id);
}
});
Button btn2 = new Button(
getApplicationContext());
btn2.setBackgroundResource(R.drawable.stylebutton_orta);
btn2.setText(answer
.get(1));
btn2.setTextSize(30);
btn2.setTextColor(Color.BLACK);
btn2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(
View v) {
// TODO
// Auto-generated
// method stub
Cevapla(2,
question_id);
}
});
LinearLayout ll = (LinearLayout) findViewById(R.id.buttonlayout);
ll.setOrientation(LinearLayout.VERTICAL);
LayoutParams lp = new LayoutParams(
new LayoutParams(
300,
100));
ll.addView(btn1, lp);
ll.addView(btn2, lp);
lm.addView(ll);
}
if (cevap_sayisi == 3) {
Button btn1 = new Button(
getApplicationContext());
btn1.setText(answer
.get(0));
btn1.setBackgroundResource(R.drawable.stylebutton_iyi);
btn1.setTextSize(30);
btn1.setTextColor(Color.BLACK);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(
View v) {
// TODO
// Auto-generated
// method stub
Cevapla(1,
question_id);
// Intent inm =
// new
// Intent(getApplicationContext(),BitisMesage.class);
// startActivity(inm);
}
});
Button btn2 = new Button(
getApplicationContext());
btn2.setText(answer
.get(1));
btn2.setBackgroundResource(R.drawable.stylebutton_orta);
btn2.setTextSize(30);
btn2.setTextColor(Color.BLACK);
btn2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(
View v) {
// TODO
// Auto-generated
// method stub
Cevapla(2,
question_id);
}
});
Button btn3 = new Button(
getApplicationContext());
btn3.setText(answer
.get(2));
btn3.setBackgroundResource(R.drawable.stylebutton_kotu);
btn3.setTextSize(30);
btn3.setTextColor(Color.BLACK);
btn3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(
View v) {
// TODO
// Auto-generated
// method stub
Cevapla(3,
question_id);
}
});
LinearLayout ll = (LinearLayout) findViewById(R.id.buttonlayout);
ll.setOrientation(LinearLayout.VERTICAL);
LayoutParams lp = new LayoutParams(
new LayoutParams(
300,
100));
ll.addView(btn1, lp);
ll.addView(btn2, lp);
ll.addView(btn3, lp);
lm.addView(ll);
}
if (cevap_sayisi == 4) {
Button btn1 = new Button(
getApplicationContext());
btn1.setText(answer
.get(0));
btn1.setBackgroundResource(R.drawable.stylebutton_iyi);
btn1.setTextSize(30);
btn1.setTextColor(Color.BLACK);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(
View v) {
// TODO
// Auto-generated
// method stub
Cevapla(1,
question_id);
}
});
Button btn2 = new Button(
getApplicationContext());
btn2.setText(answer
.get(1));
btn2.setBackgroundResource(R.drawable.stylebutton_orta);
btn2.setTextSize(30);
btn2.setTextColor(Color.BLACK);
btn2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(
View v) {
// TODO
// Auto-generated
// method stub
Cevapla(2,
question_id);
}
});
Button btn3 = new Button(
getApplicationContext());
btn3.setText(answer
.get(2));
btn3.setBackgroundResource(R.drawable.stylebutton_kotu);
btn3.setTextSize(30);
btn3.setTextColor(Color.BLACK);
btn3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(
View v) {
// TODO
// Auto-generated
// method stub
Cevapla(3,
question_id);
}
});
Button btn4 = new Button(
getApplicationContext());
btn4.setText(answer
.get(3));
btn4.setBackgroundResource(R.drawable.stylebutton_fena);
btn4.setTextSize(30);
btn4.setTextColor(Color.BLACK);
btn4.setOnClickListener(new OnClickListener() {
#Override
public void onClick(
View v) {
// TODO
// Auto-generated
// method stub
Cevapla(4,
question_id);
}
});
LinearLayout ll = (LinearLayout) findViewById(R.id.buttonlayout);
ll.setOrientation(LinearLayout.VERTICAL);
LayoutParams lp = new LayoutParams(
new LayoutParams(
300,
100));
ll.addView(btn1, lp);
ll.addView(btn2, lp);
ll.addView(btn3, lp);
ll.addView(btn4, lp);
lm.addView(ll);
}
if (cevap_sayisi == 5) {
Button btn1 = new Button(
getApplicationContext());
btn1.setText(answer
.get(0));
btn1.setBackgroundResource(R.drawable.stylebutton_iyi);
btn1.setTextSize(30);
btn1.setTextColor(Color.BLACK);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(
View v) {
// TODO
// Auto-generated
// method stub
Cevapla(1,
question_id);
}
});
Button btn2 = new Button(
getApplicationContext());
btn2.setText(answer
.get(1));
btn2.setBackgroundResource(R.drawable.stylebutton_orta);
btn2.setTextSize(30);
btn2.setTextColor(Color.BLACK);
btn2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(
View v) {
// TODO
// Auto-generated
// method stub
Cevapla(2,
question_id);
}
});
Button btn3 = new Button(
getApplicationContext());
btn3.setText(answer
.get(2));
btn3.setBackgroundResource(R.drawable.stylebutton_kotu);
btn3.setTextSize(30);
btn3.setTextColor(Color.BLACK);
btn3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(
View v) {
// TODO
// Auto-generated
// method stub
Cevapla(3,
question_id);
}
});
Button btn4 = new Button(
getApplicationContext());
btn4.setText(answer
.get(3));
btn4.setBackgroundResource(R.drawable.stylebutton_fena);
btn4.setTextSize(30);
btn4.setTextColor(Color.BLACK);
btn4.setOnClickListener(new OnClickListener() {
#Override
public void onClick(
View v) {
// TODO
// Auto-generated
// method stub
Cevapla(4,
question_id);
}
});
Button btn5 = new Button(
getApplicationContext());
btn5.setText(answer
.get(4));
btn5.setBackgroundResource(R.drawable.stylebutton_cokiyi);
btn5.setTextSize(30);
btn5.setTextColor(Color.BLACK);
btn5.setOnClickListener(new OnClickListener() {
#Override
public void onClick(
View v) {
// TODO
// Auto-generated
// method stub
Cevapla(5,
question_id);
}
});
LinearLayout ll = (LinearLayout) findViewById(R.id.buttonlayout);
ll.setOrientation(LinearLayout.VERTICAL);
LayoutParams lp = new LayoutParams(
new LayoutParams(
300,
100));
ll.addView(btn1, lp);
ll.addView(btn2, lp);
ll.addView(btn3, lp);
ll.addView(btn4, lp);
ll.addView(btn5, lp);
lm.addView(ll);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
} catch (Exception e) {
Onceki_soru();
}
}
} catch (JSONException e) {
Onceki_soru();
}
} catch (Exception e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"İnternet ayarlarınızı kontrol ediniz",
Toast.LENGTH_SHORT).show();
}
});
Onceki_soru();
e.printStackTrace();
}
}
}).start();
}
catch (Exception e) {
e.printStackTrace();
}
}
private List<String> Cevaplar(int cevabim_id) {
List<String> getCevap = new ArrayList<String>();
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://78.186.62.169:8210/AnketServis.asmx/Answers");
httppost.setHeader("Content-type", "application/json");
httppost.setHeader("Accept", "application/json");
JSONObject jsonparameter = new JSONObject();
jsonparameter.put("ID", cevabim_id);
httppost.setEntity(new StringEntity(jsonparameter.toString(),
"UTF-8"));
Log.i("httppost", "" + httppost);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String responseText = EntityUtils.toString(entity);
Log.i("#responceAnswers", "" + responseText);
try {
JSONObject returndata = new JSONObject(responseText);
JSONArray jsonMainNode = returndata.optJSONArray("d");
int lengthJsonArr = jsonMainNode.length();
Log.i("#lengthJsonAnswer", "" + lengthJsonArr);
sorusayisi = lengthJsonArr;
for (int i = 0; i < sorusayisi; i++) {
if (i == sorusayisi)
break;
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
try {
final String value1 = jsonChildNode.optString("Value1");
final String value2 = jsonChildNode.optString("Value2");
final String value3 = jsonChildNode.optString("Value3");
final String value4 = jsonChildNode.optString("Value4");
final String value5 = jsonChildNode.optString("Value5");
getCevap.add(value1);
getCevap.add(value2);
getCevap.add(value3);
getCevap.add(value4);
getCevap.add(value5);
} catch (Exception e) {
// TODO: handle exception
}
}
} catch (Exception e) {
// TODO: handle exception
}
} catch (Exception e) {
// TODO: handle exception
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"İnternet ayarlarınızı kontrol ediniz",
Toast.LENGTH_SHORT).show();
}
});
}
return getCevap;
// TODO Auto-generated method stub
}
private int Akis_TypeID() {
try {
JSONObject returndata = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://78.186.62.169:8210/AnketServis.asmx/Akis");
httppost.setHeader("Content-type", "application/json");
JSONObject jsonparameter = new JSONObject();
final TextView textView1 = (TextView) findViewById(R.id.txt1);
try {
httppost.setEntity(new StringEntity(jsonparameter.toString(),
"UTF-8"));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity);
Log.i("#akis_responseString", "" + responseString);
try {
returndata = new JSONObject(responseString);
JSONArray jsonMainNode = returndata.optJSONArray("d");
int lengthJsonArr = jsonMainNode.length();
akis_soru_sorusayisi = lengthJsonArr;
Log.i("Log_jsonlength", "" + akis_soru_sorusayisi);
for (; bas_i < akis_soru_sorusayisi; bas_i++) {
JSONObject jsonChildNode = jsonMainNode
.getJSONObject(bas_i);
try {
Type = jsonChildNode.optString("Type").toString();
Log.i("#Log_Type", "" + Type);
if (Type.equals("Soru")) {
id = jsonChildNode.optInt("ID");
Log.i("#Log_id", "" + id);
GrpID = jsonChildNode.optInt("GrpID");
Log.i("#Log_GrpID", "" + GrpID);
TypeID = jsonChildNode.optInt("TypeID");
Log.i("#Log_TypeID", "" + TypeID);
break;
}
} catch (Exception e) {
Log.i("ErrorMessage", "" + e.getMessage());
}
}
} catch (JSONException e) {
}
} catch (Exception e) {
}
} catch (Exception e) {
e.printStackTrace();
}
return TypeID;
}
private void Cevapla(int i, int question_id) {
// TODO Auto-generated method stub
try {
Thread.sleep(1500);
Oyla(i, question_id);
// SonrakiSoruKontrol();
getType();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
private void getType() {
// TODO Auto-generated method stub
try {
new Thread(new Runnable() {
#Override
public void run() {
JSONObject returndata = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://78.186.62.169:8210/AnketServis.asmx/Akis");
httppost.setHeader("Content-type", "application/json");
JSONObject jsonparameter = new JSONObject();
try {
httppost.setEntity(new StringEntity(jsonparameter
.toString(), "UTF-8"));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity);
Log.i("#akis_responseString_Soru_Akiss", ""
+ responseString);
try {
int inc_bas_i = bas_i + 1;
Log.i("inc_sonraki_soru_id", "" + inc_bas_i);
returndata = new JSONObject(responseString);
JSONArray jsonMainNode = returndata
.optJSONArray("d");
int lengthJsonArr = jsonMainNode.length();
int sorusayisi = lengthJsonArr;
Log.i("Log_jsonlength_Soru_Akis", "" + sorusayisi);
for (; inc_bas_i < sorusayisi; inc_bas_i++) {
JSONObject jsonChildNode = jsonMainNode
.getJSONObject(inc_bas_i);
try {
last_Type_inmethod = jsonChildNode
.optString("Type").toString();
Log.i("#Log_Type_Soru_Akis", "" + Type);
if (last_Type_inmethod.equals("Soru")) {
Intent pass_other_activty = new Intent(
getApplicationContext(),
SonrakiActivity.class);
data_gonder.putInt(
"data_sonraki_soru_id",
inc_bas_i);
pass_other_activty
.putExtras(data_gonder);
startActivity(pass_other_activty);
break;
}
if (last_Type_inmethod.equals("Bitis")) {
Intent pass_other_activty = new Intent(
getApplicationContext(),
BitisMesage.class);
startActivity(pass_other_activty);
break;
}
if (last_Type_inmethod
.equals("Kullanıcı Girisi")) {
Intent pass_other_activty = new Intent(
getApplicationContext(),
KullaniciGirisi1.class);
data_gonder.putInt(
"data_sonraki_soru_id",
inc_bas_i);
pass_other_activty
.putExtras(data_gonder);
startActivity(pass_other_activty);
//
break;
}
} catch (Exception e) {
Log.i("ErrorMessage", "" + e.getMessage());
}
}
} catch (JSONException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(
getApplicationContext(),
"İnternet ayarlarınızı kontrol ediniz",
Toast.LENGTH_SHORT).show();
}
});
}
} catch (Exception e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"İnternet ayarlarınızı kontrol ediniz",
Toast.LENGTH_SHORT).show();
}
});
}
}
}).start();
} catch (Exception e) {
e.printStackTrace();
}
}
private void Oyla(final int cevabim_id, final int questionn_id) {
// TODO Auto-generated method stub
try {
new Thread(new Runnable() {
#Override
public void run() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://78.186.62.169:8210/AnketServis.asmx/Oyla");
httppost.setHeader("Content-type", "application/json");
httppost.setHeader("Accept", "application/json");
JSONObject jsonparameter = new JSONObject();
try {
Log.i("question_iddd", "" + questionn_id);
Log.i("question_iddd", "" + cevabim_id);
jsonparameter.put("ID", questionn_id);
jsonparameter.put("CevapID", cevabim_id);
try {
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String deviceID = telephonyManager.getDeviceId();
jsonparameter.put("IMEI", deviceID);
} catch (Exception e) {
jsonparameter.put("IMEI", "IMEI Yok");
}
httppost.setEntity(new StringEntity(jsonparameter
.toString(), "UTF-8"));
httpclient.execute(httppost);
} catch (Exception e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"İnternet Ayarlarınızı Kontrol Ediniz",
Toast.LENGTH_SHORT).show();
}
});
e.printStackTrace();
}
}
}).start();
} catch (Exception e) {
e.printStackTrace();
}
}
private int Akis_GrpID() {
try {
JSONObject returndata = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://78.186.62.169:8210/AnketServis.asmx/Akis");
httppost.setHeader("Content-type", "application/json");
JSONObject jsonparameter = new JSONObject();
final TextView textView1 = (TextView) findViewById(R.id.txt1);
try {
// jsonparameter.put("AnketID", "3");
httppost.setEntity(new StringEntity(jsonparameter.toString(),
"UTF-8"));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity);
Log.i("#akis_responseString", "" + responseString);
try {
returndata = new JSONObject(responseString);
JSONArray jsonMainNode = returndata.optJSONArray("d");
int lengthJsonArr = jsonMainNode.length();
sorusayisi = lengthJsonArr;
Log.i("Log_jsonlength", "" + sorusayisi);
for (; bas_i < sorusayisi; bas_i++) {
// if (i == sorusayisi)
// break;
JSONObject jsonChildNode = jsonMainNode
.getJSONObject(bas_i);
try {
Type = jsonChildNode.optString("Type").toString();
Log.i("#Log_Type", "" + Type);
if (Type.equals("Soru")) {
id = jsonChildNode.optInt("ID");
Log.i("#Log_id", "" + id);
GrpID = jsonChildNode.optInt("GrpID");
Log.i("#Log_GrpID", "" + GrpID);
TypeID = jsonChildNode.optInt("TypeID");
Log.i("#Log_TypeID", "" + TypeID);
break;
}
} catch (Exception e) {
Log.i("ErrorMessage", "" + e.getMessage());
}
}
} catch (JSONException e) {
}
} catch (Exception e) {
}
} catch (Exception e) {
e.printStackTrace();
}
return GrpID;
}
public void Onceki_soru() {
try {
final GlobalClass globalVariable = (GlobalClass) getApplicationContext();
final TextView txt_soru = (TextView) findViewById(R.id.textView1);
// final TextView textViewhdn1 = (TextView)
// findViewById(R.id.txthdn1);
txt_soru.post(new Runnable() {
#Override
public void run() {
try {
txt_soru.setText(globalVariable.getSorumuz());
} catch (Exception e) {
e.printStackTrace();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
my listview repeat data some time which click on buttons fastly what do i do please help me see this images http://imgur.com/ed5uDtp after some time is show like this http://imgur.com/jAt4yn7
is show correctly data on listview but some time when click fastly buttons is load duplicate data how i will fixed this? plaa help me
public class thirdstep extends Activity implements View.OnClickListener {
int count = 0;
String id;
String title;
String tmpString, finaldate;
String valll;
ProgressBar prgLoading;
TextView txtAlert;
int IOConnect = 0;
String mVal9;
Button e01;
Button e02;
Button e03;
Button e04;
Button e05;
String SelectMenuAPI;
String url;
String URL;
String URL2, URL3, URL4;
String menu_title;
JSONArray school;
ListView listCategory;
String status;
String School_ID;
String Menu_ID;
String School_name;
String Meal_groupid;
String _response;
String _response2;
String CategoryAPI;
String SelectMenuAPI2;
TextView menu_nametxt;
thirdstepAdapter cla;
static ArrayList<Long> Category_ID = new ArrayList<Long>();
static ArrayList<String> school_name = new ArrayList<String>();
static ArrayList<String> menu_name = new ArrayList<String>();
static ArrayList<String> dish_name = new ArrayList<String>();
static ArrayList<String> dish_ID = new ArrayList<String>();
static ArrayList<String> day = new ArrayList<String>();
static ArrayList<Long> Vacation_ID = new ArrayList<Long>();
static ArrayList<String> Vacation_name = new ArrayList<String>();
static ArrayList<String> Vacation_Date = new ArrayList<String>();
String mydate;
String mode;
String s2;
ArrayList<String> myList,myList2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_list2);
listCategory = (ListView) findViewById(R.id.thirdscreenlist);
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
txtAlert = (TextView) findViewById(R.id.txtAlert);
e01 = (Button) findViewById(R.id.e01);
e02 = (Button) findViewById(R.id.e02);
e03 = (Button) findViewById(R.id.e03);
e04 = (Button) findViewById(R.id.e04);
e05 = (Button) findViewById(R.id.e05);
e01.setOnClickListener(this);
e02.setOnClickListener(this);
e03.setOnClickListener(this);
e04.setOnClickListener(this);
e05.setOnClickListener(this);
cla = new thirdstepAdapter(thirdstep.this);
listCategory.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
Intent intent = new Intent(thirdstep.this, fifthscreen.class);
startActivity(intent);
}
});
new getDataTask().execute();
}
void clearData() {
Category_ID.clear();
school_name.clear();
menu_name.clear();
dish_name.clear();
dish_ID.clear();
day.clear();
Vacation_ID.clear();
Vacation_name.clear();
Vacation_Date.clear();
}
public class getDataTask extends AsyncTask<Void, Void, Void> {
getDataTask() {
if (!prgLoading.isShown()) {
prgLoading.setVisibility(0);
txtAlert.setVisibility(8);
}
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
parseJSONData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
prgLoading.setVisibility(8);
if ((Category_ID.size() > 0) || IOConnect == 0) {
listCategory.setAdapter(cla);
cla.notifyDataSetChanged() ;
listCategory.invalidateViews();
} else {
txtAlert.setVisibility(0);
menu_nametxt.setText("");
listCategory.setVisibility(View.GONE);
}
}
}
public void parseJSONData() {
clearData();
SelectMenuAPI="";
SelectMenuAPI = Utils.Schoolmenu +Menu_ID+"&sid="+School_ID+"&lid=" +
SchoolLevelId+"&mealid="+Meal_groupid;
URL = SelectMenuAPI;
URL2 = URL.replace(" ", "%20");
try {
Log.i("url",""+URL2);
HttpClient client = new DefaultHttpClient();
HttpConnectionParams
.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(URL2);
HttpResponse response = client.execute(request);
HttpEntity resEntity = response.getEntity();
_response=EntityUtils.toString(resEntity);
JSONObject json5 = new JSONObject(_response);
status = json5.getString("status");
if (status.equals("1")) {
JSONArray school5 = json5.getJSONArray("data");
}
}
else {
}
SelectMenuAPI2="";
SelectMenuAPI2 = Utils.SchoolVacation+mVal9;
// clearData();
URL3 = SelectMenuAPI2;
URL4 = URL3.replace(" ", "%20");
Log.i("url",""+URL4);
JSONObject json2 = new JSONObject(_response);
status = json2.getString("status");
if (status.equals("1")) {
if (Vacation_Date.contains(mydate)) {
message = "holiday";
JSONObject json4 = new JSONObject(str2);
status = json4.getString("status");
if (status.equals("1")) {
school = json4.getJSONArray("data");
for (int k = 0; k < school.length(); k++) {
JSONObject jb = (JSONObject) school .getJSONObject(k);
Vacation_ID.add((long) k);
String[] mVal = new String[school.length()];
if(school.getJSONObject(k).getString("date").equals(mydate))
{
mVal[k] = school.getJSONObject(k).getString("title");
mVal3 = mVal[k];
}
}
}
} else {
JSONArray school = json2.getJSONArray("data");
for (int i = 0; i < school.length(); i++) {
JSONObject object = school.getJSONObject(i);
if (object.getString("Schedule").equals("weekly")) {
if (object.getString("day").equals(Todayday)) {
Category_ID.add((long) i);
school_name
.add(object.getString("school_name"));
dish_ID.add(object.getString("dish_id"));
dish_name.add(object.getString("dish_name"));
menu_name.add(object.getString("menu_title"));
day.add(object.getString("day"));
count = count + 1;
String[] mVal = new String[school.length()];
for (int k = 0; k < school.length(); k++) {
mVal[k] = school.getJSONObject(k).getString("menu_title");
message = "weekly";
mVal2 = mVal[0];
}
}
if(dish_name != null &&
!dish_name.isEmpty())
{
message = "weekly";
}
else {
message = "error";
}
}
else {
message = "error";
}
}
}
}
else {
message = "error";
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
IOConnect = 1;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.e01:
// do stuff;
listCategory.setVisibility(View.GONE);
new getDataTask().execute();
break;
case R.id.e02:
// do stuff;
listCategory.setVisibility(View.GONE);
new getDataTask().execute();
break;
case R.id.e03:
// do stuff;
listCategory.setVisibility(View.GONE);
new getDataTask().execute();
break;
case R.id.e04:
// do stuff;
listCategory.setVisibility(View.GONE);
new getDataTask().execute();
break;
case R.id.e05:
listCategory.setVisibility(View.GONE);
// do stuff;
new getDataTask().execute();
break;
}
}
}
You are calling asynctask twice and that is making all parts twice, I mean you are cleaning twice before filling and fill arrays twice. You should control your async task for do not execute before last one finished.
1-Create a boolean value
2-Put condition on onClicks:
if(yourBoolean){
new getDataTask().execute();}
3- in your asyncTask's onPreExecute make yourBoolean=false and onPostExecute make yourBoolean=true again.
Try this..
Just remove the below line and try it..
listCategory.invalidateViews();
because
ListView.invalidateViews() is used to tell the ListView to invalidate all its child item views (redraw them). Note that there not need to be an equal number of views than items. That's because a ListView recycles its item views and moves them around the screen in a smart way while you scroll.
My app is not working on android version 4.1 gives exception like android.os.NetworkOnMainThreadException
i have search on stackoverflow advice me to do network thread in background AsyncTask so before use backgroundtask,
My screen look like this http://imgur.com/PlhS03i show multiple rows in nutrition's and ingredient tags after using backgroundtask my screen look like this http://imgur.com/zUvxNpy show only single row in ingredients and nutrition tags
before background task code is this see below
public class fifthscreen extends Activity {
String num = null;
TextView ingredient;
long Menu_ID;
String dish_name;
String status;
HorizontalListView listview;
CategoryListAdapter3 cla;
String DescriptionAPI;
TextView txt1, txt2, txt3;
ImageView img1;
String URL, URL2;
String SelectMenuAPI;
static ArrayList<Long> Category_ID = new ArrayList<Long>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();
public static String allergen2;
private AQuery androidAQuery;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fifthscreen);
ingredient = (TextView) findViewById(R.id.ingredient);
img1 = (ImageView) findViewById(R.id.test_button_image);
txt1 = (TextView) findViewById(R.id.menuname);
txt3 = (TextView) findViewById(R.id.description);
Intent iGet = getIntent();
ImageView options = (ImageView) findViewById(R.id.options5);
androidAQuery = new AQuery(this);
options.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent iMenuList = new Intent(fifthscreen.this,
LinkButtons.class);
startActivity(iMenuList);
}
});
dish_name = iGet.getStringExtra("dish_name");
listview = (HorizontalListView) this.findViewById(R.id.listview2);
cla = new CategoryListAdapter3(fifthscreen.this);
listview.setAdapter(cla);
parseJSONData();
}
void clearData() {
Category_ID.clear();
Category_name.clear();
Category_image.clear();
}
public void parseJSONData() {
SelectMenuAPI = Utils.dishdescription + dish_name;
clearData();
URL = SelectMenuAPI;
URL2 = URL.replace(" ", "%20");
try {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams
.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(URL2);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(
atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null) {
str += line;
}
JSONObject json2 = new JSONObject(str);
status = json2.getString("status");
if (status.equals("1")) {
JSONArray school2 = json2.getJSONArray("data");
for (int i = 0; i < school2.length(); i++) {
String name = school2.getJSONObject(0).getString("name");
txt1.setText(name);
String description = school2.getJSONObject(0).getString(
"description");
txt3.setText(description);
String url1 = school2.getJSONObject(0).getString("image");
androidAQuery.id(img1).image(url1, false, false);
}
JSONObject school3 = json2.getJSONObject("dish_nutrition");
final TableLayout table = (TableLayout) findViewById(R.id.table2);
for (int j = 0; j < school3.length(); j++) {
String s = String.valueOf(j + 1);
final View row = createRow(school3.getJSONObject(s));
table.addView(row);
}
JSONArray school4 = json2.getJSONArray("dish_allergen");
//
for (int i = 0; i < school4.length(); i++) {
JSONObject object = school4.getJSONObject(i);
Category_ID.add((long) i);
Category_name.add(object.getString("name"));
Category_image.add(object.getString("image"));
listview.setAdapter(cla);
}
final LinearLayout table3 = (LinearLayout) findViewById(R.id.table3);
JSONArray school5 = json2.getJSONArray("dish_ingredient");
for (int i = 0; i < school5.length(); i++) {
final View row2 = createRow2(school5.getJSONObject(i));
table3.addView(row2);
}
}
else {
JSONArray school2 = json2.getJSONArray("data");
for (int i = 0; i < school2.length(); i++) {
JSONObject object = school2.getJSONObject(i);
Category_ID.add((long) i);
Category_name.add(object.getString("name"));
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
// IOConnect = 1;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public View createRow(JSONObject item) throws JSONException {
View row = getLayoutInflater().inflate(R.layout.rows, null);
((TextView) row.findViewById(R.id.localTime)).setText(item
.getString("qty"));
((TextView) row.findViewById(R.id.apprentTemp)).setText(item
.getString("name"));
return row;
}
public View createRow2(JSONObject item) throws JSONException {
View row2 = getLayoutInflater().inflate(R.layout.row2, null);
((TextView) row2.findViewById(R.id.name)).setText(item
.getString("name"));
((TextView) row2.findViewById(R.id.subingredients)).setText(item
.getString("sub_ingredients"));
return row2;
}
}
After using AsyncTask see this code below
public class fifthscreen extends Activity {
String num = null;
TextView ingredient;
long Menu_ID;
String dish_name;
String status;
HorizontalListView listview;
CategoryListAdapter3 cla;
String DescriptionAPI;
TextView txt1, txt2, txt3;
ImageView img1;
String URL, URL2;
String SelectMenuAPI;
String description;
int IOConnect = 0;
String name;
String url1;
TableLayout table;
LinearLayout table3;
View row;
View row2;
static ArrayList<Long> Category_ID = new ArrayList<Long>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();
public static String allergen2;
private AQuery androidAQuery;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fifthscreen);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
ingredient = (TextView) findViewById(R.id.ingredient);
img1 = (ImageView) findViewById(R.id.test_button_image);
txt1 = (TextView) findViewById(R.id.menuname);
// txt2 = (TextView) findViewById(R.id.test_button_text1);
txt3 = (TextView) findViewById(R.id.description);
table = (TableLayout) findViewById(R.id.table2);
table3 = (LinearLayout) findViewById(R.id.table3);
Intent iGet = getIntent();
ImageView options = (ImageView) findViewById(R.id.options5);
androidAQuery = new AQuery(this);
options.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent iMenuList = new Intent(fifthscreen.this,
LinkButtons.class);
startActivity(iMenuList);
}
});
dish_name = iGet.getStringExtra("dish_name");
listview = (HorizontalListView) this.findViewById(R.id.listview2);
cla = new CategoryListAdapter3(fifthscreen.this);
new getDataTask().execute();
// listview.setAdapter(cla);
ImageView btnback = (ImageView) findViewById(R.id.btnback);
btnback.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
parseJSONData();
}
void clearData() {
Category_ID.clear();
Category_name.clear();
Category_image.clear();
}
public class getDataTask extends AsyncTask<Void, Void, Void> {
getDataTask() {
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
parseJSONData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
txt1.setText(name);
txt3.setText(description);
androidAQuery.id(img1).image(url1, false, false);
table.addView(row);
table3.addView(row2);
listview.setAdapter(cla);
}
}
public void parseJSONData() {
SelectMenuAPI = Utils.dishdescription + dish_name;
clearData();
URL = SelectMenuAPI;
URL2 = URL.replace(" ", "%20");
try {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams
.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(URL2);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(
atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null) {
str += line;
}
JSONObject json2 = new JSONObject(str);
status = json2.getString("status");
if (status.equals("1")) {
JSONArray school2 = json2.getJSONArray("data");
for (int i = 0; i < school2.length(); i++) {
name = school2.getJSONObject(0).getString("name");
description = school2.getJSONObject(0).getString(
"description");
url1 = school2.getJSONObject(0).getString("image");
}
JSONObject school3 = json2.getJSONObject("dish_nutrition");
for (int j = 0; j < school3.length(); j++) {
String s = String.valueOf(j + 1);
row = createRow(school3.getJSONObject(s));
}
JSONArray school4 = json2.getJSONArray("dish_allergen");
//
for (int i = 0; i < school4.length(); i++) {
JSONObject object = school4.getJSONObject(i);
Category_ID.add((long) i);
Category_name.add(object.getString("name"));
Category_image.add(object.getString("image"));
}
JSONArray school5 = json2.getJSONArray("dish_ingredient");
for (int i = 0; i < school5.length(); i++) {
row2 = createRow2(school5.getJSONObject(i));
}
}
else {
JSONArray school2 = json2.getJSONArray("data");
for (int i = 0; i < school2.length(); i++) {
JSONObject object = school2.getJSONObject(i);
Category_ID.add((long) i);
Category_name.add(object.getString("name"));
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
// IOConnect = 1;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public View createRow(JSONObject item) throws JSONException {
View row = getLayoutInflater().inflate(R.layout.rows, null);
((TextView) row.findViewById(R.id.localTime)).setText(item
.getString("qty"));
((TextView) row.findViewById(R.id.apprentTemp)).setText(item
.getString("name"));
return row;
}
public View createRow2(JSONObject item) throws JSONException {
View row2 = getLayoutInflater().inflate(R.layout.row2, null);
((TextView) row2.findViewById(R.id.name)).setText(item
.getString("name"));
((TextView) row2.findViewById(R.id.subingredients)).setText(item
.getString("sub_ingredients"));
return row2;
}
}
Please Help
Thanks in Advance...:)
Use the Handler object from your MainActivity and post a runnable. To use it from the backgrund you need to make the object a static that you can call outside of your MainActivity or you can create a static instance of the Activity to access it.
Inside the Activity
private static Handler handler;
handler = new Handler();
handler().post(new Runnable() {
public void run() {
//ui stuff here :)
}
});
public static Handler getHandler() {
return handler;
}
Outside the Activity
MainActivity.getHandler().post(new Runnable() {
public void run() {
//ui stuff here :)
}
});
You can use **runOnUiThread()** like this:
try {
// code runs in a thread
runOnUiThread(new Runnable() {
#Override
public void run() {
// YOUR CODE
}
});
} catch (final Exception ex) {
Log.i("---","Exception in thread");
}
You need to create AsyncTask class and use it
Read here more: AsyncTask
Example would look like this:
private class UploadTask extends AsyncTask<Void, Void, Void>
{
private String in;
public UploadTask(String input)
{
this.in = input;
}
#Override
protected void onPreExecute()
{
//start showing progress here
}
#Override
protected Void doInBackground(Void... params)
{
//do your work
return null;
}
#Override
protected void onPostExecute(Void result)
{
//stop showing progress here
}
}
And start task like this:
UploadTask ut= new UploadTask(input);
ut.execute();
you are handling ui in these methods
public View createRow(JSONObject item) throws JSONException {
View row = getLayoutInflater().inflate(R.layout.rows, null);
((TextView) row.findViewById(R.id.localTime)).setText(item
.getString("qty"));
((TextView) row.findViewById(R.id.apprentTemp)).setText(item
.getString("name"));
return row;
}
public View createRow2(JSONObject item) throws JSONException {
View row2 = getLayoutInflater().inflate(R.layout.row2, null);
((TextView) row2.findViewById(R.id.name)).setText(item
.getString("name"));
((TextView) row2.findViewById(R.id.subingredients)).setText(item
.getString("sub_ingredients"));
return row2;
}
which are called in background thread
if possible do it in onPostExecute or you can use runOnUiThread and Handler.
below is my code there is a problem some where in getDataTask if i remove this class is work fine and print Toast message Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); but what is problem in my getDataTask im parsing below json file problem is some where in doinbackground method help me please
{"status":0,"message":"No such school found"}
public class thirdstep extends Activity {
ListView listCategory;
String status;
String message;
String MenuSelect;
ProgressBar prgLoading;
long Cat_ID;
String Cat_name;
String CategoryAPI;
int IOConnect = 0;
TextView txtAlert;
thirdstepAdapter cla;
static ArrayList<String> Category_ID = new ArrayList<String>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_list2);
ImageButton btnback = (ImageButton) findViewById(R.id.btnback);
listCategory = (ListView) findViewById(R.id.listCategory2);
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
txtAlert = (TextView) findViewById(R.id.txtAlert);
cla = new thirdstepAdapter(thirdstep.this);
new getDataTask().execute();
listCategory.setAdapter(cla);
btnback.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
});
Intent iGet = getIntent();
Cat_ID = iGet.getLongExtra("category_id", 0);
Cat_name = iGet.getStringExtra("category_name");
Toast.makeText(this, Cat_ID + Cat_name, Toast.LENGTH_SHORT).show();
MenuSelect = Utils.MenuSelect;
listCategory.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
Intent iMenuList = new Intent(thirdstep.this, fourthscreen.class);
iMenuList.putExtra("Cat_ID",Cat_ID);
iMenuList.putExtra("Menuitem", Category_ID.get(position));
startActivity(iMenuList);
}
});
}
void clearData() {
Category_ID.clear();
Category_name.clear();
Category_image.clear();
}
public class getDataTask extends AsyncTask<Void, Void, Void>{
getDataTask(){
if(!prgLoading.isShown()){
prgLoading.setVisibility(0);
txtAlert.setVisibility(8);
}
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
parseJSONData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
prgLoading.setVisibility(8);
if((Category_ID.size() > 0) || IOConnect == 0){
listCategory.setVisibility(0);
listCategory.setAdapter(cla);
}else{
txtAlert.setVisibility(0);
}
}
}
public void parseJSONData() {
CategoryAPI = Utils.MenuList + Cat_ID;
clearData();
try {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams
.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(CategoryAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(
atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null) {
str += line;
}
JSONObject json = new JSONObject(str);
JSONObject json2 = new JSONObject(str);
status = json2.getString("status");
message = json2.getString("message");
if (status.equals("1")) {
JSONObject data = json.getJSONObject("data");
JSONArray school = data.getJSONArray("menu_groups");
for (int i = 0; i < school.length(); i++) {
JSONObject object = school.getJSONObject(i);
Category_ID.add(object.getString("id"));
Category_name.add(object.getString("title"));
Category_image.add(object.getString("image"));
}
}
else
{
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
IOConnect = 1;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You are calling parseJSONData() in doInbackground and you have this
Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); // in parseJSONData()
you cannot update ui from doInbackground. You need to update ui on the ui thread. Return result in doInbackground. In onPostExecute update ui.
I created two activities: the first one contains details of a job offer, and the next one is to postulate to this job. after applying for the job, an alertdialog appears to confirm the success of the operation. However, this alertdialog appears in the view of the job details without values !
How can I manage this??
This is activity 1:
private static final String MY_PREFERENCES = "mespreferences";
TextView txt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail_offre);
ToggleButton precedent = (ToggleButton)findViewById(R.id.btn_preced);
precedent.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent preced = new Intent(DetailsOffre.this, Offres.class);
startActivity(preced);
}
});
Button postuler = (Button)findViewById(R.id.postuler);
postuler.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
TextView id_offre = (TextView) findViewById(R.id.tv_ID_Off1);
SharedPreferences settings = getSharedPreferences(MY_PREFERENCES, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("idoffre", id_offre.getText().toString());
editor.commit();
Intent intent_postul = new Intent(DetailsOffre.this, Candidature.class);
startActivity(intent_postul);
}
});
Button enregistrer = (Button)findViewById(R.id.enregistrer);
enregistrer.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
TextView id_offre = (TextView) findViewById(R.id.tv_ID_Off1);
String idOf = id_offre.getText().toString();
Intent intent_enregist = new Intent(DetailsOffre.this, EnregistrerOffre.class);
intent_enregist.putExtra("idoffre",idOf );
startActivity(intent_enregist);
}
});
LinearLayout rootLayout = new LinearLayout(getApplicationContext());
txt = new TextView(getApplicationContext());
rootLayout.addView(txt);
txt.setText("Connexion...");
txt.setText(getServerData(URL2));
}
public static final String URL2 = "http://10.0.2.2/mesRequetes/detail_offr.php";
private String getServerData(String returnString) {
InputStream is = null;
String result = null;
Intent intent3 = getIntent();
String id = intent3.getExtras().getString("idoffre");
ArrayList<NameValuePair> postID = new ArrayList<NameValuePair>();
postID.add(new BasicNameValuePair("idoffre", id));
// Envoie de la commande http
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL2);
httppost.setEntity(new UrlEncodedFormEntity(postID));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection " + e.toString());
}
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
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());
}
try{
JSONArray jArray = new JSONArray(result);
JSONObject detail=null;
for(int i=0;i<jArray.length();i++){
detail = jArray.getJSONObject(i);
TextView numoffre = (TextView) findViewById(R.id.tv_ID_Off1);
numoffre.setText(detail.getString("idoffre"));
TextView nom_societe = (TextView) findViewById(R.id.tv_societe1);
nom_societe.setText(detail.getString("first_name"));
TextView poste = (TextView) findViewById(R.id.TV_post1);
poste.setText(detail.getString("poste"));
TextView ville = (TextView) findViewById(R.id.tv_vill);
ville.setText(detail.getString("ville"));
TextView details = (TextView) findViewById(R.id.tv_detail);
details.setText(detail.getString("details"));
TextView d_crea = (TextView) findViewById(R.id.tv_datecrea);
d_crea.setText(format_d(detail.getString("created_at")));
TextView idste = (TextView) findViewById(R.id.TV_idsociete1);
idste.setText(detail.getString("idsoc"));
SharedPreferences settings = getSharedPreferences(MY_PREFERENCES, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("idsoc", idste.getText().toString());
editor.commit();
Log.i("log_tag","Numero de l'offre:"+detail.getInt("idoffre")+
"poste proposé:"+detail.getString("poste")+
"ville:"+detail.getString("ville")+
"details:"+detail.getString("details")+
"date de creation:"+detail.getString("created_at")+
"identifiant de la société:"+detail.getString("idsoc")+
"nom de la société:"+detail.getString("first_name")
);
// Résultats de la requête
returnString += "" + jArray.getJSONObject(i);
};
}catch(JSONException e){
Log.e("log_tag", "Error parsing data " + e.toString());
}
return returnString;
}
public static StringBuilder format_d(final String s) {
String aaaa = s.substring(0, 4);
String mm = s.substring(5, 7);
String dd = s.substring(8, 10);
String heure = s.substring (11);
return new StringBuilder(dd)
.append("/")
.append(mm)
.append("/")
.append(aaaa)
.append(" à ")
.append(heure);
}
Activity2:
private static final String MY_PREFERENCES = "mespreferences";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail_offre);
SharedPreferences sharedPreferences = getSharedPreferences(MY_PREFERENCES, 0);
String userId = sharedPreferences.getString("id", "");
String idoffr = sharedPreferences.getString("idoffre", "");
Intent intent_postul = getIntent();
ArrayList<NameValuePair> postCandidature= new ArrayList<NameValuePair>();
postCandidature.add(new BasicNameValuePair("idoffre", idoffr));
postCandidature.add(new BasicNameValuePair("id", userId));
this.sendData(postCandidature);
}
private void sendData(ArrayList<NameValuePair> postCandidature) {
// TODO Auto-generated method stub
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/mesRequetes/candidature.php");
httppost.setEntity(new UrlEncodedFormEntity(postCandidature));
HttpResponse response = httpclient.execute(httppost);
Log.i("postData", response.getStatusLine().toString());
AlertDialog.Builder cand = new AlertDialog.Builder(Candidature.this);
cand.setIcon(R.drawable.succes);
cand.setTitle("Succès");
cand.setMessage("Votre candidature a bien été transmise");
cand.setPositiveButton("OK", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Intent offr = new Intent (Candidature.this, Offres.class);
startActivity(offr);
}});
cand.show();
}catch(Exception e){
Log.e("log_tag", "Error in http connection " + e.toString());
}
}
Use the following for Alert Dialog. Give more details to understand your requirements.
public void Alert(String text, String title)
{
AlertDialog dialog=new AlertDialog.Builder(context).create();
dialog.setTitle(title);
dialog.setMessage(text);
if(!title.equals("") && !text.equals(""))
{
dialog.setButton("OK",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
//
}
});
dialog.setButton2("Cancel",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
//
}
});
}
dialog.show();
}