Reputation: 123
I've been following a tutorial (honestly, I was copy pasting, therefore I don't know why it doesn't work as I didn't change a thing) and I have this String response that I need to convert into a Json Object.
response =
Config.php\r\n{"error":false,"user":{"name":"test","surname":"test","address":"test","email":"test"}}
Right after the try
at JSONObject jObj = new JSONObject(response);
my program jumps to the exception with a message:
Method threw 'java.lang.NullPointerException' exception. Cannot evaluate org.json.JSONObject.toString()
Is it the structure of response
or something?
Here's where I use it:
@Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
// Now store the user in SQLite
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String surname = user.getString("surname");
String address = user.getString("address");
String email = user.getString("email");
// Inserting row in users table
db.addUser(name, surname, address, email);
// Launch main activity
Intent intent = new Intent(LoginScreen.this,
MainMenu.class);
startActivity(intent);
finish();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
Upvotes: 2
Views: 7110
Reputation: 6577
Remove the Config.php\r\n
prefix from the response before turning it into a JSON object.
Upvotes: 2
Reputation: 3453
Your response
is not a valid json string.
See RFC 7159.
Also you can verify your json with online json formatter
Upvotes: 0