Reputation: 385
i've received Quiz JSON string from server this string contain 10 Question, i received and stored response in ArrayList
. now i want that one Question (and its 4 options)should display on screen then there is next button when i press then next question should be display on screen similarly until control reached all 10 question. my problem is that i cannot do functionality of on press next button show the second one(next) Question. please any one help me i am beginner in android thanks.
Here Is JSON String.
{
"status": 200,
"status_message": "Success",
"response":
[
{
"quizNumber" : "1",
"image" : "",
"question" : "Which car manufacturer was the first to win 100 F1 races?",
"option1" : "Ferrari",
"option2" : "Nissan",
"option3" : "Ford",
"option4" : "",
"answer" : "Ferrari."
},
{
"quizNumber" : "2",
"image" : "",
"question" : "In the professional era which woman has won the most titles at Wimbledon [singles, doubles and mixed] ?",
"option1" : "Venus",
"option2" : "Hingis",
"option3" : "Martina Navratilova",
"option4" : "Waynetta",
"answer" : "Martina Navratilova"
},
{
"quizNumber" : "3",
"image" : "",
"question" : "How many times have Liverpool been relegated from the top flight of English football?",
"option1" : "Four",
"option2" : "Three",
"option3" : "Two",
"option4" : "Five",
"answer" : "Three"
}]}
And Here Is my MainActivity.java class.
package com.example.quistest;
//import goes here
public class MainActivity extends Activity {
String serviceUrl;
ImageView next;
TextView question,quizno;
CheckBox ans_1,ans_2,ans_3,ans_4;
ArrayList<Quiz_List>data;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
data=new ArrayList<Quiz_List>();
next=(ImageView) findViewById(R.id.imageView_nextID);
quizno=(TextView) findViewById(R.id.question_noID);
question=(TextView) findViewById(R.id.txt_questionID);
ans_1=(CheckBox) findViewById(R.id.chk_ans1ID);
ans_2=(CheckBox) findViewById(R.id.chk_ans2ID);
ans_3=(CheckBox) findViewById(R.id.chk_ans3ID);
ans_4=(CheckBox) findViewById(R.id.chk_ans4ID);
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Next...", Toast.LENGTH_SHORT).show();
}
});
if (isNetworkAvailable()) {
execute();
}
else {
// Error message here if network is unavailable.
Toast.makeText(this, "Network is unavailable!", Toast.LENGTH_LONG).show();
}
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
private void execute() {
serviceUrl ="http://mobile.betfan.com/api/?action=quiz&key=MEu07MgiuWgXwJOo7Oe1aHL0yM8VvP&sporttype=all";
class LoginAsync extends AsyncTask<String, Void, String>{
private Dialog loadingDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(MainActivity.this, "Please while wait", "Loading...");
}
@Override
protected String doInBackground(String... params) {
JSONObject jsonObject = new JSONObject();
String dataString = jsonObject.toString();
InputStream is = null;
List<NameValuePair> nameValuePairs = new
ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("data", dataString));
String result = null;
try{
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet();
URI apiurl = new URI(serviceUrl);
httpRequest.setURI(apiurl);
HttpResponse response = httpClient.execute(httpRequest);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
protected void onPostExecute(String result){
String s = result.trim();
loadingDialog.dismiss();
JSONObject respObject;
try {
respObject = new JSONObject(s);
String active = respObject.getString("status_message");
if(active.equalsIgnoreCase("success")){
JSONArray array = respObject.getJSONArray("response");
for (int i =0; i<array.length();i++){
JSONObject jsonObject = array.getJSONObject(i);
String quizNumber= jsonObject.getString("quizNumber");
String question= jsonObject.getString("question");
String option1 = jsonObject.getString("option1");
String option2 = jsonObject.getString("option2");
String option3 = jsonObject.getString("option3");
String option4 = jsonObject.getString("option4");
data.add(new Quiz_List(quizNumber,question,option1,option2,option3,option4));
quizno.setText("Question numer:"+quizNumber);
MainActivity.this.question.setText(question);
ans_1.setText(option1);
ans_2.setText(option2);
ans_3.setText(option3);
ans_4.setText(option4);
}
}else {
Toast.makeText(MainActivity.this, "Quiz received Fail", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
LoginAsync la = new LoginAsync();
la.execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, 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) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And Here is my AarrayList Quiz_List.java class.
package com.example.quistest;
public class Quiz_List {
private String quiz_no;
private String question;
private String answer_1;
private String answer_2;
private String answer_3;
private String answer_4;
public String getQuiz_no() {
return quiz_no;
}
public void setQuiz_no(String quiz_no) {
this.quiz_no = quiz_no;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getAnswer_1() {
return answer_1;
}
public void setAnswer_1(String answer_1) {
this.answer_1 = answer_1;
}
public String getAnswer_2() {
return answer_2;
}
public void setAnswer_2(String answer_2) {
this.answer_2 = answer_2;
}
public String getAnswer_3() {
return answer_3;
}
public void setAnswer_3(String answer_3) {
this.answer_3 = answer_3;
}
public String getAnswer_4() {
return answer_4;
}
public void setAnswer_4(String answer_4) {
this.answer_4 = answer_4;
}
public Quiz_List(String quiz_no, String question, String answer_1,
String answer_2, String answer_3, String answer_4) {
super();
this.quiz_no = quiz_no;
this.question = question;
this.answer_1 = answer_1;
this.answer_2 = answer_2;
this.answer_3 = answer_3;
this.answer_4 = answer_4;
}
}
Please anyone help i want when i want press next then it should display second one question(its 4 options) should display on screen. And In current situation it displays last question(its 4 options) only.
Upvotes: 1
Views: 4537
Reputation: 132
Initially set in MainActivity
int count=0;
Add 1 to count and send count to MainActivity.class when next button is clicked.
Intent i=new Intent(MainActivity.this,MainActivity.class);
i.putStringExtra("count",count);
startActivity(i);
and according to received count in post Execute
JSONObject jsonObject = array.getJSONObject(count);
String quizNumber= jsonObject.getString("quizNumber");
String question= jsonObject.getString("question");
String option1 = jsonObject.getString("option1");
String option2 = jsonObject.getString("option2");
String option3 = jsonObject.getString("option3");
String option4 = jsonObject.getString("option4");
Every time next button is clicked count is increased by one
Paste the below in MainActivity
package com.example.quistest;
//import goes here
public class MainActivity extends Activity {
String serviceUrl;
ImageView next;
TextView question,quizno;
CheckBox ans_1,ans_2,ans_3,ans_4;
ArrayList<Quiz_List>data;
String count=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
data=new ArrayList<Quiz_List>();
next=(ImageView) findViewById(R.id.imageView_nextID);
quizno=(TextView) findViewById(R.id.question_noID);
question=(TextView) findViewById(R.id.txt_questionID);
ans_1=(CheckBox) findViewById(R.id.chk_ans1ID);
ans_2=(CheckBox) findViewById(R.id.chk_ans2ID);
ans_3=(CheckBox) findViewById(R.id.chk_ans3ID);
ans_4=(CheckBox) findViewById(R.id.chk_ans4ID);
Intent i=getIntent();
count=i.getStringExtra("count");
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
int new_count=Integer.parseInt(count)+1;
Intent intent=new Intent(MainActivity.this, MainActivity.class);
intent.putExtra("count",String.valueOf(new_count));
Toast.makeText(getApplicationContext(), "Next...", Toast.LENGTH_SHORT).show();
}
});
if (isNetworkAvailable()) {
execute();
}
else {
// Error message here if network is unavailable.
Toast.makeText(this, "Network is unavailable!", Toast.LENGTH_LONG).show();
}
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
private void execute() {
serviceUrl ="http://mobile.betfan.com/api/?action=quiz&key=MEu07MgiuWgXwJOo7Oe1aHL0yM8VvP&sporttype=all";
class LoginAsync extends AsyncTask<String, Void, String>{
private Dialog loadingDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(MainActivity.this, "Please while wait", "Loading...");
}
@Override
protected String doInBackground(String... params) {
JSONObject jsonObject = new JSONObject();
String dataString = jsonObject.toString();
InputStream is = null;
List<NameValuePair> nameValuePairs = new
ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("data", dataString));
String result = null;
try{
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet();
URI apiurl = new URI(serviceUrl);
httpRequest.setURI(apiurl);
HttpResponse response = httpClient.execute(httpRequest);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
protected void onPostExecute(String result){
String s = result.trim();
loadingDialog.dismiss();
JSONObject respObject;
try {
respObject = new JSONObject(s);
String active = respObject.getString("status_message");
if(active.equalsIgnoreCase("success")){
JSONArray array = respObject.getJSONArray("response");
JSONObject jsonObject = array.getJSONObject(Integer.parseInt(count));
String quizNumber= jsonObject.getString("quizNumber");
String question= jsonObject.getString("question");
String option1 = jsonObject.getString("option1");
String option2 = jsonObject.getString("option2");
String option3 = jsonObject.getString("option3");
String option4 = jsonObject.getString("option4");
data.add(new Quiz_List(quizNumber,question,option1,option2,option3,option4));
quizno.setText("Question numer:"+quizNumber);
MainActivity.this.question.setText(question);
ans_1.setText(option1);
ans_2.setText(option2);
ans_3.setText(option3);
ans_4.setText(option4);
}else {
Toast.makeText(MainActivity.this, "Quiz received Fail", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
LoginAsync la = new LoginAsync();
la.execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, 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) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Upvotes: 1
Reputation: 527
I write an example as per your requriment
1-we have a json array
{
"status": 200,
"status_message": "Success",
"response":
[
{
"quizNumber" : "1",
"image" : "",
"question" : "Which car manufacturer was the first to win 100 F1 races?",
"option1" : "Ferrari",
"option2" : "Nissan",
"option3" : "Ford",
"option4" : "",
"answer" : "Ferrari."
},
{
"quizNumber" : "2",
"image" : "",
"question" : "In the professional era which woman has won the most titles at Wimbledon [singles, doubles and mixed] ?",
"option1" : "Venus",
"option2" : "Hingis",
"option3" : "Martina Navratilova",
"option4" : "Waynetta",
"answer" : "Martina Navratilova"
},
{
"quizNumber" : "3",
"image" : "",
"question" : "How many times have Liverpool been relegated from the top flight of English football?",
"option1" : "Four",
"option2" : "Three",
"option3" : "Two",
"option4" : "Five",
"answer" : "Three"
}]}
2-Make a pojo class
class Mypojo {
String op1,op2,op3,op4,ans;
Mypojo(String s1,String s2,String s3,String s4,String ss){
op1 = s1;
.......
ans = ss;
}
//add getter / setter method here
}
3- Now in activity take an array list
int i = 0;
ArrayList<Mypojo> mypojo = new AarrayList();
where you parse json
make pojo class object like
Mypojo pojo = new Mypojo(parameters) and pass all parameters
then mypojo.add(pojo);
In this way all json data will be added in pojo type array list.
4-Now in Next button code will be
int arraysize = mypojo.size();
if(i<arraysize){
i++;
get all values from pojo arraylist by using i as a index position like
String op1 = mypojo.get(i).getOp1();
and change your UI.
}
This is for example if you will do all steps correctly your problem will be solved.
Upvotes: 1
Reputation: 527
If you parse json and add data in array list I suggest you make a pojo class and take all values in pojo type array list. When you press next button find array list size and array list index start from 0 to array list size so take a integer (int i = 0 )
and its initial value must be 0(zero).Now use if (i<array.size())
condition and inside it increase integer value (i++)
. By this way you can solve your problem.Do not use Intent , all things do in same activity.
Upvotes: 0
Reputation: 3190
When you need to pass data from one activity to another activity you need to use intent.putExtra()
method to send data.
For send data from your main activity ->
Intent intent = new Intent(MainActivity.this,NEXT_ACTIVITY.class); // Change NEXT_ACTIVITY to your option / answer activity.
intent.putExtra("option_1",option1);
intent.putExtra("option_2",option2);
intent.putExtra("option_3",option3);
intent.putExtra("option_4",option4);
intent.putExtra("answer",answer);
startActivity(intent);
To receive data from your next activity ->
Bundle bundle = getIntent().getExtras();
String option1 = bundle.getString("option_1");
String option2 = bundle.getString("option_2");
String option3 = bundle.getString("option_3");
String option4 = bundle.getString("option_4");
String answer = bundle.getString("answer");
Now you can use these data wherever you want in this activity.
Upvotes: 0