我正在使用ParseObject来获取一些数据,每件事在循环上都很好,但是在循环之外似乎列表将被删除且大小为零,对此我感到疑惑!请帮帮我
public class frag1 extends Fragment {
public frag1() {
// Required empty public constructor
}
String TAG="val";
public static ArrayList<getData> data;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.fragment_frag1, container, false);
data=new ArrayList<getData>();
ListView list=(ListView)v.findViewById(R.id.list);
list.setAdapter(new listAdapter());
ParseQuery<ParseObject> query = ParseQuery.getQuery("mPlayDataBase");
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> obj, ParseException e) {
if (e == null) {
for(ParseObject po:obj){
String st1=(String) po.getString("name");
String st2=(String) po.getString("family");
String st3=(String) po.getString("phone");
data.add(new getData(st1,st2,st3));
Log.v(TAG,"size "+ data.size());//the size here is 3 and this is right
}
} else {
Log.v(TAG,"WRONG VALUE");
}
}
});
Log.v(TAG,"size2 "+ data.size());//the problem is here,size is 0
return v;
最佳答案
问题是query.findInBackground()
异步执行代码,因此它将触发调用而无需等待提取完成,然后直接继续执行此行Log.v(TAG,"size2 "+ data.size());//the problem is here,size is 0
然后,在提取完成后,会调用done()
,然后您会看到它包含3个元素,
那么如何解决呢?
将您的代码移至done()
或将其放入函数中,然后在done()
中调用该函数
希望这可以帮助!