Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/211.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何从JSON数组中获取单个随机JSONObject_Android_Json - Fatal编程技术网

Android 如何从JSON数组中获取单个随机JSONObject

Android 如何从JSON数组中获取单个随机JSONObject,android,json,Android,Json,这是我的JSON数组,带有不同的引号和作者姓名 { "quotes": [ { "id": "4", "quote": "whatsapp is bad", "author": "William W. Purkey " }, { "id": "3", "quote": "yahoo is a company", "author": "William W. Purkey " },

这是我的JSON数组,带有不同的引号和作者姓名

 {
  "quotes": [
    {
      "id": "4",
      "quote": "whatsapp is bad",
      "author": "William W. Purkey "
    },
    {
      "id": "3",
      "quote": "yahoo is a company",
      "author": "William W. Purkey "
    },
    {
      "id": "1",
      "quote": "Google is a search engine",
      "author": "William W. Purkey "
    }
  ]
}
我想在android中获取一个随机JSON对象。而不是整个事情

例如:

 {
  "id": "4",
  "quote": "whatsapp is bad",
  "author": "William W. Purkey "
}
这就是我现在在Android应用程序中得到的:

这是我的MainActivity.java

    public class MainActivity extends AppCompatActivity {
    private TextView quoteTV, authorTV, startReading;
   // private RequestQueue mQueue;
    private ProgressDialog progress;
    public RequestQueue mQueue;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        startReading = findViewById(R.id.startReading);
        quoteTV = findViewById(R.id.quoteTV);
        quoteTV.setVerticalScrollBarEnabled(true);
        quoteTV.setMovementMethod(ScrollingMovementMethod.getInstance());
        quoteTV.setScrollBarStyle(View.SCROLLBARS_INSIDE_INSET);
        authorTV = findViewById(R.id.authorTV);
        final Button buttonParse = findViewById(R.id.button_parse);

        mQueue = Volley.newRequestQueue(this);

        CardView editProfileLayout = (CardView) findViewById(R.id.authorTVBG);
        editProfileLayout.setVisibility(View.GONE);

        buttonParse.setText("Start Reading");

        buttonParse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                buttonParse.setText("Next Quote");
                CardView editProfileLayout = (CardView) findViewById(R.id.authorTVBG);
                editProfileLayout.setVisibility(View.VISIBLE);
                quoteTV.setText("");
                authorTV.setText("");


                progress = new ProgressDialog(MainActivity.this);
                progress.setMessage("Loading.. Please Wait");
                progress.setCancelable(true);
                progress.show();

                jsonParse();
                startReading.setText("");
            }
        });
    }

    private void jsonParse() {

        String url = "http://myjson.com/q3wr4";

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONArray jsonArray = response.getJSONArray("quotes");

                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject quotes = jsonArray.getJSONObject(i);

                                int id = quotes.getInt("id");
                                String quote = quotes.getString("quote");
                                String author = quotes.getString("author");

                                progress.hide();

                                quoteTV.append("“ " + String.valueOf(quote) + " ”");
                                authorTV.append("Author " + ": " + String.valueOf(author));

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });

        mQueue.add(request);

    }
}
public类MainActivity扩展了AppCompatActivity{
私有文本视图quoteTV、authorTV、startReading;
//专用请求队列MQUE;
私人进展对话进展;
公共请求队列MQUE;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startReading=findviewbyd(R.id.startReading);
quoteTV=findViewById(R.id.quoteTV);
quoteTV.setVerticalScrollBarEnabled(真);
setMovementMethod(ScrollingMovementMethod.getInstance());
quoteTV.setScrollBarStyle(视图.滚动条在插图中);
authorTV=findviewbyd(R.id.authorTV);
最终按钮按钮分析=findViewById(R.id.Button\u parse);
mQueue=Volley.newRequestQueue(this);
CardView编辑档案布局=(CardView)findViewById(R.id.authorTVBG);
editProfileLayout.setVisibility(View.GONE);
按钮pass.setText(“开始阅读”);
ButtonPasse.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
按钮pass.setText(“下一个引号”);
CardView编辑档案布局=(CardView)findViewById(R.id.authorTVBG);
editProfileLayout.setVisibility(View.VISIBLE);
quoteTV.setText(“”);
authorTV.setText(“”);
进度=新建进度对话框(MainActivity.this);
progress.setMessage(“正在加载..请稍候”);
进度。可设置可取消(true);
progress.show();
jsonParse();
startReading.setText(“”);
}
});
}
私有void jsonParse(){
字符串url=”http://myjson.com/q3wr4";
JsonObjectRequest=新的JsonObjectRequest(request.Method.GET,url,null,
新的Response.Listener(){
@凌驾
公共void onResponse(JSONObject响应){
试一试{
JSONArray JSONArray=response.getJSONArray(“引号”);
for(int i=0;i

我需要在我的android应用程序中只显示一个引号,而不是显示JSON数组中的所有引号。我需要帮助。提前感谢

键是随机的jsonArray索引,可以这样做:

import java.util.Random;
Random r = new Random();
int index = r.nextInt(jsonArray.length()) ; //range is 0~jsonArray.length()

JSONObject quotes = jsonArray.getJSONObject(index);

int id = quotes.getInt("id");
String quote = quotes.getString("quote");
String author = quotes.getString("author");

关键是jsonArray的索引随机化,可以这样做:

import java.util.Random;
Random r = new Random();
int index = r.nextInt(jsonArray.length()) ; //range is 0~jsonArray.length()

JSONObject quotes = jsonArray.getJSONObject(index);

int id = quotes.getInt("id");
String quote = quotes.getString("quote");
String author = quotes.getString("author");

您可以使用随机数生成器

Random rand = new Random();
jsonArray.getJSONObject(rand.nextInt(jsonArray.length());

您可以使用随机数生成器

Random rand = new Random();
jsonArray.getJSONObject(rand.nextInt(jsonArray.length());

当您获得所有的引号、JsonArray时,将其存储起来供以后使用,并显示其中的随机引号。然后,当单击Next Quote时,调用相同的方法以显示先前下载的JsonArray中的随机Quote

JSONArray jsonArray;

@Override
public void onResponse(JSONObject response) {
    try {
        progress.hide();
        jsonArray = response.getJSONArray("quotes");
        displayRandomQuote();

    } catch (JSONException e) {
        e.printStackTrace();
    }
}
显示随机报价的方法是:

public void displayRandomQuote(){
    // Get the total number of quotes
    int totalQuotes = jsonArray.length();

    // Pick a random between 0 and the total
    Random r = new Random();
    int random = r.nextInt(totalQuotes);

    try {
        JSONObject quoteData = jsonArray.getJSONObject(random);
        int id = quoteData.getInt("id");
        String quote = quoteData.getString("quote");
        String author = quoteData.getString("author");

        quoteTV.setText("“ " + String.valueOf(quote) + " ”");
        authorTV.setText("Author " + ": " + String.valueOf(author));
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

当您获得所有的引号、JsonArray时,将其存储起来供以后使用,并显示其中的随机引号。然后,当单击Next Quote时,调用相同的方法以显示先前下载的JsonArray中的随机Quote

JSONArray jsonArray;

@Override
public void onResponse(JSONObject response) {
    try {
        progress.hide();
        jsonArray = response.getJSONArray("quotes");
        displayRandomQuote();

    } catch (JSONException e) {
        e.printStackTrace();
    }
}
显示随机报价的方法是:

public void displayRandomQuote(){
    // Get the total number of quotes
    int totalQuotes = jsonArray.length();

    // Pick a random between 0 and the total
    Random r = new Random();
    int random = r.nextInt(totalQuotes);

    try {
        JSONObject quoteData = jsonArray.getJSONObject(random);
        int id = quoteData.getInt("id");
        String quote = quoteData.getString("quote");
        String author = quoteData.getString("author");

        quoteTV.setText("“ " + String.valueOf(quote) + " ”");
        authorTV.setText("Author " + ": " + String.valueOf(author));
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

只需找到json数组的大小,然后使用
random
class生成0到json数组大小之间的任意随机数,并在该位置获取元素。就这样!不明飞行物。如果我每天添加一个报价,它会每天增加。在这种情况下,我需要经常更新我的应用程序吗?您的答案需要更多的解释或代码示例。谢谢,你不需要每天更新你的应用程序,因为你每次都会找到数组的大小,我们会将它传递给
Random
类。所以,random类每次都会从您给它的新范围生成随机数。例如,如果最初数组中有3个对象,则
Random
class将生成0到2之间的随机数。现在,如果您从服务中增加数组大小,您的应用程序将找到新的长度(假设为4),并且
Random
类将简单地生成0到3之间的数字。只需找到json数组的大小,然后使用
Random
类生成0到json数组大小之间的任意随机数,并在该位置获取元素。就这样!不明飞行物。如果我每天添加一个报价,它会每天增加。在这种情况下,我需要经常更新我的应用程序吗?您的答案需要更多的解释或代码示例。谢谢,你不需要每天更新你的应用程序,因为你每次都会找到数组的大小,我们会将它传递给
Random
类。所以,random类将在每次从新范围生成随机数时