我正在使用 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()
是异步执行代码的,所以会触发调用,不等待fetching完成,直接继续执行这一行
Log.v(TAG,"size2 "+ data.size());//问题来了,size为0
然后当抓取完成时调用 done()
然后你可以看到它有 3 个元素,
那么如何解决呢?
将您的代码移至done()
或将其放入函数中并在done()
中调用该函数
希望这对您有所帮助!
关于java - ArrayList 大小在循环外为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47958668/