我使用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;
答案 0 :(得分:1)
问题是query.findInBackground()
异步执行代码,因此它将触发调用而不等待提取完成,然后直接继续执行此行
Log.v(TAG,"size2 "+ data.size());//the problem is here,size is 0
然后,当完成提取时,调用done()
,然后您可以看到它有3个元素,
那么如何解决这个问题?
将您的代码移至done()
或将其放入函数并在done()
希望这有帮助!