我正在尝试为 Android Java JsonObjectRequests 实现回调。我发现几十个帖子显示的代码几乎是逐字记录的。我的问题是它callback
是空的。请参阅两个内联注释。
public interface JsonObjectCallbackInterface {
void onSuccess(JSONObject result);
}
class DispatchBuddyBase {
//...
public void addGmapMarker(String inAddress) {
final String address = DBB.prepareAddress(inAddress);
DatabaseReference ref = DBB.getTopPathRef("/geocodedAddresses");
ref.orderByChild("address")
.equalTo(address)
.addListenerForSingleValueEvent(
new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i(TAG, address+" stored: "+dataSnapshot.exists());
if (!dataSnapshot.exists()) {
DBB.getLatLng(
"17 River Rd Meriden CT 06451",
new JsonObjectCallbackInterface() {
// ^--- why is this passing a **null?**
@Override
public void onSuccess(JSONObject response) {
Log.i(TAG, "got a json body:"+response.toString());
addGmapMarker(response);
}
});
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
public class DispatchesActivity extends AppCompatActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
ResultCallback<LocationSettingsResult> {
//...
public void getLatLng(final String address,
final JsonObjectCallbackInterface callback) {
// why does this get a **null** callback? -------------^
Log.e(TAG, "callback is: "+callback);
String url = "https://maps.googleapis.com/maps/api/geocode/json?address="
+ address;
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.e(TAG,"Response: " + response.toString());
DatabaseReference ref = getTopPathRef("/geocodedAddresses").push();
Map<String, Object> u = new HashMap<>();
u.put("address", address);
u.put("geocoded", response.toString());
ref.updateChildren(u, new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError databaseError,
DatabaseReference databaseReference) {
if (databaseError != null) {
Log.e(TAG,"Geocoded address could not be saved "
+ databaseError.getMessage());
} else {
Log.e(TAG,"Geocoded address saved successfully.");
}
}
});
Log.e(TAG, "callback2 is: "+callback);
callback.onSuccess(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
});
DBVolley.getInstance(context)
.addToRequestQueue(jsObjRequest);
}
}
需要明确的是,我确实曾经在测试时注意到它callback
不是 null一次。从那时起,重复运行没有产生非空回调。我才 8 天进入 Java,所以如果我做了一些幼稚的事情,请原谅。
单DispatchBuddyBase
例只在主活动中实例化一次,DBVolley
同样如此。所有其他引用都通过 获得相同的引用DispatchBuddyBase.getInstance()
。我在其他地方的匿名课程没有任何问题。
Volley 代码很简单,可以很好地触发请求,JsonObjectRequest 成功地从 Google 获得了我期望的一切。除了这个回调之外,其他一切都运行良好。
我需要修复什么才能正确传递此回调?