我在Facebook的代码中使用了一个arraylist的问题。 公共类Facebook {
//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变空。 如何解决此问题?
答案 0 :(得分:0)
如果我没有弄错的话,您的HashMap
应该用
HashMap<String,String> postsMap = new HashMap<String,String>();
然后,您应该在调用postsMap
put()
变量
postsMap.put(TAG_MESSAGE, message);
postsMap.put(TAG_CREATION, createdTime);
答案 1 :(得分: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();
}
我用方法.executeAndWait()更改了.executeAsynk()因为我已经在asyncTask中了。