0

I'm working on integrating Google app indexing into my android app that will take the URL, query the server for the internal ID of the article, then open that article. I'm a little confused on how to accomplish this though as I don't have as much experience with network calls.

  private void openAppIndexedArticle(String data) {
    HomeActivity home = getActivity();
    MyFragment currentFragment = home.getCurrentFragment();
    MyHandler handler = MyHandler.getInstance(mActivity.get());
    String articleUrn = handler.getArticleUrnFromUrl(data);
    ReadingFragment readingFragment = ReadingFragment.createInstance(articleUrn);
    home.openFragment(readingFragment);
  }

Here is where I need to fetch the ID in MyHandler

public String getArticleUrnFromUrl(String url) {
  HttpResponse response = performGET(storyUrl);
  if (response != null) {
    if (response.getStatusLine().getStatusCode() == 200) {
      GzipResponse gzip = new GzipResponse(response);
      InputStream is = gzip.getContent();
      try {
        String json = IOUtils.toString(is);
        JSONObject object = new JSONObject(json);
        String id = object.optString("articleId");
        gzip.close();
        return new Urn(id, LiEntityType.ARTICLE).toString();
      } catch (IOException e) {
        e.printStackTrace();
      } catch (JSONException e) {
        e.printStackTrace();
      }
    }
  }
  return null;
}

Now when I try this, it gives me a NetworkOnMainThreadException which is understandable since it is on the main thread. Whenever I look up AsyncTasks for accomplishing this, I don't understand how they get the data back since the only thing the app is supposed to do right now is open that article - it needs to wait for the request to finish anyway, right? Is this an error I should suppress and just put up a loading screen until it finishes? Any suggestions would be greatly appreciated.

Thanks.

rakoonise
  • 529
  • 3
  • 16
  • 1
    Did you even read AsyncTask documentation ? – Shumail Jul 28 '14 at 19:40
  • AsyncTask.get() seems to accomplish what I wanted but I just felt it defeated the purpose of running something in the background if you're waiting for it anyway. I was just hoping for some explanation on best practices for this sort of issue instead of something like populating a list or object that doesn't require all the data right away. – rakoonise Jul 28 '14 at 19:46
  • call the asynctask then do whatever you need to in the onPostExecute, there is no other way – tyczj Jul 28 '14 at 19:48

0 Answers0