Skip to content Skip to sidebar Skip to footer

Android Rest Api Connection

I'm a little bit to stupid - sry for that. I wrote an API which gives some JSON back. My goal is to use this API from an Android App. I've tried it with AsyncTask but failed hard.

Solution 1:

I'm a little bit to stupid - sry for that.

Don't be silly, everyone has to start from somewhere when learning :)

As Bosko mentions, an AsyncTask is probably the best solution here because you need to take any I/O type operations off the main thread, otherwise the application will crash.

I answered a similar question a while back, but the same code applies, please see the below.

publicclassMainActivityextendsActivity {

    @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button = (Button) findViewById(R.id.btn);


        button.setOnClickListener(newView.OnClickListener() {
            @OverridepublicvoidonClick(View v) {
                String url = "http://date.jsontest.com";
                newMyAsyncTask().execute(url);
            }
        });


    }
    classMyAsyncTaskextendsAsyncTask<String,Void,JSONObject> {

        @OverrideprotectedJSONObjectdoInBackground(String... urls) {
            returnRestService.doGet(urls[0]);
        }

        @OverrideprotectedvoidonPostExecute(JSONObject jsonObject) {
            TextView tv = (TextView) findViewById(R.id.txtView);
            tv.setText(jsonObject.toString());
        }
    }

}

The onCreate sets an onClickListener onto a button, when the button is pressed a new AsyncTask is created and execute() is called.

The doInBackground runs on a separate thread so you can perform long running tasks here, such as calling your REST API and handling the response. See Boskos' answer for that bit of code.

The onPostExecute happens after the task is complete, so you can handle your JSON object here and update the UI as you need to.

If you haven't already done so, I'd highly suggest reading the AsyncTask docs.

Hope this helps

Solution 2:

In many application I used AsyncTask to communicate with API and IMO AsyncTask approach have a lot benefits. Here is example of AsyncTask which gets the JSON data over the API:

privateclassEventsAsyncTaskextendsAsyncTask<GetRequest, String, JSONObject>
    {
        @OverrideprotectedJSONObjectdoInBackground(GetRequest... params)
        {
            JSONObject data = null;

            GetRequest eventRequest = params[0];
            if (eventRequest instanceofGetRequest)
            {
                DefaultHttpClient httpClient = HttpClient.getHttpClientInstance();

                try
                {
                    HttpGet httpGet = HttpClient.getHttpGetInstance();
                    httpGet.setURI(eventRequest.getUriString());

                    httpGet.setHeader("Content-type", "application/json");

                    HttpResponse httpResponse = httpClient.execute(httpGet);

                    //Check is authentication to the server passedif (httpResponse.getStatusLine().getStatusCode() == 401)
                    {
                        // do some actions to clear userID, token etc ...// finish finish();
                    }

                    HttpEntity responseEntity = httpResponse.getEntity();

                    if (responseEntity instanceofHttpEntity)
                        data = newJSONObject(EntityUtils.toString(responseEntity));

                    responseEntity.consumeContent();
                }
                catch (ClientProtocolExceptionCPException)
                {
                    //set data to null, handle and log CPException
                }
                catch (IOException ioException)
                {
                  //set data to null, handle and log IOException
                }
                catch (JSONException jsonException)
                {
                  //set data to null, handle and log JSONException
                }
                catch (URISyntaxException useException)
                {
                  //set data to null, handle and log URISyntaxException
                }

            }
            return data;
        }
    }

You have to post your code and point to problem, then SO users can help you. Everything else is personally opinion based and it is not constructive.

Post a Comment for "Android Rest Api Connection"