多次调用AsyncTask with Parser时的com.google.gson.JsonSyntaxException

时间:2015-08-19 11:54:33

标签: android parsing android-asynctask gson

我正在使用AsyncTask从后端服务器检索数据并使用gson解析器解析它。我多次执行AsyncTask时收到com.google.gson.JsonSyntaxException

这是我的Async解析器

public class ParseTask extends AsyncTask<String, Void, JsonObject> {

public JsonObject jsonObject;
String url;

@Override
protected JsonObject doInBackground(String... arg0) {
    url = arg0[0];
    try {
        URL uRL = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) uRL.openConnection();
        connection.connect();
        JsonParser parser = new JsonParser();
        jsonObject = parser.parse(new InputStreamReader((InputStream) connection.getContent())).getAsJsonObject();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return jsonObject;
}

@Override
protected void onPostExecute(JsonObject json) {
    super.onPostExecute(json);
}

}

这是我的主要活动

public class DrillOneFragment extends Activity {

private static String url = "abc";
private static final String TAG_YEAR = "year";
LayoutParams params;
View view;
private JsonObject result;
String q;
String[] qq = { "2013", "2014" };

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.a);
    for (int i = 0; i < 2; i++) {
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair(TAG_YEAR, qq[i]));
    String paramString = URLEncodedUtils.format(params, "utf-8");
    url += "?" + paramString;
    try {
        result = new ParseTask().execute(url).get();
        Log.e(qq[i], result.toString());
    } catch (Exception e) {
        e.printStackTrace();
        }
    }
}

}

这是我的logcat

08-19 17:14:51.937: W/System.err(14735): 

com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 6 path $
08-19 17:14:51.937: W/System.err(14735):    at com.google.gson.JsonParser.parse(JsonParser.java:65)
08-19 17:14:51.937: W/System.err(14735):    at com.example.tester.ParseTask.doInBackground(ParseTask.java:25)
08-19 17:14:51.937: W/System.err(14735):    at com.example.tester.ParseTask.doInBackground(ParseTask.java:1)
08-19 17:14:51.937: W/System.err(14735):    at android.os.AsyncTask$2.call(AsyncTask.java:288)
08-19 17:14:51.937: W/System.err(14735):    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
08-19 17:14:51.937: W/System.err(14735):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
08-19 17:14:51.937: W/System.err(14735):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
08-19 17:14:51.937: W/System.err(14735):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
08-19 17:14:51.937: W/System.err(14735):    at java.lang.Thread.run(Thread.java:841)
08-19 17:14:51.937: W/System.err(14735): Caused by: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 6 path $
08-19 17:14:51.937: W/System.err(14735):    at com.google.gson.stream.JsonReader.syntaxError(JsonReader.java:1573)
08-19 17:14:51.937: W/System.err(14735):    at com.google.gson.stream.JsonReader.checkLenient(JsonReader.java:1423)
08-19 17:14:51.937: W/System.err(14735):    at com.google.gson.stream.JsonReader.doPeek(JsonReader.java:546)
08-19 17:14:51.937: W/System.err(14735):    at com.google.gson.stream.JsonReader.peek(JsonReader.java:429)
08-19 17:14:51.937: W/System.err(14735):    at com.google.gson.JsonParser.parse(JsonParser.java:60)
08-19 17:14:51.937: W/System.err(14735):    ... 8 more
08-19 17:14:51.937: W/System.err(14735): java.lang.NullPointerException
08-19 17:14:51.937: W/System.err(14735):    at com.example.tester.DrillOneFragment.onCreate(DrillOneFragment.java:41)
08-19 17:14:51.937: W/System.err(14735):    at android.app.Activity.performCreate(Activity.java:5248)
08-19 17:14:51.937: W/System.err(14735):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
08-19 17:14:51.937: W/System.err(14735):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2162)
08-19 17:14:51.937: W/System.err(14735):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2247)
08-19 17:14:51.937: W/System.err(14735):    at android.app.ActivityThread.access$800(ActivityThread.java:141)
08-19 17:14:51.937: W/System.err(14735):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
08-19 17:14:51.937: W/System.err(14735):    at android.os.Handler.dispatchMessage(Handler.java:102)
08-19 17:14:51.937: W/System.err(14735):    at android.os.Looper.loop(Looper.java:136)
08-19 17:14:51.937: W/System.err(14735):    at android.app.ActivityThread.main(ActivityThread.java:5050)
08-19 17:14:51.937: W/System.err(14735):    at java.lang.reflect.Method.invokeNative(Native Method)
08-19 17:14:51.937: W/System.err(14735):    at java.lang.reflect.Method.invoke(Method.java:515)
08-19 17:14:51.937: W/System.err(14735):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-19 17:14:51.937: W/System.err(14735):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
08-19 17:14:51.937: W/System.err(14735):    at dalvik.system.NativeStart.main(Native Method)

提前感谢。

2 个答案:

答案 0 :(得分:0)

你误用了对AsyncTask类的调用,你必须实例化该类,然后定义参数,连接并最终获取JSON对象。最后记得使用motodo onPostExecute()作为输出。你可能不会

result = new ParseTask().execute(url).get();

您必须执行以下操作。这段代码对我来说很好

private class GetArticulosParam extends AsyncTask<String, Void, Void> {
    public GetArticulosParam() {
        contactList = new ArrayList<HashMap<String, String>>();
    }
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Por Favor, Espere...");
        pDialog.setCancelable(true);
        pDialog.show();
    }
    @Override
    protected Void doInBackground(String... arg0) {

        // String
        // url1="http://pracsysonline.dyndns.org/ListaArticulos/consultaParam.php";
        String url1 = "http://"+direccion+"/ListaArticulos/consultaParam.php";
        String param = arg0[0];
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("param", param));
        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();
        // Making a request to url and getting response
        String jsonStr =sh.makeServiceCall(url1,ServiceHandler.POST,params);
        Log.d("Response: ", "> " + jsonStr);
        if (jsonStr != null) {
            try {
                // Getting JSON Array node
                contacts = new JSONArray(jsonStr);
                // looping through All Contacts
                for (int i = 0; i < contacts.length(); i++) {
                    JSONObject c = contacts.getJSONObject(i);
                    String id = c.getString(TAG_DESC);
                    String name = c.getString(TAG_CODE);

                    HashMap<String, String> contact = new HashMap<String, String>();

                    Log.e("PRUEBA", img);
                    // adding each child node to HashMap key => value
                    contact.put(TAG_DESC, id);
                    contact.put(TAG_CODE, name);
                    contactList.add(contact);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        miAdapter = new ListViewAdapter(MainActivity.this, contactList);
        setListAdapter(miAdapter);
        pDialog.dismiss();
    }
}

然后是ServiceHandler类

public class ServiceHandler {

static String response = null;
public final static int GET = 1;
public final static int POST = 2;

public ServiceHandler() {

}

/*
 * Making service call
 * @url - url to make request
 * @method - http request method
 * */
public String makeServiceCall(String url, int method) {
    return this.makeServiceCall(url, method, null);
}

/*
 * Making service call
 * @url - url to make request
 * @method - http request method
 * @params - http request params
 * */
public String makeServiceCall(String url, int method,
        List<NameValuePair> params) {
    try {
        // http client
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpEntity httpEntity = null;
        HttpResponse httpResponse = null;

        // Checking http request method type
        if (method == POST) {
            HttpPost httpPost = new HttpPost(url);
            // adding post params
            if (params != null) {
                UrlEncodedFormEntity encodedEntity = new UrlEncodedFormEntity(params,"UTF-8");
                encodedEntity.setContentEncoding(HTTP.UTF_8);
                httpPost.setEntity(encodedEntity);
                //httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));
            }

            httpResponse = httpClient.execute(httpPost);

        } else if (method == GET) {
            // appending params to url
            if (params != null) {
                String paramString = URLEncodedUtils
                        .format(params, "utf-8");
                url += "?" + paramString;
            }
            HttpGet httpGet = new HttpGet(url);

            httpResponse = httpClient.execute(httpGet);

        }
        //codigo pruebna
        response = new Scanner(httpResponse.getEntity().getContent(),"UTF-8").useDelimiter("\\A").next();
        /*httpEntity = httpResponse.getEntity();
        response = EntityUtils.toString(httpEntity,"utf-8");*/

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return response;

}

}

答案 1 :(得分:0)

我认为您使用的AsyncTask工作类也是错误的,您必须执行以下操作

protected void onPostExecute(JsonObject json) {
super.onPostExecute(json);
result=json;

}

然后你应该从onPostExecute工作来做我应该做的事情,记住作为辅助线程代码块,主线程仍然在运行,因此会生成NullPointer。你将是空的访问对象。这就是为什么我们必须使用onPostExecute