一些片段代码
//定义个个获取查询出的数据的数量
private int carNum;
public int findCars(String goods_id, String user_id){
//--and条件1
BmobQuery eq1 = new BmobQuery("car");
eq1.addWhereEqualTo("goods_id", goods_id);
//--and条件2
BmobQuery eq2 = new BmobQuery("car");
eq2.addWhereEqualTo("user_id", user_id);
//整合成and条件
List> andQuerys = new ArrayList>();
andQuerys.add(eq1);
andQuerys.add(eq2);
//查询符合整个and条件的人
BmobQuery query = new BmobQuery("car");
query.and(andQuerys);
query.findObjects(context, new FindCallback() {
@Override
public void onSuccess(JSONArray arg0) {
Log.i("bmob", "for的legrnt::" + arg0.length() + "条数据。");
carNum=arg0.length();
}
@Override
public void onFailure(int arg0, String arg1) {
Log.i("bmob", "查询失败:");
}
});
Log.i("bmob", "count:" +carNum);
return carNum;
}
然后再另一个类中使用该方法,一个点击事件里
public void onClick(View v) {
//将商品的id和用户id存入数据库
if(User.getCurrentUser(context)== null){
Intent intent = new Intent(context, LoginActivity.class);
context.startActivity(intent);
}else {
//将商品的id存入数据库
CarDao carDao = new CarDao(context);
GoodsDao goodsDao=new GoodsDao(context);
//添加到购物车里
if(carDao.findCars(goodsId,user_id)<=0) {
Log.i("bmob", "进入for循环。。。。。。");
carDao.saveGoods(goodsId, User.getCurrentUser(context).getObjectId());
}else {
carDao.updateCar(carDao.getCarId(goodsId,user_id));
}
//商品可售数量减一
goodsDao.updateData(goodsId);
}
}
数据输出
for的legrnt::3
count:0
也就是说findCars(String goods_id, String user_id)方法中在onSuccess里成功对carNum赋值了,但是return回来后确实0.
在网上查了一些资料说是onSuccess异步加载的问题,
我试过用handler去获取,是可以获取得了在onSuccess里面的数据,但是handler里面的数据我又拿不出给主线程里的变量,还是为null
小弟我能力不够解决这个问题,这问题已经困扰我好几天天了,希望有大神可以帮下我。