【问题标题】:Android JSON object parse store in array list which will change each time button clickedAndroid JSON对象解析存储在数组列表中,每次单击按钮时都会更改
【发布时间】:2014-02-08 17:49:39
【问题描述】:

我在将 JSON 数据解析到我的 android 应用程序时遇到问题。我需要解析一个 JSON 对象,如下所示。对于我的应用程序,我想将这个 json 数据存储在一个数组中。然后使用文本视图和按钮显示每个问题以及可能的答案。然后我想在数组中显示下一个问题以及可能的答案。

JSON 对象

 {
    "52f66c6eb82944cc1c00002a": {
        "_id": {
            "$id": "52f66c6eb82944cc1c00002a"
        },
        "Question": "Capital city of England",
        "Answer 1": "Paris",
        "Answer 2": "Liverpool",
        "Correct Answer": "London"
    },
    "52f66c8ab82944780d000029": {
        "_id": {
            "$id": "52f66c8ab82944780d000029"
        },
        "Question": "Capital city of Ireland",
        "Answer 1": "Cork",
        "Answer 2": "Liverpool",
        "Correct Answer": "Dublin"
    }
}

安卓代码

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    protected TextView TitleTextView;
    protected Button PossibleAnswer1;
    protected Button PossibleAnswer2;
    protected Button CorrectAnswer;
    protected String URL ="http://127.0.0.1/mongo-form-create-quiz/processform.php";
    protected HttpClient HTTPClient;
    protected HttpPost HTTPPost;
    protected HttpResponse ResponseFromWeb;
    protected String JSONString;
    protected JSONObject JSONObject;
    protected String JSONQuestion;
    protected String JSONPossibleAnswer1;
    protected String JSONPossibleAnswer2;
    protected String JSONCorrectAnswer;
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppostresponse = new HttpPost("http://127.0.0.1/mongo-form-create-quiz/recordinput.php");
    Intent openLastActivity = new Intent("com.example.quizqizzdemo.LASTACTIVITY");


    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        StrictMode.ThreadPolicy policy = new StrictMode.
        ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy); 

        setContentView(R.layout.activity_main);

        HTTPClient = new DefaultHttpClient();
        HTTPPost = new HttpPost(URL);

        TitleTextView = (TextView) findViewById(R.id.Question_Title);


        PossibleAnswer1 = (Button) findViewById(R.id.PossibleAnswer1);

        PossibleAnswer2 = (Button) findViewById(R.id.PossibleAnswer2);

        CorrectAnswer = (Button) findViewById(R.id.CorrectAnswer);

        try{
            ResponseFromWeb = HTTPClient.execute(HTTPPost);

            JSONString = FormatJSONInput(
                    ResponseFromWeb.getEntity().getContent()).toString();
            JSONObject = new JSONObject(JSONString);

            JSONQuestion = JSONObject.getString("Question");
            JSONPossibleAnswer1 = JSONObject.getString("Answer 1");
            JSONPossibleAnswer2 = JSONObject.getString("Answer 2");
            JSONCorrectAnswer = JSONObject.getString("Correct Answer");

            TitleTextView.setText(JSONQuestion);
            PossibleAnswer1.setText(JSONPossibleAnswer1);
            PossibleAnswer2.setText(JSONPossibleAnswer2);
            CorrectAnswer.setText(JSONCorrectAnswer);

        }

    catch (JSONException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }



        PossibleAnswer1.setOnClickListener(new OnClickListener() {

              @Override
              public void onClick(View arg0) {

                  /*
                 Toast.makeText(getApplicationContext(), 
                               "Incorrect!!", Toast.LENGTH_LONG).show();
                 PossibleAnswer1.setBackgroundColor(Color.RED);
                 */

                    try {
                        // Add your data
                        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                        nameValuePairs.add(new BasicNameValuePair("UserAnswer", JSONPossibleAnswer1));
                        nameValuePairs.add(new BasicNameValuePair("CorrectAnswer", JSONCorrectAnswer));
                        httppostresponse.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                        // Execute HTTP Post Request
                        HttpResponse response = httpclient.execute(httppostresponse);


                        startActivity(openLastActivity);

                    } catch (ClientProtocolException e) {
                        // TODO Auto-generated catch block
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                    }

              }
        });

        PossibleAnswer2.setOnClickListener(new OnClickListener() {

              @Override
              public void onClick(View arg0) {

                  /*
                 Toast.makeText(getApplicationContext(), 
                             "Incorrect!!", Toast.LENGTH_LONG).show();
                 PossibleAnswer1.setBackgroundColor(Color.RED);
                 */

                    try {
                        // Add your data
                        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                        nameValuePairs.add(new BasicNameValuePair("UserAnswer", JSONPossibleAnswer2));
                        nameValuePairs.add(new BasicNameValuePair("CorrectAnswer", JSONCorrectAnswer));
                        httppostresponse.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                        // Execute HTTP Post Request
                        HttpResponse response = httpclient.execute(httppostresponse);

                        startActivity(openLastActivity);

                    } catch (ClientProtocolException e) {
                        // TODO Auto-generated catch block
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                    }

              }
        });

        CorrectAnswer.setOnClickListener(new OnClickListener() {

              @Override
              public void onClick(View arg0) {

                  /*
                 Toast.makeText(getApplicationContext(), 
                             "Correct!!", Toast.LENGTH_LONG).show();
                 CorrectAnswer.setBackgroundColor(Color.GREEN);
                 */

                try {
                    // Add your data
                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                    nameValuePairs.add(new BasicNameValuePair("UserAnswer", JSONCorrectAnswer));
                    nameValuePairs.add(new BasicNameValuePair("CorrectAnswer", JSONCorrectAnswer));
                    httppostresponse.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                    // Execute HTTP Post Request
                    HttpResponse response = httpclient.execute(httppostresponse);

                    startActivity(openLastActivity);

                } catch (ClientProtocolException e) {
                    // TODO Auto-generated catch block
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                }
              }
        });
    }
    private StringBuilder FormatJSONInput(InputStream is) {
        String ReadLine = "";
        StringBuilder CorrectDBData = new StringBuilder();

        BufferedReader rd = new BufferedReader(new InputStreamReader(is));

        try {
            while ((ReadLine = rd.readLine()) != null) {
                CorrectDBData.append(ReadLine);
            }
        }

        catch (IOException e) {
            e.printStackTrace();
        }
        return CorrectDBData;
    }

}

我可以使用字符串数组来做到这一点,但对于我的应用程序,我需要显示来自 mongohq 数据库的数据。

我是一名学生,不熟悉 Android、json 和 mongodb。

【问题讨论】:

  • 这是完整的 json,到目前为止你尝试了什么?
  • 是的,json 会显示在 php 网页上,随着问题的添加会增加我可以解析一个问题并显示在 android 应用程序中,但我需要在单击按钮后显示下一个问题
  • 如果你能够解析这个 json 那么显示数据有什么问题?
  • 我已经添加了我的 java 代码,它正在显示一个问题和答案我现在希望能够在按下任何按钮时显示下一个问题
  • 我的部分问题也是我如何正确解析上述 json 对象并将其内容存储在数组中

标签: java android json mongodb mongohq


【解决方案1】:

如果您每次按下按钮时都会从服务器中提取新问题。 我建议您将这些代码放入新方法中,然后在 onClick() 方法中完成工作时调用方法

但如果你只是一次得到所有问题,我建议你将其转换为JSONObject,就像你所做的那样,然后这样做

ArrayList<JSONObject> list = new ArrayList<JSONObject>();
JSONArray names = json.names();
for(int i =0; i<json.length();i++){
   JSONObject innerJson = json.getJSONObject(names.optString(i));
   /* put stuffs in object*/
   /* add object to list */
   list.add("parse object");
}

当你按下下一个按钮得到一个列表后,你只会从列表中获取你的对象

【讨论】:

  • 好的,但我不确定每次单击按钮时是否需要从服务器中提取?一旦创建了 json 对象,它就会使用运行时更改一次
  • 谢谢,我有点困惑,对不起。什么是 json.names() ?我怎么得到那个?是内在的问题吗?然后我将它们添加到每个循环的对象中,然后将其添加到列表中?
  • json.names() 是从您的 JSONObject 中获取所有名称,它将返回 JSONArray,即{["52f66c6eb82944cc1c00002a","52f66c8ab82944780d000029"]},因此您可以使用循环获取您的问题的每个 JSONObject 添加到您的列表中并使用该列表稍后在您的应用程序上工作
猜你喜欢
  • 1970-01-01
  • 2021-06-06
  • 1970-01-01
  • 1970-01-01
  • 2021-08-27
  • 2015-04-15
  • 1970-01-01
  • 1970-01-01
  • 2021-09-04
相关资源
最近更新 更多