我是android studio的新手,正在学习阶段。 我可以获取当前用户位置并将其存储在Parse服务器中。现在,我还在Parse数据库中的“医院”类中存储了一些超级市场的地理位置。现在,我正在尝试检索特定医院的地理位置,并试图比较当前用户与医院之间的距离。
当我尝试从Parse数据库中获取值时,它是在后台计算的,因此由于返回值将为null,因此我无法在其他函数中使用它来获取距离差。
使用以下代码:
class RemoteDataTask extends AsyncTask<Void, Void, Void> {
ProgressDialog mProgressDialog;
private Context context;
List<ParseUser> object = new ArrayList<>();
final ParseGeoPoint[] parlourUser = new ParseGeoPoint[1];
RemoteDataTask(Context context) {
Log.i("info", "Enetred RemoteDataTask");
this.context = context;
}
@Override protected Void doInBackground(Void... params) {
Log.i("info", "Entered doInbackground");
ParseQuery<ParseUser> query = ParseUser.getQuery();
try{
Log.i("info", "value is " + query.get("aifg14PNKz"));
object.set(1, query.get("aifg14PNKz"));
Log.i("info", "Object value" + object.get(1));
parlourUser[0] = object.get(0).getParseGeoPoint("Location");
Log.i("info", "Location of parlour user " + parlourUser[0]);
} catch (ParseException e) {
e.printStackTrace();
}
}
答案 0 :(得分:0)
首先,这是制作依赖于后台线程的函数的非常错误的做法。
query.getInBackground
它将在后台线程和
上运行后台查询完成后,此回调方法与UI线程通信
new GetCallback<ParseObject>() {
@Override
public void done(ParseObject object, ParseException e) {
}
如果 query.getInBackground 需要一些时间,则您的功能将无法正常工作。
两步解决您的问题
1)您可以在AsyncTask中调用它并在后台处理查询
// RemoteDataTask AsyncTask
ProgressDialog mProgressDialog;
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
private Context context;
List<ParseObject> object;
final ParseGeoPoint[] hospitalUser = new ParseGeoPoint[1];
RemoteDataTask(Context context) {
this.context = context;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(context);
// Set progressdialog title
mProgressDialog.setTitle("Title...");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
@Override
protected Void doInBackground(Void... params) {
// Create the array
try {
ParseQuery<ParseObject> query = ParseQuery.getQuery("Lakme");
object = query.find();
if (ob != null) {
hospitalUser[0] = object.getParseGeoPoint("Location");
//calculate distance
}
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
// Close the progressdialog
mProgressDialog.dismiss();
// You can use "hospitalUser" Object here.
}
}
从调用此方法的地方调用它
new RemoteDataTask(YourActivity.this).execute();
2)一旦查询得到结果,就计算距离