0

我需要做什么来获取当前登录用户的用户 ID、Facebook 个人资料图片、电子邮件 ID 和地址。

一旦应用程序授权用户登录,我将在 Async Task 中调用以下方法,但它失败并抛出异常:-

“android.os.NetworkOnMainThreadException”

请查看我在 asynctask 的 doInBackground() 中执行的方法:-

private void callFBMethods() {

    try {
        response = facebook.request("/me");
        if(response!=null)
        {
            handler.sendEmptyMessage(0);
        }
        JSONObject json = Util.parseJson(response);
        mainURL = Constant.FB_PIC_URL+json.getString("id")+"/picture?type=small";
        //To registere new user here
        Vector<Object> userData = new Vector<Object>();
        userData.add(Constant.CURRENT_FLAG);

        userData.add(json.getString("username"));
        userData.add(json.getString("name"));
        userData.add(json.getString("id"));
        userData.add(mainURL);

        new AsynServices(mActivity, userData, 4).execute();
    } catch (Exception e) {
        // TODO: handle exception
        System.out.println("exception occurs:-"+e.getMessage());
    }   

}
4

1 回答 1

0

NetworkOnMainThreadException此错误是因为从 Android API 14 开始,您必须在 AsyncTask 中运行与互联网相关的代码。像这样你可以在 AsyncTask 中运行你的代码

private class Task extends AsyncTask<Void, Void, Void> {

   @Override
   protected String doInBackground(String... urls) {

      // call your methods from here

      try {
         response = facebook.request("/me");
         if(response!=null)
         {
            handler.sendEmptyMessage(0);
         }
         JSONObject json = Util.parseJson(response);
         mainURL = Constant.FB_PIC_URL+json.getString("id")+"/picture?type=small";
         //To registere new user here
         Vector<Object> userData = new Vector<Object>();
         userData.add(Constant.CURRENT_FLAG);

         userData.add(json.getString("username"));
         userData.add(json.getString("name"));
         userData.add(json.getString("id"));
         userData.add(mainURL);

         // instead of calling another Asynctask here just write related code here.

         new AsynServices(mActivity, userData, 4).execute();

     } catch (Exception e) {
         // TODO: handle exception
         System.out.println("exception occurs:-"+e.getMessage());
     } 
   }
}
于 2013-07-01T12:00:48.883 回答