我已经使用开放天气api创建了一个天气应用程序,当我单击按钮来确定天气时,它会崩溃。下面是logcat
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
at org.json.JSONTokener.nextValue(JSONTokener.java:94)
at org.json.JSONObject.<init>(JSONObject.java:156)
at org.json.JSONObject.<init>(JSONObject.java:173)
at com.example.hemantj.weather.MainActivity$DownloadTask.onPostExecute(MainActivity.java:133)
at com.example.hemantj.weather.MainActivity$DownloadTask.onPostExecute(MainActivity.java:92)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.access$500(AsyncTask.java:180)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5451)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)下面是代码..。我已经使用了ANDROID TARGET SDK 25和MIN SDK as 23。所以牵涉到了棉花糖..因此,如果与权限相关的任何事情都是错误的,也请指出...
weather.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(checkSelfPermission(Manifest.permission.INTERNET) == PackageManager.PERMISSION_GRANTED){
try {
//to hide the keyboard after pressing the button
InputMethodManager manager =
(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
manager.hideSoftInputFromInputMethod(weatherInput.getWindowToken(),0);
DownloadTask downloadTask = new DownloadTask();
//used to encode the entered input for url.. for example San Fransisco appears in url
//as San%20Fransisco ... and to enable that we use the encoder...
String encodedCity = URLEncoder.encode(city,"UTF-8");
downloadTask.execute("http://api.openweathermap.org/data/2.5/weather?q=" + encodedCity + "&APPID=0a7808bb8061814df9b6d5fc88d58b8f");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
else{
if(shouldShowRequestPermissionRationale(Manifest.permission.INTERNET)){
Toast.makeText(MainActivity.this,
"Internet permissions are necessary",Toast.LENGTH_LONG).show();
}
requestPermissions(new String[]{Manifest.permission.INTERNET},INTERNET_CODE);
}
}
});
}
public class DownloadTask extends AsyncTask<String, Void, String>{
@Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection httpURLConnection = null;
try {
url = new URL(urls[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream in = httpURLConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while(data != -1){
char current = (char) data;
result += current;
data = reader.read();
}
return result;
}
//combined the exceptions MalformedURL and IOException to a common to display a toast msg
catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
String message = "";
JSONObject jsonObject = new JSONObject(result);
String weatherInfo = jsonObject.getString("weather");
Log.i("Weather content", weatherInfo);
JSONArray arr = new JSONArray(weatherInfo);
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
String main = "";
String description = "";
main = jsonPart.getString("main");
description = jsonPart.getString("description");
if (main != "" && description != "") {
message += main + ": " + description + "\r\n";
}
}
if (message != "") {
weatherReport.setText(message);
} else {
Toast.makeText(getApplicationContext(), "Could not find weather", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Could not find weather", Toast.LENGTH_LONG).show();
}
}
}发布于 2017-02-26 01:40:34
您缺少API key,因此将返回一个错误,并且String weatherInfo = jsonObject.getString("weather");为空。所以当你尝试获取数组的.length时,它是空的。创建另一个String对象,如下所示:
String apiKey = "Put API key here";
然后改变:
此
downloadTask.execute("http://api.openweathermap.org/data/2.5/weather?q=" + encodedCity);指向此的
downloadTask.execute("http://api.openweathermap.org/data/2.5/weather?q=" + encodedCity + "&appid=" + apiKey);
此外,请确保您在清单中具有internet权限。
<uses-permission android:name="android.permission.INTERNET" />
https://stackoverflow.com/questions/42459307
复制相似问题