2015-12-04 37 views
0

我在Facebook的代码中使用了arraylist的问题。全局变量在Facebook的GraphRequest后丢失值 - android

//this are global variable 
HashMap<String,String> postsMap = new HashMap<>(); 
ArrayList<HashMap<String, String>> list = new ArrayList<>(); 
... 
private void retrievePosts() { 
GraphRequest postsRequest = new GraphRequest(
      AccessToken.getCurrentAccessToken(), 
      "/{page-id}/", 
      null, 
      HttpMethod.GET, 
      new GraphRequest.Callback() { 
       public void onCompleted(GraphResponse response) { 
        Log.d("Facebook: ", response.toString()); 

        try { 
         JSONObject jobj = response.getJSONObject().getJSONObject(TAG_POST); 
         JSONArray posts = jobj.getJSONArray(TAG_DATA); 

         for (int i = 0; i < posts.length(); i++) { 
          JSONObject c = posts.getJSONObject(i); 

          String message = c.getString(TAG_MESSAGE); 
          String createdTime = c.getString(TAG_CREATION); 

          map.put(TAG_MESSAGE, message); 
          map.put(TAG_CREATION, createdTime); 


          list.add(postsMap); 

         } 

        } catch (JSONException e) { 
         e.printStackTrace(); 
        } 
       } 
      }); 
    Bundle parameters = new Bundle(); 
    parameters.putString("fields", "posts.limit(20)"); 
    postsRequest.setParameters(parameters); 
    postsRequest.executeAsync(); 
} 

当我尝试看看什么是列表Facebook的方法调用中,我可以看到正确的元素中,但在方法结束我的ArrayList成为空 公共类的Facebook {。 我该如何解决这个问题?

回答

0

我发现了一个分辨率为我问题。 问题是我在主线程中执行了一个asyncTask。我决定以这样的方式

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.list_view); 

    new RetrievePosts().execute(); 

} 
class RetrievePosts extends AsyncTask<String, String, String> { 

    @Override 
    protected String doInBackground(String... params) { 
     GraphRequest postsRequest = new GraphRequest(
     AccessToken.getCurrentAccessToken(), 
     "/{page-id}/", 
     null, 
     HttpMethod.GET, 
     new GraphRequest.Callback() { 
      public void onCompleted(GraphResponse response) { 
       Log.d("Facebook: ", response.toString()); 
       //my stuff 
      } 
     }); 
Bundle parameters = new Bundle(); 
parameters.putString("fields", "posts.limit(20)"); 
postsRequest.setParameters(parameters); 
postsRequest.executeAndWait(); 
} 

我已经改变.executeAsynk()与方法.executeAndWait(),因为我已经的AsyncTask我。

0

如果我没有记错的话,你的HashMap应与

HashMap<String,String> postsMap = new HashMap<String,String>(); 

,那么你应该用你的电话你postsMap变量初始化为put()

postsMap.put(TAG_MESSAGE, message); 
postsMap.put(TAG_CREATION, createdTime); 
+0

我在我的应用程序中写了正确的构造函数,这是一个复制错误。 – Daniel