在Android中的活动之外执行API请求

时间:2018-02-05 14:19:07

标签: java android linkedin linkedin-api

问题摘要

我想要一个标准的Java类来将LinkedIn API结果返回到当前的Activity。

当前进度

到目前为止,我已经能够通过Activity中的API调用来完成此操作。

我一直在使用本教程,试图在HomePage活动中分离出API功能: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) {
            }
        });
    }

目前出现了什么问题

返回的结果当前为null,因为onApiSuccess()没有被调用。

我认为可能是问题

我的猜测是我没有正确地获取活动的上下文,但这只是猜测。

非常感谢你的帮助!

1 个答案:

答案 0 :(得分:1)

为什么不使用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);
    }
}

使用它....

new Execute().execute();

HttpHandler类是这样的:

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();
    }
}