WordPress JSON Volley Only Get One Last Value

by Sa'ad Abdurrazzaq   Last Updated September 12, 2019 04:08 AM

I wanna get list posts based on specific category from this url https://www.kisahmuslim.com/wp-json/wp/v2/categories using JSON Volley, but unfortunately it only get the last value.

I don't know what's wrong. Below the code you can check!

DaftarCategories

public class CallingPage extends AsyncTask<String, String, String> {

        HttpURLConnection conn;
        java.net.URL url = null;
        private int page = 1;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            //this method will be running on UI thread
            showNoFav(false);
            pb.setVisibility(View.VISIBLE);

        }

        @Override
        protected String doInBackground(String... params) {

            try {

                url = new URL("https://www.kisahmuslim.com/wp-json/wp/v2/categories");

            }
            catch(MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return e.toString();
            }
            try {

                // Setup HttpURLConnection class to send and receive data from php and mysql
                conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(READ_TIMEOUT);
                conn.setConnectTimeout(CONNECTION_TIMEOUT);
                conn.setRequestMethod("GET");

                // setDoOutput to true as we recieve data from json file
                conn.setDoOutput(true);

            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
                return e1.toString();
            }

            try {

                int response_code = conn.getResponseCode();

                // Check if successful connection made
                if (response_code == HttpURLConnection.HTTP_OK) {

                    // Read data sent from server
                    InputStream input = conn.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                    StringBuilder result = new StringBuilder();
                    String line;

                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }

                    // Pass data to onPostExecute method
                    return (result.toString());

                } else {
                    return("koneksi gagal");
                }

            } catch (IOException e) {
                e.printStackTrace();
                return e.toString();
            } finally {
                conn.disconnect();
            }

        }


        protected void onPostExecute(final String result)
        {
            JsonArrayRequest stringRequest = new JsonArrayRequest(Request.Method.GET, SumberPosts.HOST_URL+"wp/v2/categories/", null, new Response.Listener<JSONArray>()
            {
                @Override
                public void onResponse(JSONArray response) {
                    // display response
                    Log.d(TAG, response.toString() + "Size: "+response.length());

                    // agar setiap kali direfresh data tidak redundant
                    typeForPosts.clear();

                    for(int i=0; i<response.length(); i++) { //ambil semua objek yang ada
                        final CategoriesModel post = new CategoriesModel();
                        try {
                            Log.d(TAG, "Object at " + i + response.get(i));
                            JSONObject obj = response.getJSONObject(i);

                            post.setId(obj.getInt("id"));
                            post.setPostURL(obj.getString("link"));

                            //Get category name
                            post.setCategory(obj.getString("name"));

                            //////////////////////////////////////////////////////////////////////////////////////
                            // getting article konten
                            JSONObject postCategoryParent = obj.getJSONObject("_links");
                            JSONArray postCategoryObj = postCategoryParent.getJSONArray("wp:post_type");
                            postCategoryIndex = postCategoryObj.getJSONObject(0); //yang dimaksud 0, tanda {} cuma ada satu, karena itu indexnya 0.
                            postCategoryUrl = postCategoryIndex.getString("href"); //satu objek yang dimaksud adalah href

                            if(postCategoryUrl != null) {
                                //Log.d(TAG, postCategoryIndex.getString("href"));
                                JsonArrayRequest getKonten = new JsonArrayRequest(Request.Method.GET, postCategoryUrl, null, new Response.Listener<JSONArray>()
                                {
                                    @Override
                                    public void onResponse(JSONArray respon) {
                                        Log.d(TAG, respon.toString() + "Size: "+respon.length());
                                        for(int d=0; d<respon.length(); d++) {
                                            try {
                                                //Log.d(TAG, "Object at " + i + respon.get());
                                                JSONObject objek = respon.getJSONObject(d); //ambil semua artikel di dalam {} yang tersedia di postCategoryUrl

                                                post.setCreatedAt(objek.getString("date"));

                                                //Get category title
                                                JSONObject titleObj = objek.getJSONObject("title");
                                                post.setJudul(titleObj.getString("rendered"));

                                                //Get excerpt
                                                JSONObject exerptObj = objek.getJSONObject("excerpt");
                                                post.setExcerpt(exerptObj.getString("rendered"));

                                                // Get content
                                                JSONObject contentObj = objek.getJSONObject("content");
                                                post.setContent(contentObj.getString("rendered"));

                                                //////////////////////////////////////////////////////////////////////////////////////
                                                // getting URL of the Post fetured Image
                                                JSONObject featureImage = objek.getJSONObject("_links");
                                                JSONArray featureImageUrl = featureImage.getJSONArray("wp:featuredmedia");
                                                JSONObject featureImageObj = featureImageUrl.getJSONObject(0);
                                                String fiurl = featureImageObj.getString("href");

                                                if(fiurl != null) {
                                                    Log.d(TAG, featureImageObj.getString("href"));

                                                    JsonArrayRequest getMedia = new JsonArrayRequest(Request.Method.GET, fiurl, null, new Response.Listener<JSONArray>()
                                                    {
                                                        @Override
                                                        public void onResponse(JSONArray response) {
                                                            for(int f=0; f<response.length(); f++) {
                                                                try {
                                                                    JSONObject objek = response.getJSONObject(f);

                                                                    JSONObject gambar = objek.getJSONObject("guid");
                                                                    post.setPostImg(gambar.getString("rendered"));
                                                                }
                                                                catch (JSONException e) {
                                                                    e.printStackTrace();
                                                                }
                                                            }
                                                            //notifyDataSetChanged untuk mendapatkan gambar
                                                            recycleViewWordPress.setAdapter(mAdapter);
                                                            mAdapter.notifyDataSetChanged();

                                                        }

                                                    }, new Response.ErrorListener() {
                                                        @Override
                                                        public void onErrorResponse(VolleyError error) {
                                                            pb.setVisibility(View.GONE);
                                                            Log.d(TAG, error.toString());
                                                        }

                                                    });

                                                    queue.add(getMedia);
                                                } //if fiurl

                                            }
                                            catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                        }// for category

                                        recycleViewWordPress.setAdapter(mAdapter);
                                        mAdapter.notifyDataSetChanged();

                                    } //onResponse2

                                }, new Response.ErrorListener() { //getKonten
                                    @Override
                                    public void onErrorResponse(VolleyError error) {
                                        pb.setVisibility(View.GONE);
                                        Log.d(TAG, error.toString());
                                    }

                                });

                                queue.add(getKonten);

                            } //if postCategoryUrl

                            //////////////////////////////////////////////////////////////////////////////////////

                            typeForPosts.add(post);

                        } //try 1
                        catch (JSONException e) {
                            e.printStackTrace();
                        }

                    } //for 1

                    pb.setVisibility(View.GONE);
                    recycleViewWordPress.setAdapter(mAdapter);
                    mAdapter.notifyDataSetChanged();

                } //onResponse1

            }, new Response.ErrorListener() { //stringRequest
                @Override
                public void onErrorResponse(VolleyError error) {
                    showNoFav(true);
                    pb.setVisibility(View.GONE);
                    Log.e(TAG, "Error: " + error.getMessage());
                    Toast.makeText(getContext(), "Tidak bisa menampilkan data. Periksa kembali sambungan internet Anda", Toast.LENGTH_LONG).show();
                }
            });

            // Add the request to the RequestQueue.
            queue.add(stringRequest);

        } //onPostExecute

    } //CallingPage
Tags : api json


Related Questions





Content personalization

Updated November 05, 2018 20:08 PM

Activate Theme After Purchase Code Verification

Updated May 21, 2019 14:08 PM