【发布时间】:2015-03-17 18:29:28
【问题描述】:
我一直在 Android Studio 中编写一个 android 应用程序,目的是从 Google 方向 API(使用 Volley 库)获取 JSONObject,然后将其传递给一个新活动(然后它将被打印出来,所以我可以在解析它之前进行调试)。但是,通过 ADB 在我的手机上运行该应用程序时,LogCat returns this。
提交按钮的onClick(应用崩溃时)调用的方法是:
public void submit(View view) {
Location location = LocationServices.FusedLocationApi.getLastLocation(locationClient);
String destination = findViewById(R.id.destinationInput).toString();
String url = "https://maps.googleapis.com/maps/api/directions/json?origin="
+ location.getLatitude()
+ location.getLongitude()
+ "&destination=" + destination
+ "&mode=driving"
+ avoids()
+ "departure_time=now"
+ "&key=" + getString(R.string.API_KEY);
RequestQueue requestQueue;
// Instantiate the cache
Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap
// Set up the network to use HttpURLConnection as the HTTP client.
Network network = new BasicNetwork(new HurlStack());
// Instantiate the RequestQueue with the cache and network.
requestQueue = new RequestQueue(cache, network);
// Start the queue
requestQueue.start();
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject dirs) {
Intent intent;
intent = new Intent(getApplicationContext(), DisplayDirections.class);
intent.putExtra("DIRECTIONS", dirs.toString());
startActivity(intent);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
// Add the request to the RequestQueue.
requestQueue.add(jsObjRequest);
}
private String avoids() {
String avoid = "avoid=";
boolean any = false;
if(((Switch) findViewById(R.id.avoidTollsSwitch)).isChecked()) {
avoid += "tolls";
any = true;
}
if(((Switch) findViewById(R.id.avoidMotorwaysSwitch)).isChecked()) {
if(any) avoid += "|";
avoid += "highways";
any = true;
}
if(((Switch) findViewById(R.id.avoidFerriesSwitch)).isChecked()) {
if(any) avoid += "|";
avoid += "ferries";
any = true;
}
if(any) return avoid;
else return "";
}
LogCat 日志链接到 String url = 行,但我对这行有什么问题感到困惑。据我所知,我的代码应该可以工作......
排球教程:https://developer.android.com/training/volley/simple.html
【问题讨论】:
-
可能位置为空?
-
请提供完整的堆栈跟踪
-
LocationServices.FusedLocationApi.getLastLocation(...)在某些情况下可以返回null。行动前检查。 -
不应该
avoid=是&avoid=吗?出发前还有&?
标签: java android string android-studio nullpointerexception