Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2

i wanna to pass List of Student as List from AsyncTask to Activity using Gson library

But it gives me the following error :

ERROR LOG :

       FATAL EXCEPTION: main
   java.lang.RuntimeException: Unable to start activity ComponentInfo{com.hesham.sams/com.hesham.sams.ListActivity1}: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
    at android.app.ActivityThread.access$700(ActivityThread.java:140)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:4921)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
    at dalvik.system.NativeStart.main(Native Method)
   Caused by: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:176)
    at com.google.gson.Gson.fromJson(Gson.java:803)
    at com.google.gson.Gson.fromJson(Gson.java:768)
    at com.google.gson.Gson.fromJson(Gson.java:717)
    at com.google.gson.Gson.fromJson(Gson.java:689)
    at com.hesham.sams.ListActivity1.getNames(ListActivity1.java:171)
    at com.hesham.sams.ListActivity1.onCreate(ListActivity1.java:68)
    at android.app.Activity.performCreate(Activity.java:5206)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2074)
    ... 11 more
   Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2
    at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:374)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:165)
    ... 20 more

My AsyncTask Full class :

public class GetListAsync extends AsyncTask<Void, Void, ArrayList<Student>> {

private Activity activity;
private  ProgressDialog progressDialog;
 Context context;


public GetListAsync(Activity activity, ProgressDialog progressDialog, Context context) {
    super();
    this.progressDialog = progressDialog;
    this.activity = activity;
    this.context = context;
}
 private Student get(String s) {

    return new Student(s);

}

@Override
protected ArrayList<Student> doInBackground(Void... voids) {

    ArrayList<Student> StudentIdList = new ArrayList<Student>();
    ArrayList<Student> StudentNamesList = new ArrayList<Student>();

    SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(context);
    String TID = prefs.getString("TID", null);
 SoapObject request2 = new SoapObject(NAMESPACE2, METHOD_NAME2);
        PropertyInfo pi2 = new PropertyInfo();
        pi2.setName("TID");
        pi2.setValue(Integer.parseInt(TID.toString()));
        pi2.setType(Integer.class);
        request2.addProperty(pi2);
        SoapSerializationEnvelope envelope2 = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
        envelope2.setOutputSoapObject(request2);
        HttpTransportSE androidHttpTransport2 = new HttpTransportSE(URL2);

        try {

            androidHttpTransport2.call(SOAP_ACTION2, envelope2);

            KvmSerializable result = (KvmSerializable) envelope2.bodyIn;

            String str = null;
            for (int i = 0; i < result.getPropertyCount(); i++) {
                str = ((String) result.getProperty(i).toString());

                StudentIdList.add(get(str));

            }
            return StudentIdList;
        } catch (Exception e) {

        }

        return  StudentIdList;
}

@Override
protected void onPostExecute(ArrayList<Student> result) {

    GsonBuilder gsonb = new GsonBuilder();
    Gson gson = gsonb.create();
    String json = gson.toJson(result);
    SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(context);
    prefs.edit().putString("studentnames", json).commit();



     activity.startActivity(new Intent(activity, ListActivity1.class));

    progressDialog.dismiss();
}

}

Here is ListView1 Activity method that's should return or get that list from AsyncTask: Note : I think the error cused from here in comment

 public List<Student> getNames() {
SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(getApplicationContext());

    Gson gson = new Gson();
    String result = prefs.getString("studentnames", null);

    Student obj = gson.fromJson(result, Student.class); // MayBe the error   here in class type 

    Toast.makeText(getApplicationContext(), obj.toString(),
            Toast.LENGTH_LONG).show();
return (List<Student>) obj;
}

I need you help cuz it's first time to use Gson Library .

like image 438
hesham Avatar asked Sep 10 '13 02:09

hesham


1 Answers

You serialized a list of Student instances but you try to deserialize a single Student from your saved string. Try this instead:

Gson gson = new Gson();
String result = prefs.getString("studentnames", null);

ArrayList<Student> list = new ArrayList<Student>();
Type listType = new TypeToken<List<Student>>() {}.getType();
list = gson.fromJson(result, listType);
like image 62
giampaolo Avatar answered Nov 15 '22 08:11

giampaolo