2016-07-28 74 views
1

我有一个冻结我的应用程序分析查询:我可以在后台迭代吗?

ParseQuery<ParseObject> query = new ParseQuery<>("Puzzle"); 
query.whereEqualTo("puzzle", "somePuzzle"); 
query.findInBackground(new FindCallback<ParseObject>() { 
    public void done(List<ParseObject> objects, ParseException e) { 
     if (e == null) { 
      ArrayList<Puzzle> listPuzzle = new ArrayList<>(); 
      for (ParseObject object : objects) listPuzzle.add(new Puzzle(object)); 

      ListView list = (ListView) findViewById(R.id.list_puzzle); 
      if (list != null && listPuzzle.size() != 0) { 
       AdapterPuzzle adapterPuzzle = new AdapterPuzzle(listPuzzle, ScreenPuzzle.this); 
       list.setAdapter(adapterPuzzle); 
      } 
     } else e.printStackTrace(); 
    } 
}); 

当我这样做查询,活动几秒钟冻结,直到我有我的ListView填补。

我测试了运行查询而没有方法中的内容“完成”,它似乎运行顺畅,所以我的猜测是我的行为在“完成”方法冻结了活动,因为它可能会做得太多工作,特别是迭代器:

for (ParseObject object : objects) listPuzzle.add(new Puzzle(object)); 

有什么办法来运行这个迭代器或在后台这一切的行动?任何方法来避免这种冻结?

回答

1

尝试使用AsyncTask类。它有完全适合你的任务的doInBackground方法。

编辑:

我加入的人对我的代码的解决方案,需要一些参考:

public class ScreenPuzzle extends AppCompatActivity { 

    private ListView list; 
    private TextView textUnresolved; 
    private ProgressBar loading; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.screen_puzzle); 

     list = (ListView) findViewById(R.id.list_puzzle); 
     textUnresolved = (TextView) findViewById(R.id.text_unresolved); 
     loading = (ProgressBar) findViewById(R.id.loading_rank); 

     ParseQuery<ParseObject> query = new ParseQuery<>("Puzzle"); 
     query.whereEqualTo("puzzle", "somePuzzle"); 
     query.findInBackground(new FindCallback<ParseObject>() { 
      public void done(List<ParseObject> objects, ParseException e) { 
       if (e == null) new BackgroundOperation(objects).execute(); 
       else e.printStackTrace(); 
      } 
     }); 
    } 

    private class BackgroundOperation extends AsyncTask<Void, Void, ArrayList<Puzzle>> { 

     private List<ParseObject> objects; 
     private ArrayList<Puzzle> listPuzzle; 

     public BackgroundOperation(List<ParseObject> objects) { this.objects = objects; } 

     @Override 
     protected ArrayList<Puzzle> doInBackground(Void... voids) { 
      listPuzzle = new ArrayList<>(); 
      for (ParseObject object : objects) listPuzzle.add(new Puzzle(object)); 

      return listPuzzle; 
     } 

     @Override 
     protected void onPostExecute(ArrayList<Puzzle> listPuzzle) { 
      if (list != null && listPuzzle.size() != 0) { 
       final AdapterPuzzle adapterPuzzle = new AdapterPuzzle(listPuzzle, ScreenPuzzle.this); 
       list.setAdapter(adapterPuzzle); 
      } else textUnresolved.setVisibility(View.VISIBLE); 

      loading.setVisibility(View.GONE); 
     } 
    } 
} 
相关问题