1

Can anyone say me why i am getting the following error:

org.json.JSONException: Value org.apache.http.message.BasicHttpResponse@94bea9f of type java.lang.String cannot be converted to JSONObject.

MainActivity:

package com.example.addvehicle;
import android.app.ListActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.util.Pair;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.HttpResponse;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.example.addvehicle.R.string.brand;

public class MainActivity extends AppCompatActivity {


    private String TAG = MainActivity.class.getSimpleName();
    ArrayList<String> brandListArray = new ArrayList<String>();
    ArrayList<String> modelList;
    Button addVehicleBtn;
    EditText AddVehicle_Regno, kmscovered;
    RadioButton petrol, Diesel, fullyloaded, Basicmodel;
    TextView textView8, textViewkms;
    Spinner AddspinnerMake, AddspinnerModel, AddspinnerYear;
    private static String url = "http://garage.kaptastech.mobi/api/5k/master/vehicle";
    private String[] values;
    ArrayList<HashMap<String, String>> addVehiclelist;

    String jsonStr;
    String Regno, fuelType, Brand, Year, Model, variant;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        brandListArray = new ArrayList<String>();
        modelList = new ArrayList<String>();


        addVehiclelist = new ArrayList<HashMap<String, String>>();
        petrol = (RadioButton) findViewById(R.id.petrol);
        Diesel = (RadioButton) findViewById(R.id.diesel);
        fullyloaded = (RadioButton) findViewById(R.id.fullyLoaded);
        Basicmodel = (RadioButton) findViewById(R.id.basicmodel);
        addVehicleBtn = (Button) findViewById(R.id.addVehicleBtn);
        AddVehicle_Regno = (EditText) findViewById(R.id.AddVehicle_Regno);
        kmscovered = (EditText) findViewById(R.id.kmsCovered);
        textView8 = (TextView) findViewById(R.id.textView8);
        textViewkms = (TextView) findViewById(R.id.textViewkms);
        AddspinnerMake = (Spinner) findViewById(R.id.AddspinnerMake);
        AddspinnerModel = (Spinner) findViewById(R.id.AddspinnerModel);
        AddspinnerYear = (Spinner) findViewById(R.id.AddspinnerYear);


        new Getbrands().execute();
        new Getmodels().execute();

        petrol.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

                if (petrol.isChecked()) {
                    fuelType = petrol.getText().toString();
                }
            }
        });

        Diesel.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

                if (Diesel.isChecked()) {
                    fuelType = Diesel.getText().toString();
                }
            }
        });
        AddspinnerMake.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                Brand = AddspinnerMake.getSelectedItem().toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        AddspinnerYear.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                Year = AddspinnerYear.getSelectedItem().toString();

            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        AddspinnerModel.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                Model = AddspinnerModel.getSelectedItem().toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        Basicmodel.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

                if (Basicmodel.isChecked()) {
                    variant = Basicmodel.getText().toString();
                }
            }
        });

        fullyloaded.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

                if (fullyloaded.isChecked()) {
                    variant = fullyloaded.getText().toString();
                }
            }
        });


        addVehicleBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Regno = AddVehicle_Regno.getText().toString();
                new GetVehicle().execute();




                Intent intent = new Intent(MainActivity.this, AddVehicle.class);
                startActivity(intent);
            }
        });
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("Main Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        AppIndex.AppIndexApi.start(client, getIndexApiAction());
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        AppIndex.AppIndexApi.end(client, getIndexApiAction());
        client.disconnect();
    }

    private class GetVehicle extends AsyncTask<Void, Void, Void> {

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

        @Override
        protected Void doInBackground(Void... arg0) {

            HttpClient client = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost("http://garage.kaptastech.mobi/api/5k/master/vehicle");

            List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(6);

            nameValuePair.add(new BasicNameValuePair("registration_no", Regno));
            nameValuePair.add(new BasicNameValuePair("brand", Brand));
            nameValuePair.add(new BasicNameValuePair("model", Model));
            nameValuePair.add(new BasicNameValuePair("type", fuelType));
            nameValuePair.add(new BasicNameValuePair("variant", variant));
            nameValuePair.add(new BasicNameValuePair("year", Year));

            try {
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
            } catch (UnsupportedEncodingException e) {
                // writing error to Log
                e.printStackTrace();
            }

            // Making HTTP Request
            try {
                HttpResponse response = client.execute(httpPost);


                // writing response to log
                Log.d("Response from url:", response.toString());
                jsonStr = response.toString();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                HttpConnection ht = new HttpConnection();
                ht.getVehicle();
                JSONObject object = new JSONObject(jsonStr);
                //JSONObject jb1 = object.getJSONObject("response");

                JSONArray Vehicle = object.getJSONArray("data");
                for (int i = 0; i < Vehicle.length(); i++) {

                    JSONObject c = Vehicle.getJSONObject(i);
                    String Regno = c.getString("registration_no");
                    String brand = c.getString("brand_id");
                    String model = c.getString("model_id");
                    String fueltype = c.getString("type");
                    String variant = c.getString("variant");
                    HashMap<String, String> Vl = new HashMap<String, String>();
                    Vl.put("registration_no", Regno);
                    Vl.put("brand_id", brand);
                    Vl.put("model_id", model);
                    Vl.put("type", fueltype);
                    Vl.put("variant:", variant);
                    addVehiclelist.add(Vl);
                    values = new String[]{
                            "Registration No:" + Regno,
                            "Brand:" + brand,
                            "Model:" + model,
                            "Type:" + fueltype,
                            "Variant:" + variant,
                    };
                }


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

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
        }
    }

    private class Getbrands extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            HttpClient client = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet("http://garage.kaptastech.mobi/api/5k/master/brand");

            try {
                HttpResponse response = client.execute(httpGet);


                // writing response to log
                Log.d("Response from url:", response.toString());
                jsonStr = response.toString();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                HttpConnection ht = new HttpConnection();
                ht.getbrand();
                JSONObject object = new JSONObject(jsonStr);
                JSONArray brandArray = object.getJSONArray("data");

                brandListArray.clear();
                for (int i = 0; i < brandArray.length(); i++) {
                    JSONObject gb = brandArray.getJSONObject(i);
                    brandListArray.add(gb.getString("name"));
                    String[] brandStringArray = new String[brandListArray.size()];
                    brandStringArray = brandListArray.toArray(brandStringArray);
                    for(int i1=0;i1<brandStringArray.length; i1++){
                        Log.d("String is",(String)brandStringArray[i1]);
                    }

                }


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

            return null;
        }

        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, brandListArray );
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            AddspinnerMake.setAdapter(adapter);


        }
    }

private class Getmodels extends AsyncTask<Void,  Void, Void> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... arg0) {
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet("http://garage.kaptastech.mobi/api/5k/master/models/1");

        try {
            HttpResponse response = client.execute(httpGet);


            // writing response to log
            Log.d("Response from url:", response.toString());
            jsonStr = response.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            HttpConnection ht = new HttpConnection();
            ht.getmodel();
            JSONObject object = new JSONObject(jsonStr);
            JSONArray modelArray = object.getJSONArray("data");

            modelList.clear();
            for (int i = 0; i < modelArray.length(); i++) {
                JSONObject gm = modelArray.getJSONObject(i);
                modelList.add(gm.getString("name"));

            }


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

        return null;
    }

    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, modelList);
        AddspinnerModel.setAdapter(adapter);


    }
}

}

My logcat:

12/22 10:02:06: Launching app
$ adb shell am start -n "com.example.addvehicle/com.example.addvehicle.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 2991 on device MOTO_G4_PLUS [emulator-5554]
W/System: ClassLoader referenced unknown path: /data/app/com.example.addvehicle-1/lib/x86
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Swap behavior 1
E/EGL_emulation: tid 3011: eglSurfaceAttrib(1146): error 0x3009 (EGL_BAD_MATCH)
W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x9a8756e0, error=EGL_BAD_MATCH
D/Response from url:: org.apache.http.message.BasicHttpResponse@d24bd43
D/RESPONSE: {"status":1,"data":[{"id":1,"name":"AUDI","code":"AUDI","image":"","status":"1","created_at":"2016-09-27 00:07:38","updated_at":"2016-09-27 00:07:38"},{"id":2,"name":"Bravian Motor Works","code":"BMW","image":"","status":"1","created_at":"2016-09-27 00:07:58","updated_at":"2016-09-27 00:07:58"},{"id":3,"name":"AB Volvo","code":"VOLVO","image":"","status":"1","created_at":"2016-09-27 00:08:36","updated_at":"2016-09-27 00:08:36"},{"id":4,"name":"Ford Motor Company","code":"FORD","image":"","status":"1","created_at":"2016-09-27 00:11:51","updated_at":"2016-09-27 00:11:51"},{"id":5,"name":"Maruti Suzuki","code":"Maruti","image":"","status":"1","created_at":"2016-09-27 00:12:14","updated_at":"2016-09-27 00:12:14"}],"msg":"success","info":"data list"}
W/System.err: org.json.JSONException: Value org.apache.http.message.BasicHttpResponse@d24bd43 of type java.lang.String cannot be converted to JSONObject
W/System.err:     at org.json.JSON.typeMismatch(JSON.java:111)
W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:160)
W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:173)
W/System.err:     at com.example.addvehicle.MainActivity$Getbrands.doInBackground(MainActivity.java:335)
W/System.err:     at com.example.addvehicle.MainActivity$Getbrands.doInBackground(MainActivity.java:311)
W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:304)
W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
W/System.err:     at java.lang.Thread.run(Thread.java:761)
D/Response from url:: org.apache.http.message.BasicHttpResponse@94bea9f
D/RESPONSE: {"status":0,"data":[],"msg":"success","info":"data list"}
W/System.err: org.json.JSONException: Value org.apache.http.message.BasicHttpResponse@94bea9f of type java.lang.String cannot be converted to JSONObject
W/System.err:     at org.json.JSON.typeMismatch(JSON.java:111)
W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:160)
W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:173)
W/System.err:     at com.example.addvehicle.MainActivity$Getmodels.doInBackground(MainActivity.java:393)
W/System.err:     at com.example.addvehicle.MainActivity$Getmodels.doInBackground(MainActivity.java:369)
W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:304)
W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
W/System.err:     at java.lang.Thread.run(Thread.java:761)
Application terminated.

My new logcat after changing from from jsonStr=response.toString() to jsonStr=EntityUtils.toString(response.getEntity());

12/22 11:57:54: Launching app
$ adb push C:\Users\Arun\AndroidStudioProjects\Addvehicle\app\build\outputs\apk\app-debug.apk /data/local/tmp/com.example.addvehicle
$ adb shell pm install -r "/data/local/tmp/com.example.addvehicle"
Success


$ adb shell am start -n "com.example.addvehicle/com.example.addvehicle.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 2801 on device MOTO_G4_PLUS [emulator-5554]
I/art: Not late-enabling -Xcheck:jni (already on)
W/art: Unexpected CPU variant for X86 using defaults: x86
W/System: ClassLoader referenced unknown path: /data/app/com.example.addvehicle-1/lib/x86
I/InstantRun: Instant Run Runtime started. Android package is com.example.addvehicle, real application class is null.

              [ 12-22 11:58:02.648  1308: 1309 D/         ]
              HostConnection::get() New Host Connection established 0xb481c300, tid 1309
W/System: ClassLoader referenced unknown path: /data/app/com.example.addvehicle-1/lib/x86
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Swap behavior 1
E/EGL_emulation: tid 2826: eglSurfaceAttrib(1146): error 0x3009 (EGL_BAD_MATCH)
W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x9147ed00, error=EGL_BAD_MATCH
D/Response from url:: org.apache.http.message.BasicHttpResponse@b2c650d
D/RESPONSE: {"status":1,"data":[{"id":1,"name":"AUDI","code":"AUDI","image":"","status":"1","created_at":"2016-09-27 00:07:38","updated_at":"2016-09-27 00:07:38"},{"id":2,"name":"Bravian Motor Works","code":"BMW","image":"","status":"1","created_at":"2016-09-27 00:07:58","updated_at":"2016-09-27 00:07:58"},{"id":3,"name":"AB Volvo","code":"VOLVO","image":"","status":"1","created_at":"2016-09-27 00:08:36","updated_at":"2016-09-27 00:08:36"},{"id":4,"name":"Ford Motor Company","code":"FORD","image":"","status":"1","created_at":"2016-09-27 00:11:51","updated_at":"2016-09-27 00:11:51"},{"id":5,"name":"Maruti Suzuki","code":"Maruti","image":"","status":"1","created_at":"2016-09-27 00:12:14","updated_at":"2016-09-27 00:12:14"}],"msg":"success","info":"data list"}
D/String is: AUDI
D/String is: AUDI
D/String is: Bravian Motor Works
D/String is: AUDI
D/String is: Bravian Motor Works
D/String is: AB Volvo
D/String is: AUDI
D/String is: Bravian Motor Works
D/String is: AB Volvo
D/String is: Ford Motor Company
D/String is: AUDI
D/String is: Bravian Motor Works
D/String is: AB Volvo
D/String is: Ford Motor Company
D/String is: Maruti Suzuki
D/Response from url:: org.apache.http.message.BasicHttpResponse@8d3b727
D/RESPONSE: {"status":0,"data":[],"msg":"success","info":"data list"}
E/EGL_emulation: tid 2826: eglSurfaceAttrib(1146): error 0x3009 (EGL_BAD_MATCH)
W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x900e8900, error=EGL_BAD_MATCH
D/OpenGLRenderer: endAllActiveAnimators on 0x90406800 (DropDownListView) with handle 0x900e9b30
E/EGL_emulation: tid 2826: eglSurfaceAttrib(1146): error 0x3009 (EGL_BAD_MATCH)
W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x900e8a00, error=EGL_BAD_MATCH
E/EGL_emulation: tid 2826: eglSurfaceAttrib(1146): error 0x3009 (EGL_BAD_MATCH)
W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x900e8ba0, error=EGL_BAD_MATCH
D/gralloc_ranchu: gralloc_unregister_buffer: exiting HostConnection (is buffer-handling thread)
W/IInputConnectionWrapper: finishComposingText on inactive InputConnection
E/EGL_emulation: tid 2826: eglSurfaceAttrib(1146): error 0x3009 (EGL_BAD_MATCH)
W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x900e8b40, error=EGL_BAD_MATCH
W/IInputConnectionWrapper: finishComposingText on inactive InputConnection
D/Response from url:: org.apache.http.message.BasicHttpResponse@648015e
D/RESPONSE: {"status":1,"data":[{"id":8,"user_id":"5","brand_id":"3","model_id":"1","registration_no":"TN47T1020","year":"2016","color":"","type":"2","variant":"1","door_mats":"0","audio_systems":"0","front_speaker":"0","back_speaker":"0","led_screen":"0","alloy":"0","status":"1","created_at":"2016-12-01 11:10:48","updated_at":"2016-12-01 11:10:48","brand":{"id":3,"name":"AB Volvo","code":"VOLVO","image":"","status":"1","created_at":"2016-09-27 00:08:36","updated_at":"2016-09-27 00:08:36"},"vehicle_model":{"id":1,"brand_id":"2","name":"BMW 320 D","code":"320 D","type":"3","image":"","status":"1","created_at":"2016-09-27 00:13:24","updated_at":"2016-09-29 04:56:55"}}],"msg":"success","info":"records found"}
W/System.err: org.json.JSONException: Value {"user_id":["The user id field is required."],"brand":["The brand must be a number."],"model":["The model must be a number."],"type":["The type must be a number."],"year":["The year must be a number."],"variant":["The variant must be a number."]} at data of type org.json.JSONObject cannot be converted to JSONArray
W/System.err:     at org.json.JSON.typeMismatch(JSON.java:100)
W/System.err:     at org.json.JSONObject.getJSONArray(JSONObject.java:588)
W/System.err:     at com.example.addvehicle.MainActivity$GetVehicle.doInBackground(MainActivity.java:273)
W/System.err:     at com.example.addvehicle.MainActivity$GetVehicle.doInBackground(MainActivity.java:227)
W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:304)
W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
W/System.err:     at java.lang.Thread.run(Thread.java:761)
D/RESPONSE: {"status":1,"data":[{"id":8,"user_id":"5","brand_id":"3","model_id":"1","registration_no":"TN47T1020","year":"2016","color":"","type":"2","variant":"1","door_mats":"0","audio_systems":"0","front_speaker":"0","back_speaker":"0","led_screen":"0","alloy":"0","status":"1","created_at":"2016-12-01 11:10:48","updated_at":"2016-12-01 11:10:48","brand":{"id":3,"name":"AB Volvo","code":"VOLVO","image":"","status":"1","created_at":"2016-09-27 00:08:36","updated_at":"2016-09-27 00:08:36"},"vehicle_model":{"id":1,"brand_id":"2","name":"BMW 320 D","code":"320 D","type":"3","image":"","status":"1","created_at":"2016-09-27 00:13:24","updated_at":"2016-09-29 04:56:55"}}],"msg":"success","info":"records found"}
1
  • There is lot of questions about it you can google it.. you are getting responce which is cannot be converted into JSONObject which String should looks like {"data" : "content" } if it is not you ll get an error.. Commented Dec 22, 2016 at 5:08

1 Answer 1

1

Here is the mistake

jsonStr = response.toString();

You are calling toString() on HttpResponse object. Instead you have to extract the response content from HttpResponse like below :

jsonStr = EntityUtils.toString(response.getEntity());


Answer to the new error after making the above changes :

After going through the error logs, I can say there is some validation checks at server end. If the request is not in a particular format it returns a JSON explaining which parameters violates the request format. From the logs, the server has returned the following JSON :

{
  "user_id": [
    "The user id field is required."
  ],
  "brand": [
    "The brand must be a number."
  ],
  "model": [
    "The model must be a number."
  ],
  "type": [
    "The type must be a number."
  ],
  "variant": [
    "The variant must be a number."
  ]
}

You have to handle this differently. As here the JSON values are arrays, not object. Consult your server-side developer and handle the responses accordingly.

Sign up to request clarification or add additional context in comments.

5 Comments

W/System.err: org.json.JSONException: Value {"user_id":["The user id field is required."],"brand":["The brand must be a number."],"model":["The model must be a number."],"type":["The type must be a number."],"variant":["The variant must be a number."]} at data of type org.json.JSONObject cannot be converted to JSONArray
I guess you are trying to assign the parsed JSON to JSONArray instead of JSONObject. As the JSON is enclosed within { and }, it is a JSONObject.
Monsish, can you please say me exactly where should i make the change as you said before?
Post the changes you done and the new error log in the question as an edit.
Manish, i have posted an edit off my new logcat error with the changes i have made as suggested by you.

Your Answer

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