Return 解析查询数据从辅助class到我的activity

Return Parse query data from an auxiliary class to my activity

我正在从数据库获取数据,并填充 ArrayList

变量ArrayList类,填充在findInBackground范围内。我注意到该程序永远不会超出 findInBackground 范围,因此对于我的 activity

它永远不会 return 任何东西
 public ArrayList<Categorias> onCompleteGetData(String tableName) {

    ParseQuery<ParseObject> query = ParseQuery.getQuery(tableName);
    query.findInBackground((objects, e) -> {
        for (ParseObject objectList : objects) {
            Categorias categ = new Categorias();
            categ.setName(String.valueOf(objectList.get("name")));
            categ.setCategoriaId(String.valueOf(objectList.get("objectId")));
            this.categories.add(categ);
        }
    });

    return this.categories;
}

['House', 'loan', 'salary']

我的一部分activity

            if (value == -1){
                categorias = new ArrayList<>();
                CategoryController controller = new CategoryController(context);
                categorias = controller.onCompleteGetData(Utils.CATEGORIA_EXPENSE);
                Toast.makeText(context,  String.valueOf(controller.onCompleteGetData(Utils.CATEGORIA_DESPESA).size()), Toast.LENGTH_SHORT).show();
            }else if (value == +1){
                categorias = new ArrayList<>();
                CategoryController controller = new CategoryController(context);
                categorias = controller.onCompleteGetData(Utils.CATEGORIA_REVENUE);
                Toast.makeText(context, String.valueOf(controller.onCompleteGetData(Utils.CATEGORIA_RECEITA).size()), Toast.LENGTH_SHORT).show();
            }

由于您使用的是 findInBackground 方法,"return this.categories;" 比您的循环早 运行(因此返回一个空列表)。修复代码的更简单方法是使用 find 方法而不是 findInBackground。

public ArrayList<Categorias> onCompleteGetData(String tableName) {

  ParseQuery<ParseObject> query = ParseQuery.getQuery(tableName);
  List<ParseObject> objectList = query.find();

  for (ParseObject objectList : objects) {
    Categorias categ = new Categorias();
    categ.setName(String.valueOf(objectList.get("name")));
    categ.setCategoriaId(String.valueOf(objectList.get("objectId")));
    this.categories.add(categ);
  }

  return this.categories;
}