java - 从服务器接收测验 JSON 字符串并显示在屏幕上

标签 java android json arraylist

我从服务器收到了测验 JSON 字符串,该字符串包含 10 个问题,我收到响应并将其存储在 ArrayList 中。现在我希望一个问题(及其 4 个选项)应该显示在屏幕上,然后当我按下时有下一个按钮,然后下一个问题应该类似地显示在屏幕上,直到控制达到所有 10 个问题。我的问题是我无法执行按下一步按钮显示第二个(下一个)问题的功能。请任何人帮助我,我是 android 的初学者,谢谢。

这是 JSON 字符串。

   { 
  "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"
    }]}   

这是我的 MainActivity.java 类。

     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);
  }
 }

这是我的 AarrayList Quiz_List.java 类。

     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;
 }


}

请任何人帮助我,当我想按下一步时,它应该显示第二个问题(它的 4 个选项)应该显示在屏幕上。 并且在当前情况下,它仅显示最后一个问题(其 4 个选项)。

最佳答案

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.

关于java - 从服务器接收测验 JSON 字符串并显示在屏幕上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37430519/

相关文章:

java - android-onOptionsItemSelected 方法调用了两次

java - 在 Java 和 Spring 中对 REST API 进行单元测试

java.lang.ClassCastException : android. widget.ImageButton 无法转换为 android.widget.TextView

android - new Thread 和 AsyncTask 的区别

Javascript 获取 JSON 数组

java - 如何在selenium中关闭Web驱动程序之前验证文件下载是否完成?

java - Webdriver隐式等待动态ID

android - 修改android中的游标列值

json - 将特定的 Javascript 库导入到 Angular 4(如果库不导出变量)

c++ - 从 nlohmann json 访问元素