How to get JSONArray form JSONObject using OkHttp3

Digvijay :

I am trying to fetch data using OkHttp3 but I am getting below exceptions in logcat window.Though I am getting data in logcat but showing in recycler view.

2020-03-13 12:17:24.123 19447-19447/com.app.aamkuapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.app.aamkuapp, PID: 19447
android.os.NetworkOnMainThreadException
    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1513)
    at java.net.SocketInputStream.read(SocketInputStream.java:175)
    at java.net.SocketInputStream.read(SocketInputStream.java:144)
    at okio.InputStreamSource.read(Okio.kt:102)
    at okio.AsyncTimeout$source$1.read(AsyncTimeout.kt:159)
    at okio.RealBufferedSource.read(RealBufferedSource.kt:41)
    at okhttp3.internal.http1.Http1ExchangeCodec$AbstractSource.read(Http1ExchangeCodec.kt:352)
    at okhttp3.internal.http1.Http1ExchangeCodec$ChunkedSource.read(Http1ExchangeCodec.kt:433)
    at okhttp3.internal.connection.Exchange$ResponseBodySource.read(Exchange.kt:279)
    at okio.Buffer.writeAll(Buffer.kt:1104)
    at okio.RealBufferedSource.readString(RealBufferedSource.kt:194)
    at okhttp3.ResponseBody.string(ResponseBody.kt:187)
    at com.app.aamkuapp.HomeFragment$1$1.run(HomeFragment.java:122)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7156)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)
    Suppressed: android.os.NetworkOnMainThreadException
    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1513)
    at java.net.SocketInputStream.read(SocketInputStream.java:175)
    at java.net.SocketInputStream.read(SocketInputStream.java:144)
    at okio.InputStreamSource.read(Okio.kt:102)
    at okio.AsyncTimeout$source$1.read(AsyncTimeout.kt:159)
    at okio.RealBufferedSource.read(RealBufferedSource.kt:41)
    at okhttp3.internal.http1.Http1ExchangeCodec$AbstractSource.read(Http1ExchangeCodec.kt:352)
    at okhttp3.internal.http1.Http1ExchangeCodec$ChunkedSource.read(Http1ExchangeCodec.kt:433)
    at okhttp3.internal.Util.skipAll(Util.kt:337)
    at okhttp3.internal.Util.discard(Util.kt:358)
    at okhttp3.internal.http1.Http1ExchangeCodec$ChunkedSource.close(Http1ExchangeCodec.kt:471)
    at okio.ForwardingSource.close(ForwardingSource.kt:34)
    at okhttp3.internal.connection.Exchange$ResponseBodySource.close(Exchange.kt:306)
    at okio.RealBufferedSource.close(RealBufferedSource.kt:461)
    at kotlin.io.CloseableKt.closeFinally(Closeable.kt:56)
    at okhttp3.ResponseBody.string(ResponseBody.kt:186)
            ... 8 more

This is the line in java code below where error is showing:

String resp = response.body().string();

Below is my code:

  private void loadGen(){

    final ProgressDialog prg = new ProgressDialog(getActivity());
    prg.setMessage("Getting data...");
    prg.setCancelable(false);
    prg.show();

    OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(20, TimeUnit.SECONDS)
            .readTimeout(20,TimeUnit.SECONDS)
            .writeTimeout(20,TimeUnit.SECONDS)
            .build();

    Request request = new Request.Builder().url(URL).build();

    client.newCall(request).enqueue(new Callback() {

        @Override
        public void onResponse(@NotNull Call call, @NotNull final Response response) throws IOException {

            if(getActivity() != null) {

                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        try {

                            String resp = response.body().string();

                            if (resp.length() > 0) {

                                JSONObject jsonObject = new JSONObject(resp);
                                JSONArray jsonArray = jsonObject.getJSONArray("product_data");

                                for (int i = 0; i < 4; i++) {

                                    JSONObject jObj = jsonArray.getJSONObject(i);
                                    String str1 = jObj.getString("product_photo");
                                    String str2 = jObj.getString("product_price");

                                    //   Log.d("img",str1 + str2);
                                    Log.d("pr", str2);

                                    HomeGeneralModel model = new HomeGeneralModel(str1, str2);

                                    generalList.add(model);
                                }

                                genAdapter = new HomeGeneralAdapter(getActivity(), generalList);
                                homeGen.setAdapter(genAdapter);
                            }

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

            }
        }

        @Override
        public void onFailure(@NotNull Call call, @NotNull final IOException e) {

            if(getActivity() != null){

                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        prg.dismiss();
                        Toast.makeText(getActivity(),e.getMessage(),Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }
    });

}

JSON response from the server seems like below:

{
"image_path": "http://aamku.com/admin/upload/product_images/general/",
"msg": "General categoery product details",
"status": 1,
"product_data": [
    {
        "product_name": "Pi-Pi jod kar ye Notebook li hai",
        "product_price": "249.00",
        "category_id": "9",
        "product_id": "125",
        "product_photo": "1574935198_1.jpg"
    },
    {
        "product_name": "Tere Jesa year kaha kaha esa yarana",
        "product_price": "249.00",
        "category_id": "9",
        "product_id": "128",
        "product_photo": "1574935455_1.jpg"
     }
    ]
   }

Someone please let me know what I am doing wrong.Any hep would be appreciated.

THANKS

Praful Patel :

Try this:

Add this code into onCreate():

int SDK_INT = android.os.Build.VERSION.SDK_INT;
if (SDK_INT > 8) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
        .permitAll().build();
    StrictMode.setThreadPolicy(policy);
    // Your code here...
}

Happy Coding :D

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=237985&siteId=1