user3136622
user3136622

Reputation: 41

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.

I imagine to use it like this:

Here's the link to the API: Link

What do I have to do?

EDIT:

Here's my code now. He doesn't like the GetRequest variable type, also getHttpClientInstance is not possible. He also cannot resolve the method execute on MyAsyncTask.

@Override
public boolean onOptionsItemSelected(MenuItem item) {        
    if (item.getItemId() == R.id.action_settings) startActivity(new Intent(this, editPreference.class));
    if (item.getItemId() == R.id.action_kurse) startActivity(new Intent(this, Login.class));
    if (item.getItemId() == R.id.action_refresh) {
        String url = "http://vplan.florian-schmidt.org/api/get_klassen.php";
        new MyAsyncTask().execute(url);
    };
    return super.onOptionsItemSelected(item);
}

class MyAsyncTask extends AsyncTask <GetRequest,String,JSONObject> {

    @Override
    protected JSONObject doInBackground(GetRequest... params)
    {
        JSONObject data = null;

        GetRequest eventRequest = params[0];
        if (eventRequest instanceof GetRequest)
        {
            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 passed
                if (httpResponse.getStatusLine().getStatusCode() == 401)
                {
                    // do some actions to clear userID, token etc ...
                    // finish
                    finish();
                }

                HttpEntity responseEntity = httpResponse.getEntity();

                if (responseEntity instanceof HttpEntity)
                    data = new JSONObject(EntityUtils.toString(responseEntity));

                responseEntity.consumeContent();
            }
            catch (ClientProtocolException CPException)
            {
                //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;
    }

    @Override
    protected void onPostExecute(JSONObject jsonObject) {
        TextView tv = (TextView) findViewById(R.id.textView);
        tv.setText(jsonObject.toString());
    }


}

Upvotes: 4

Views: 7013

Answers (2)

Jimmy
Jimmy

Reputation: 16428

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.

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

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


        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = "http://date.jsontest.com";
                new MyAsyncTask().execute(url);
            }
        });


    }
    class MyAsyncTask extends AsyncTask<String,Void,JSONObject> {

        @Override
        protected JSONObject doInBackground(String... urls) {
            return RestService.doGet(urls[0]);
        }

        @Override
        protected void onPostExecute(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

Upvotes: 1

Bosko Mijin
Bosko Mijin

Reputation: 3331

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:

private class EventsAsyncTask extends AsyncTask<GetRequest, String, JSONObject>
    {
        @Override
        protected JSONObject doInBackground(GetRequest... params)
        {
            JSONObject data = null;

            GetRequest eventRequest = params[0];
            if (eventRequest instanceof GetRequest)
            {
                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 passed
                    if (httpResponse.getStatusLine().getStatusCode() == 401)
                    {
                        // do some actions to clear userID, token etc ...
                        // finish 
                        finish();
                    }

                    HttpEntity responseEntity = httpResponse.getEntity();

                    if (responseEntity instanceof HttpEntity)
                        data = new JSONObject(EntityUtils.toString(responseEntity));

                    responseEntity.consumeContent();
                }
                catch (ClientProtocolException CPException)
                {
                    //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.

Upvotes: 0

Related Questions