![](/img/trans.png)
[英]Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.getString(java.lang.String)' on a null object reference
[英]java.lang.String org.json.JSONObject.getString(java.lang.String)' on a null object reference
我在以下代碼中收到錯誤。 我在---> 1&---> 2 .. while循環之間得到錯誤。 響應代碼為200.但我的應用程序仍然崩潰了。
注意:同樣的問題已經被問過了。即使我分析了但是我沒有得到正確的東西。請幫我解決。
if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_BAD_METHOD) {
is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
Log.e("LOGIN CHECK", "json"); // -----------> 1 (Prints in Log.e)
while ((line = br.readLine()) != null){
buffer.append(line).append("\r\n");
}
json = buffer.toString(); // -----------> 2 (Didnt print in Log.e)
Log.e("LOGIN CHECK", "json" + buffer.toString());
is.close();
}
LogCat錯誤:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.getString(java.lang.String)' on a null object reference
at com.xxxxx.restaurant.Fragment.SignUpFragment_1$ProcessLogin.onPostExecute(SignUpFragment_1.java:187)
at com.xxxx.restaurant.Fragment.SignUpFragment_1$ProcessLogin.onPostExecute(SignUpFragment_1.java:163)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
Json PArser:
public class JSONParser {
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, HashMap<String, String> params) {
HttpURLConnection con = null;
InputStream is = null;
try {
con = (HttpURLConnection) (new URL(url)).openConnection();
con.setRequestMethod("POST");
con.connect();
OutputStream os = con.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(params));
writer.flush();
writer.close();
os.close();
StringBuilder buffer = new StringBuilder();
Log.e("Response Buffer", String.valueOf(buffer));
int responseCode = con.getResponseCode();
Log.e("Response Code", String.valueOf(responseCode));
if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_BAD_METHOD) {
is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
Log.e("LOGIN CHECK", "json");
while ((line = br.readLine()) != null)
buffer.append(line).append("\r\n");
json = buffer.toString();
Log.e("LOGIN CHECK", "json" + buffer.toString());
is.close();
}else{
json = "abc";
}
con.disconnect();
} catch (Throwable t) {
t.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
} catch (Throwable ignored) {
}
try {
if (con != null) {
con.disconnect();
}
} catch (Throwable ignored) {
}
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
}
return jObj;
}
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();
}
}
SignUpFragment_1:
try {
if (json.getString(KEY_SUCCESS) != null) { // Error in this LINE
String res = json.getString(KEY_SUCCESS);
if (Integer.parseInt(res) == 1) {
dbUtil.open();
JSONObject json_user = json.getJSONObject("user");
UserFunctions logout = new UserFunctions();
logout.logoutUser(context);
dbUtil.addLogIn(strUsername, strEmail, strPassword, LogInActivity.img);
Intent upanel = new Intent(context, MainActivity.class);
upanel.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pDialog.dismiss();
startActivity(upanel);
} else {
pDialog.dismiss();
Toast.makeText(context, "Incorrect username/password", Toast.LENGTH_SHORT).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Exception
是JSONObject.getString(java.lang.String)
,所以它意味着你得到的JSONObject
為null,因此jObj
為null
並且LogCat
沒有顯示任何Exception
因為你的優點,你沒有捕獲異常。
因此,要處理代碼,請替換else部分中的代碼。
您沒有將JSONObject
分配給else部分中的json
字符串變量。
if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_BAD_METHOD) {
is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
Log.e("LOGIN CHECK", "json");
while ((line = br.readLine()) != null)
buffer.append(line).append("\r\n");
json = buffer.toString();
Log.e("LOGIN CHECK", "json" + buffer.toString());
is.close();
} else {
json = "{" + KEY_SUCCESS + ":\"error response code " + responseCode + " \"}";
}
Catch
和Log
Exception
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
我敢肯定,它會解決你的問題。
錯誤說你沒有初始化你的字符串line
...所以要么初始化像line = ""
或者傳遞null
(當它訪問時會再次拋出NullPointerException而不分配任何值)你也可以嘗試StringBuilder
類喜歡..
BufferedReader reader = new BufferedReader(new InputStreamReader(http.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
reader.close();
json = sb.toString(); // this is your String json;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.