2

This is My JSON Array with Different Quotes along with their Author Name.

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

I want to Fetch a Single Random JSON Object inside android. Instead of whole things.

Example :

 {
  "id": "4",
  "quote": "whatsapp is bad",
  "author": "William W. Purkey "
}

This is What I'm Getting Now in my Android App: Getting All JSON Object from Array

Here is my 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);

    }
}

I Need to Show Only One Quote in my android app instead of showing all Quotes from JSON Array. Need help. Thanks in Advance

3
  • Just find size of your json array and then after generate any random number between 0 to size of your json array using Random class and get element at this position. That's it! Commented Sep 11, 2018 at 3:24
  • Uff. What if I'm adding One Quote Daily it'll increase day to day. In that Case, I need to Update my App Frequently? Need more Explanation or Code Example on your answer. Thanks Commented Sep 11, 2018 at 3:26
  • No, you don't need to update your app daily because you are going to find size of your array every time and we are passing it to Random class. so, random class will generate random number every time from the new range you have given to it. ex. if initially you have 3 objects in array then Random class will generate random number between 0 to 2. Now, if you increase array size from your service, your app will find new length (suppose 4) and Random class will simply generate number between 0 to 3. Commented Sep 11, 2018 at 3:30

3 Answers 3

3

You can just use a random number generator.

Random rand = new Random();
jsonArray.getJSONObject(rand.nextInt(jsonArray.length());
Sign up to request clarification or add additional context in comments.

Comments

1

The key is randomized the index of jsonArray,which could be done like this:

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

Comments

1

When you get all your quotes, the JsonArray, store it for later use and display a random quote from it. Then when clicking Next Quote call the same method to display a random quote from the JsonArray you previously download.

JSONArray jsonArray;

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

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

And the method to display a random quote would be:

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

5 Comments

Awesome. It's Working Thanks. Are you sure it won't increase the App Size(or) Storage used by the app?
And Possible to Clear the Cache of Volley? Because if I update some info in JSON, It's not get reflected in the Android App.
You're wellcome! You can safely clear the volley cache. It won't significally increase the size of your app. The storage use depends on how much data you download. Another approach would be to select the random quote in your server and just ask for one-single-random-quote instead of getting all the quotes and randomize in the app
My API Endpoint is made in PHP. Just with SQL LIMIT Function. I'm displaying only one Quote in JSON Output. But If I do so, The Problem will be, Android app fetches and Stores in Volley cache. Even if the Button is clicked in android, It wont refresh the Backend API. So I'm not getting new quote on Button Click.
And why don't you just clear Volley's cache before a new request?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.