Search code examples
androidjsonandroid-asynctaskokhttp

java.lang.String cannot be converted to JSONArray from Okhttp


i am trying to get json from server and place it into my RecyclerView, but its says "java.lang.String cannot be converted to JSONArray". I am try to track my json, but its shown nothing. Whats wrong, how can i solve this?

     private void Prosesdataserver(int id){
     AsyncTask<Integer, Void, Void> task = new AsyncTask<Integer, Void, Void>() {
        @Override
        protected Void doInBackground(Integer... integers) {
        OkHttpClient client = new OkHttpClient();
        try{
           RequestBody formBody = new FormBody.Builder().add("username_krm", username).add("password_krm", password).build();
           Request request = new Request.Builder().url("http://" + urlpakai + "/utrapos/index.php/getpenawaran?id="+integers[0]).post(formBody).build();
           response = client.newCall(request).execute();
           ini = response.body().toString();
           JSONArray array = new JSONArray(ini);
           System.out.println("Saya Berkata: " + ini);
              for(int i=0; i<array.length();i++){
                 JSONObject object = array.getJSONObject(i);
                 DataJson hasil = new DataJson(object.getInt("id"), object.getString("kode"), object.getString("tglpenawaran"), object.getString("nama"), object.getString("supplier"), object.getString("nopenawaran"));
                 data.add(hasil);
              }
            }catch (IOException e){
               e.printStackTrace();
             }
             catch (JSONException e){
                e.printStackTrace();
             }
  return null;
 }

Solution

  • With minimum information you've shared, I'm assuming the error is at this line

    JSONArray array = new JSONArray(ini);
    

    The reason behind that is your ini. It should be

    ini = response.body().string();
    

    and not .toString()

    Here is a sample code:

    try {
            String responseData = response.body().string();
            JSONArray json = new JSONArray(responseData);
        } catch (JSONException e) {
    
        }
    

    For more understanding on how to make network calls with OkHttp, take a look at this documentation.