EDIT: 20020-20020/practise.mysql_php_json I/System.out: org.json.JSONException: Value br of type java.lang.String cannot be converted to JSONObjectww is the message in the terminal I'm getting.
I am working to get a simple insert and retrieve application to work in android by following a tutorial on youtube. Should be fairly simple and I am able to post the user info to the online database, but when I go to retrieve it, nothing happens. Not getting any errors, just not getting any response in JSON.
I am just starting to work with JSON and php both, so I don't know if I'm just not getting something or missing something small.
Here is my connection.php which I know my credentials are correct because I can insert.
<?php
define('hostname', '--------');
define('user', '---------');
define('password', '-------');
define('database', '------------------');
$connect = mysqli_connect(hostname, user, password, database);
?>
Here is my insertUser.php
<?php
if($_SERVER["REQUEST_METHOD"]=="POST") {
require 'connection.php';
createUser();
}
function createUser() {
global $connect;
$name = $_POST["name"];
$email = $_POST["email"];
$password = $_POST["password"];
$query = " Insert into user_table(user_name, user_email, user_password) values ('$name','$email','$password');";
mysqli_query($connect, $query) or die (mysqli_error($connect));
mysqli_close($connect);
}
?>
Here is my showUsers.php
<?php
if($_SERVER["REQUEST_METHOD"]=="GET"){
include 'connection.php';
showStudent();
}
function showStudent()
{
global $connect;
$query = " Select * FROM users; ";
$result = mysqli_query($connect, $query);
$number_of_rows = mysqli_num_rows($result);
$temp_array = array();
if($number_of_rows > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$temp_array[] = $row;
}
}
header('Content-Type: application/json');
echo json_encode(array("users"=>$temp_array));
mysqli_close($connect);
}
?>
Now here's my Android application code in the Main Activity. This is supposed to just get the name, email, and password of the users in my database. I have another onclick method to insert the users.
showButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
JsonObjectRequest jsonObjectRequest; = new JsonObjectRequest(Request.Method.GET, showURL, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray users = response.getJSONArray("users");
for(int i=0; i<users.length(); i++) {
JSONObject user = users.getJSONObject(i);
String name = user.getString("user_name");
String email = user.getString("user_email");
String password = user.getString("user_password");
results.append(name);
}
results.append("\n");
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObjectRequest);
}
});
– ZWis212 Jan 06 '16 at 23:29