I'm developing an Android app that connects to a remote MYSQL database and retrieves info via JSON data. The part of the app I'm having trouble with involves searching by userID
in the app, and returning the associated user info from the database, such as the ID, first name, company and position.
The problem is parsing the JSON data within the app. The error message I get is System.err: org.json.JSONException: No value for id
.
The php page displays JSON data. Two JSON objects are outputted: a success
object and a result
object. The success
object is properly parsed by the app and tells the app what to do via an if-statement. So if success == 1
, the app executes a block of code that should parses the result
object and assigns each element of the array to a String
value in the app. The output from the php page is:
{"success":1,"message":"UserID found!"}{"result":[{"id":"1100011","firstname":"Kevin","company":"company","position":"bartender"}]}
The problem is the values from the results
object are not being parsed by the app. Here is the php page:
<?php
define('HOST','localhost');
define('USER','********');
define('PASS','**********');
define('DB','**********');
if (!empty($_POST)){
if (empty($_POST['userID'])){
$response["success"] = 0;
$response["message"] = "Please enter a User ID";
die(json_encode($response));
}
$userID = mysql_escape_string($_POST['userID']);
$con = mysqli_connect(HOST,USER,PASS,DB);
$sql = "SELECT * FROM users WHERE id = $userID";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result, array(
'id'=>$row[0],
'firstname'=>$row[4],
'company'=>$row[6],
'position'=>$row[7],
)
);
}
if($result){
$response["success"] = 1;
$response["message"] = "UserID found!";
echo json_encode($response); // if I comment out this line, the result array gets parsed properly by the app.
echo json_encode(array("result"=>$result));
}else{
$response["success"] = 0;
$response["message"] = "UserID not found. Please try again.";
die(json_encode($response));
}
mysqli_close($con);
} else {
?>
<h1>Search by User ID:</h1>
<form action="searchbyuserid.php" method="post">
Enter the UserID of the receipient:<br />
<input type="text" name="userID" placeholder="User ID" />
<br /><br />
<input type="submit" value="Submit" />
</form>
<a href="register.php">Register</a>
<?php
}
?>
If I comment out the line noted above, the Log from the app shows the correct data being parsed by the app for the results
array:
D/UserID Lookup:: {"result":[{"id":"1100011","firstname":"Kevin","company":"company","position":"bartender"}]}
, but then I get an error for W/System.err: org.json.JSONException: No value for success
because success
isn't being sent (obviously).
Here's my android code:
import android.app.ProgressDialog; ...
public class SearchByUserID extends ActionBarActivity implements View.OnClickListener {
// Buttons
private Button mSubmitButton, mBackButton;
// EditText Field
EditText enterUserID;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// Variable for holding URL:
private static final String LOGIN_URL = "http://www.***********/webservice/searchbyuserid.php";
//JSON element ids from response of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private static final String TAG_USERID = "id";
private static final String TAG_FIRSTNAME = "firstname";
private static final String TAG_COMPANY = "company";
private static final String TAG_POSITION = "POSITION";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.search_by_user_id_layout);
mSubmitButton = (Button)findViewById(R.id.submit);
mBackButton = (Button)findViewById(R.id.back);
mSubmitButton.setOnClickListener(this);
mBackButton.setOnClickListener(this);
enterUserID = (EditText)findViewById(R.id.enterUserIdNumber);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.submit:
new SearchUserId().execute();
break;
case R.id.back:
finish();
break;
default:
break;
}
}
class SearchUserId extends AsyncTask<String, String, String> {
// Show progress dialog
boolean failure = false;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SearchByUserID.this);
pDialog.setMessage("Searching User ID...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... args) {
// Check for success tag
int success;
String userID = enterUserID.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("userID", userID));
Log.d("UserID:", userID);
Log.d("request!", "starting");
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST", params);
// check your log for json response
Log.d("UserID Lookup:", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
JSONObject json2 = jsonParser.makeHttpRequest(LOGIN_URL, "POST", params);
String userid = json2.getString(TAG_USERID);
String firstName = json2.getString(TAG_FIRSTNAME);
String company = json2.getString(TAG_COMPANY);
String position = json2.getString(TAG_POSITION);
Log.d("User ID Found!", json.toString());
Log.d("userid:", userid);
Log.d("firstName:", firstName);
Log.d("company:", company);
Log.d("position:", position);
Intent i = new Intent(SearchByUserID.this, HomeActivity.class);
finish();
startActivity(i);
return json.getString(TAG_MESSAGE);
}else{
Log.d("User ID not found.", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(SearchByUserID.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
So basically I'm able to properly parse either the success
object or the results
object, but not both. If I try to parse both, I get a JSON error for no value for id
.