Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json Parsing from Url In Android , Not working

I am parsing data from URL , Its Getting below mentioned Error.

Raw Data is Showing Perfectly from Server.Not able to Split the Data Using Json Parsing.

Please help me solve this error

EDIT : 1

Json Response from URL

[
    {
        "ID": 4,
        "Name": "Vinoth",
        "Contact": "1111111111",
        "Msg": "1"
    },
    {
        "ID": 5,
        "Name": "Mani",
        "Contact": "22222222",
        "Msg": "1"
    },
    {
        "ID": 6,
        "Name": "Manoj",
        "Contact": "33333333333",
        "Msg": "1"
    }
]

Error :

org.json.JSONException: Value [{"ID":1,"Name":"Lalita","Contact":"9997162499","Msg":"1"},{"ID":2,"Name":"kumar","Contact":"123456789","Msg":"1"}] of type java.lang.String cannot be converted to JSONArray
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at org.json.JSON.typeMismatch(JSON.java:111)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at org.json.JSONArray.<init>(JSONArray.java:96)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at org.json.JSONArray.<init>(JSONArray.java:108)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at com.knowledgeflex.restapidemo.MainActivity$LoadService.onPostExecute(MainActivity.java:135)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at com.knowledgeflex.restapidemo.MainActivity$LoadService.onPostExecute(MainActivity.java:58)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at android.os.AsyncTask.finish(AsyncTask.java:632)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at android.os.AsyncTask.access$600(AsyncTask.java:177)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at android.os.Looper.loop(Looper.java:136)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5584)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at java.lang.reflect.Method.invokeNative(Native Method)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at java.lang.reflect.Method.invoke(Method.java:515)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
12-11 18:23:27.259 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
12-11 18:23:27.259 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at dalvik.system.NativeStart.main(Native Method)

MainActivity.java

public class MainActivity extends Activity {

    TextView name1,email,status,face;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final Button GetServerData = (Button) findViewById(R.id.button1);


      name1 = (TextView)findViewById(R.id.sname);
       email = (TextView)findViewById(R.id.email);
         status = (TextView)findViewById(R.id.status);
       face = (TextView)findViewById(R.id.fb);

        GetServerData.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {

                // Server Request URL
                String serverURL = "http://webapp/api/values";

                // Create Object and call AsyncTask execute Method
                new LoadService().execute(serverURL);

            }
        });

    }


    // Class with extends AsyncTask class
    private class LoadService extends AsyncTask<String, Void, Void> {

        private final HttpClient Client = new DefaultHttpClient();
        private String Content;
        private String Error = null;
        private final String TAG = null;
        String name = null;
        private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);

        TextView uiUpdate = (TextView) findViewById(R.id.textView2);

        protected void onPreExecute() {
            // NOTE: You can call UI Element here.

            // UI Element
            uiUpdate.setText("");
            Dialog.setMessage("Loading service..");
            Dialog.show();
        }

        // Call after onPreExecute method
        protected Void doInBackground(String... urls) {
            try {

                // NOTE: Don't call UI Element here.

                HttpGet httpget = new HttpGet(urls[0]);
                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                Content = Client.execute(httpget, responseHandler);

            } catch (ClientProtocolException e) {
                Error = e.getMessage();
                cancel(true);
            } catch (IOException e) {
                Error = e.getMessage();
                cancel(true);
            }

            return null;
        }

        protected void onPostExecute(Void unused) {
            // Close progress dialog
            Dialog.dismiss();
            Log.e(TAG, "------------------------------------- Output: " + Content);


            try {
                JSONArray jArr=new JSONArray(Content);
                for(int i=0;i<jArr.length();i++) {
                    JSONObject json=jArr.getJSONObject(i);


                    name1.setText(json.getString("Name"));
                    email.setText(json.getString("ID"));
                    status.setText(json.getString("Contact"));
                    face.setText(json.getString("Msg"));

                }

            } catch (JSONException e) {
                e.printStackTrace();
                Log.i("EXCEPTION   ","");
            }

            uiUpdate.setText("Raw Output : " + Content);
        }



    }


}
like image 584
Kumar Avatar asked Dec 11 '15 13:12

Kumar


2 Answers

As per your response is JSONArray and gson library is better to use while json data parsing so use below class to any type of data like that

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;


public class ApiData {
    @SerializedName("data")
    @Expose
    private JsonArray Data;

    public <T> List<T> getData(Class<T> c) {
        Type type = new ListParams(c);
        return new Gson().fromJson(Data, type);
    }

    private class ListParams implements ParameterizedType {

        private Type type;

        private ListParams(Type type) {
            this.type = type;
        }

        @Override
        public Type[] getActualTypeArguments() {
            return new Type[]{type};
        }

        @Override
        public Type getRawType() {
            return ArrayList.class;
        }

        @Override
        public Type getOwnerType() {
            return null;
        }


        @Override
        public boolean equals(Object o) {
            return super.equals(o);
        }

    }
}

Create model class like :

public class Model{
   String ID;
   String Name;
   String Contact;
   String msg;
}

Now parse your data like:

ApiData apiData = new Gson().fromJson(Content, ApiData.class);
Lis<Model> models = apiData.getData(Model.class); 
like image 188
Hits Avatar answered Oct 24 '22 02:10

Hits


 try {
                Object jsonObject = new JSONTokener(Content).nextValue();
                JSONArray jArr=new JSONArray(jsonObject );
                for(int i=0;i<jArr.length();i++) {
                    JSONObject json=jArr.getJSONObject(i);
                    name1.setText(json.getString("Name"));
                    email.setText(json.getString("ID"));
                    status.setText(json.getString("Contact"));
                    face.setText(json.getString("Msg"));

                }

            } catch (JSONException e) {
                e.printStackTrace();
                Log.i("EXCEPTION   ","");
            }

Directly you cannot apply string to array, you should convert string to jsonobject ,then you can do object to array. Hope you understand

like image 41
learner Avatar answered Oct 24 '22 03:10

learner