JSON Object null Android AsyncTask

2019-08-14 22:28发布

i want to consume a rest service, download the json and put it in a object, then return it, but the object always return me null, this is the class:

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
Context ctx;

// constructor
public JSONParser(Context ctx) {

    this.ctx = ctx;

}

public JSONObject getJSONFromUrl(String url) {

    AsyncjSONTask task = new AsyncjSONTask();

    task.execute(url);

    return jObj;

}

private class AsyncjSONTask extends AsyncTask<String, Void, JSONObject>{



    @Override
    protected JSONObject doInBackground(String... params) {

        String url = params[0];
        InputStream is = null;
        // Making HTTP request
                try {
                    // defaultHttpClient
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost(url);

                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    is = httpEntity.getContent();           

                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                JSONObject jObjOut = null;
                try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
                    StringBuilder sb = new StringBuilder();
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    is.close();
                    json = sb.toString();
                } catch (Exception e) {
                    Log.e("Buffer Error", "Error converting result " + e.toString());
                }

                // try parse the string to a JSON object
                try {
                    jObjOut = new JSONObject(json);

                } catch (JSONException e) {
                    Log.e("JSON Parser", "Error parsing data " + e.toString());
                }
        return jObjOut;
    }

    @Override
    protected void onPostExecute(JSONObject jObjIn) {

        jObj = jObjIn;
    }

}

}

if there's another way to consume rest services, please tell me.

1条回答
不美不萌又怎样
2楼-- · 2019-08-14 22:51
  1. Please make sure you want to do a HTTP POST and not a GET.
  2. Before reading the response it is a good idea to check what the HTTP Response status was
  3. Don't wrap your Async code in a non-async class? It seems you are getting confused and calling it as if its not async.

Your JSONParser class is assuming the AsyncTask is NOT Async when in fact it is. Here is an example of how you would do what you are trying to do:

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        new AsyncJsonTask(this).execute();

    }

    public void doSomethingWithTheResult(JsonObject result) {
        // Show the result on the View or do whatever with it.
    }

    private class AsyncJsonTask extends AsyncTask<String, Void, JsonObject> {

        private MainActivity _activity;

        public AsyncJsonTask(MainActivity activity) {
            this._activity = activity;
        }

        @Override
        protected JsonObject doInBackground(String... params) {
            JsonObject outputObject = null;

            // Call your web service to return the output 
            // ...

            return outputObject
        }

        @Override
        protected void onPostExecute(JsonObject result) {
            _activity.doSomethingWithTheResult(result);
        }

    }
}
查看更多
登录 后发表回答