我使用HttpURLConnection来解析jsonResponse。它大部分时间都做得很好。但有时,它给出了java.lang.String java.lang.String.toString()'在此行中的空对象引用错误:" jsonResponse = new JSONObject(response.toString());"然后应用程序崩溃。我正在使用try并赶上这里,但应用程序崩溃了。为什么应用程序崩溃btw?我该如何解决这个问题?
错误日志
11-06 16:31:59.312 21887-21887/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.zzz.com.zz, PID: 21887
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
at com.zzz.com.zz.jobschedulers.MainActivity$LoginTask.onPostExecute(MainActivity.java:761)
at com.zzz.com.zz.jobschedulers.MainActivity$LoginTask.onPostExecute(MainActivity.java:664)
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:7409)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
码
class LoginTask extends AsyncTask<String, Void, String> {
@Override
protected void onPreExecute() {
}
protected String doInBackground(String... params) {
URL url;
String response = "";
try {
url = new URL("http://zzzz.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(25000);
conn.setConnectTimeout(25000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
HashMap<String, String> h1 = new HashMap<String, String>();
h1.put("username", email);
h1.put("password", password);
writer.write(getPostDataString(h1));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
Log.e("upload gps", "uploaded");
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
return response;
} else {
response = "";
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String response) {
JSONObject jsonResponse = null;
try {
jsonResponse = new JSONObject(response.toString());
status = jsonResponse.getString("status");
responseMsg = jsonResponse.getString("message");
if (status.equalsIgnoreCase("true")) {
Log.e("response ", response + "");
JSONObject jsonResponse1 = jsonResponse.getJSONObject("data");
String userId = jsonResponse1.getString("user_id");
Log.e("userId", userId + "");
if (userId != null) {
SharedPreferences abc = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
SharedPreferences.Editor editor2 = abc.edit();
editor2.putString("userId", userId);
editor2.apply();
} else {
}
Intent i = new Intent(MainActivity.this, LiveTrack.class);
i.putExtra("userId", userId);
startActivity(i);
} else {
Log.e("response", "onloginfailed");
validate();
Toast.makeText(MainActivity.this, "Smth went wrong. Please check your network and try again", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Log.e("Json", "execption" + e);
}
}
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
答案 0 :(得分:0)
所以你的问题就是为什么即使你设置了Try / Catch它也会崩溃。所以我的答案是你已经捕获了JSONException
异常,这与Json-Parsing相关。
所以请使用下面的Try / Catch。
JSONObject jsonResponse = null;
try {
jsonResponse = new JSONObject(response.toString());
status = jsonResponse.getString("status");
responseMsg = jsonResponse.getString("message");
if (status.equalsIgnoreCase("true")) {
Log.e("response ", response + "");
JSONObject jsonResponse1 = jsonResponse.getJSONObject("data");
String userId = jsonResponse1.getString("user_id");
Log.e("userId", userId + "");
if (userId != null) {
SharedPreferences abc = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
SharedPreferences.Editor editor2 = abc.edit();
editor2.putString("userId", userId);
editor2.apply();
} else {
}
Intent i = new Intent(MainActivity.this, LiveTrack.class);
i.putExtra("userId", userId);
startActivity(i);
} else {
Log.e("response", "onloginfailed");
validate();
Toast.makeText(MainActivity.this, "Smth went wrong. Please check your network and try again", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Log.e("Json", "execption" + e);
} catch (Exception e) {
Log.e("Generic", "execption" + e);
}
请注意,在上面我添加了一个带有通用Exception
的Catch。
希望这对你有用。
答案 1 :(得分:0)
实际问题出在其他地方。您的onPostExecute(String result)
执行以下操作:
jsonResponse = new JSONObject(response.toString());
然而,在您doInBackground()
的最后,您明确表示:
return null;
doInBackground()
应该返回一个结果(参见documentation)。您将返回null,因此在onPostExecute()
中,如果连接失败,则始终执行此操作:
jsonResponse = new JSONObject(null.toString());
因此,您的应用程序崩溃,Android运行时抱怨您尝试在null上运行toString()
。要解决此问题,您必须在String result
doInBackground()
答案 2 :(得分:0)
onPostExecute()
之前jsonResponse = new JSONObject(response.toString());
上的输入此内容:if(response == null)return;