hardanger
hardanger

Reputation: 2617

Perform an API request outside of the activity in Android

Summary of issue

I'd like a standard Java class to return LinkedIn API results to the current Activity.

Current progress

So far, I have been able to do this with the API call within the Activity.

I have been working from this tutorial, attempting to separate out the API functionality within the HomePage activity: https://www.studytutorial.in/linkedin-integration-and-login-in-android-tutorial

private Context activityContext;


public ApiSearchLinkedin(String query, Context activityContextIn) {
    // Initialize the progressbar
    progress= new ProgressDialog(theActivity);
    progress.setMessage("Retrieve data...");
    progress.setCanceledOnTouchOutside(false);
    progress.show();

    this.activityContext=activityContextIn;

    linkededinApiHelper(activityContext);
}

    public void linkededinApiHelper(Context activityContext){
        APIHelper apiHelper = APIHelper.getInstance(activityContext.getApplicationContext());
        apiHelper.getRequest(activityContext, url, new ApiListener() {
            @Override
            public void onApiSuccess(ApiResponse result) {
                try {
                    showResult(result.getResponseDataAsJson());
                    progress.dismiss();

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onApiError(LIApiError error) {
            }
        });
    }

What is currently going wrong

The returned results are currently just null as onApiSuccess() does not get called.

What I reckon might be the issue

My guess is that I'm not getting the Activity's context correctly, but this is just a guess.

Very many thanks for your help!

Upvotes: 0

Views: 634

Answers (1)

letsCode
letsCode

Reputation: 3036

Why not just use an AsyncTask?

private class Execute extends AsyncTask<Void, Void, Void> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... arg0) {
        HttpHandler httpHandler = new HttpHandler();

        String jsonString = httpHandler.makeServiceCall(jsonUrl);

        if (jsonString != null) {

            try {
                //Parse JSON
            } catch (JSONException e) {
                Log.i("Error: ", e.getMessage());
            }

        }

        return null;
    }

    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
    }
}

To use it....

new Execute().execute();

The HttpHandler class is this:

public class HttpHandler {

    private static final String TAG = HttpHandler.class.getSimpleName();

    public HttpHandler() {
    }

    public String makeServiceCall(String reqUrl) {
        String response = null;
        try {
            URL url = new URL(reqUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());
            response = convertStreamToString(in);
            in.close();
        } catch (MalformedURLException e) {
            Log.e(TAG, "MalformedURLException: " + e.getMessage());
        } catch (ProtocolException e) {
            Log.e(TAG, "ProtocolException: " + e.getMessage());
        } catch (IOException e) {
            Log.e(TAG, "IOException: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }

        return response;
    }

    private String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line).append('\n');
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();
    }
}

Upvotes: 1

Related Questions