Design a Quiz activity which refreshes every 20 seconds (Reworked)

73 views Asked by At

I am making a quiz application, in which I have a quiz activity where I am doing the following work.

  1. Get data from server (Now getting all data using Asynctask).
  2. Set data to my UI (which is going well).
  3. get user input and check the marked answer.
  4. 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();
            }
        }
    }
}
}
2

There are 2 answers

0
kiturk3 On

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.

0
avinash On

Here is the code snippet to schedule a task using ScheduledExecutorService, hope it will give a way. This class will update the textview after every 20 secs. Initially(when launched) it will wait of 20 sec,after that it will start modify the textview. Basically if server is fast enough to give the response within 20 sec. you can download the data in run() and pass it to handler via Message. But I will prefer to download the questions/data(to make app more responsive and reduce the number of request) and then populate it by using ScheduledExecutorService.

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView textView;
private int i=0;
private ScheduledExecutorService executor;
private Handler handler=new Handler()
{
    public void handleMessage(Message msg) {
        textView.setText(msg.arg1+"");
    };
};
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textView=(TextView)findViewById(R.id.textView1);
    executor=Executors.newSingleThreadScheduledExecutor();
    executor.scheduleAtFixedRate(new Runnable() {

        @Override
        public void run() {
        Message message=Message.obtain();
        message.arg1=i;
        i++;
        handler.sendMessage(message);
        }
    },20, 20, TimeUnit.SECONDS);

    }

@Override
protected void onPause() {
    super.onPause();
    executor.shutdown();

}
}