I am making a quiz application, in which I have a quiz activity where I am doing the following work.
- Get data from server (Now getting all data using Asynctask).
- Set data to my UI (which is going well).
- get user input and check the marked answer.
- Refresh activity after every 20 seconds with new question (for which i am using handler)
I am having all the data, and now want that my UI refreshes with new question from data I have. how can I do that?
Any help appreciated.
follow is the code I am using.
public class Quiz extends ActionBarActivity {
private SessionManager session;
Intent intent;
String categoryid,userid,uri="http://demopurpose.com/Quiz/API/";
JSONArray jArray;
InputStream is;
JSONObject json_data;
String[] data;
int len,countdown=20,lastquestion=0;
private Handler mHandler,handler;
protected static final long TIME_DELAY = 20000;
TextView txtcountdown,txtquestion,txtanswer;
Button btn1,btn2,btn3,btn4;
String opt1,opt2,opt3,opt4,question,answer ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
this.session = new SessionManager(this);
mHandler = new Handler();
handler = new Handler();
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
txtcountdown =(TextView)findViewById(R.id.txtcountdown);
txtquestion = (TextView)findViewById(R.id.txtquestion);
btn1 =(Button)findViewById(R.id.btn1);
btn2 =(Button)findViewById(R.id.btn2);
btn3 =(Button)findViewById(R.id.btn3);
btn4 =(Button)findViewById(R.id.btn4);
userid= session.getuserid();
intent =getIntent();
categoryid = intent.getExtras().getString("categoryid");
data = new String[3];
data[0] = userid;
data[1] = categoryid;
data[2] = Integer.toString(lastquestion);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
opt1 = btn1.getText().toString();
opt2 = btn2.getText().toString();
opt3 = btn3.getText().toString();
opt4 = btn4.getText().toString();
if (opt1.equals(answer)) {
btn2.setEnabled(false);
btn3.setEnabled(false);
btn4.setEnabled(false);
btn1.setBackgroundResource(R.color.colortrue);
}
else{
btn1.setBackgroundResource(R.color.colorfalse);
btn2.setEnabled(false);
btn3.setEnabled(false);
btn4.setEnabled(false);
}
}
});
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
opt1 = btn1.getText().toString();
opt2 = btn2.getText().toString();
opt3 = btn3.getText().toString();
opt4 = btn4.getText().toString();
if (opt2.equals(answer)) {
btn1.setEnabled(false);
btn3.setEnabled(false);
btn4.setEnabled(false);
btn2.setBackgroundResource(R.color.colortrue);
}
else{
btn2.setBackgroundResource(R.color.colorfalse);
btn1.setEnabled(false);
btn3.setEnabled(false);
btn4.setEnabled(false);
}
}
});
btn3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
opt1 = btn1.getText().toString();
opt2 = btn2.getText().toString();
opt3 = btn3.getText().toString();
opt4 = btn4.getText().toString();
if (opt3.equals(answer)) {
btn2.setEnabled(false);
btn1.setEnabled(false);
btn4.setEnabled(false);
btn3.setBackgroundResource(R.color.colortrue);
}
else{
btn3.setBackgroundResource(R.color.colorfalse);
btn2.setEnabled(false);
btn1.setEnabled(false);
btn4.setEnabled(false);
}
}
});
btn4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
opt1 = btn1.getText().toString();
opt2 = btn2.getText().toString();
opt3 = btn3.getText().toString();
opt4 = btn4.getText().toString();
if (opt4.equals(answer)) {
btn2.setEnabled(false);
btn3.setEnabled(false);
btn1.setEnabled(false);
btn4.setBackgroundResource(R.color.colortrue);
}
else{
btn4.setBackgroundResource(R.color.colorfalse);
btn2.setEnabled(false);
btn3.setEnabled(false);
btn1.setEnabled(false);
}
}
});
new GetData().execute(data);
}
Runnable refreshActivity=new Runnable(){
public void run() {
countdown =20;
lastquestion++;
mHandler.postDelayed(this, TIME_DELAY);
}
};
Runnable refreshCounter = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
countdown--;
txtcountdown.setText("Time Remaining"+countdown);
handler.postDelayed(this, 1000);
}
};
public JSONArray getquiz(String uid, String cid,String lastindex) {
String result = "";
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(uri+"question.php");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("userId", uid));
nameValuePairs.add(new BasicNameValuePair("categoryId", cid));
nameValuePairs.add(new BasicNameValuePair("lastquestionId", lastindex));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
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());
}
//convert response to string
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();
Log.e("result...",result);
jArray = new JSONArray(result);
Log.e("Array...", ""+jArray);
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
return jArray;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.quiz, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
Log.e("click...", "");
return true;
}
return super.onOptionsItemSelected(item);
}
private class GetData extends AsyncTask<String, Void, Object[]>
{
@Override
protected Object[] doInBackground(String... params) {
String cid,uid,lastindex;
uid = params[0];
cid = params[1];
lastindex = params[2];
Log.e("Data"," "+cid+" "+uid+" "+lastindex);
JSONArray arr = new JSONArray();
arr = getquiz(uid, cid, lastindex);
Object[] obj = new Object[2];
obj[0]=arr;
obj[1]=lastindex;
return obj;
}
@Override
protected void onPostExecute(Object[] obj) {
JSONArray arr = new JSONArray();
String lastindex;
arr = (JSONArray)obj[0];
lastindex =(String)obj[1];
int li;
if(arr!=null) {
try{
li= Integer.parseInt(lastindex);
json_data = arr.getJSONObject(li);
String flag="";
flag =json_data.getString("success");
if(flag.equalsIgnoreCase("0"))
{
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(Quiz.this, "Unable to load Quiz...Try again", Toast.LENGTH_SHORT).show();
}
});
}
else
{
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(Quiz.this, "Loading Quiz...", Toast.LENGTH_SHORT).show();
try{
txtquestion.setText(json_data.getString("title"));
btn1.setText(json_data.getString("option1"));
btn1.setBackgroundResource(R.color.colorreset);
btn1.setEnabled(true);
btn2.setText(json_data.getString("option2"));
btn2.setBackgroundResource(R.color.colorreset);
btn2.setEnabled(true);
btn3.setText(json_data.getString("option3"));
btn3.setBackgroundResource(R.color.colorreset);
btn3.setEnabled(true);
btn4.setText(json_data.getString("option4"));
btn4.setBackgroundResource(R.color.colorreset);
btn4.setEnabled(true);
answer = json_data.getString("answer");
mHandler.post(refreshActivity);
handler.post(refreshCounter);
}
catch(JSONException je){
je.printStackTrace();
}
}
});
}
}
catch(JSONException je){
je.printStackTrace();
}
}
}
}
}
Two ways for that:
1) use AsyncTask: for one by one process you should use asynctask.
2) use thread: call your api in asynctask and every time in thread with 20 second recursion time in your asynctask, refresh all ie: layouts, IDs, view and all.