0

I am learning from the following tutorial. http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/ WAMP PHP Directory I came across this directory overview image and I also noticed some JSON responses in Section 3.3 Types of JSON Responses. I know they're echoes in php codes, depending on user registers and login successfully or not. But I don't know how and where do I save such JSON files. The tutorial is quite quite detailed except this part. And I haven't dealt with JSON APIs and other objects yet.

Mitesh
  • 35
  • 1
  • 7
  • Please copy paste which code line / file are your referring to .. – Varun Verma Nov 04 '15 at 04:15
  • I was referring to: { "error": false, "uid": "55fa7220a2c187.50984590", "user": { "name": "Ravi Tamada", "email": "ravi@androidhive.info", "created_at": "2015-09-17 13:26:16", "updated_at": null } } – Mitesh Nov 04 '15 at 04:39
  • Means you want to store php files and get JSON response from it? – Chirag Savsani Nov 04 '15 at 04:50
  • If you look at Login.php files, particularly as below code where user fails to login if the entered data doesn’t match the row, stored in MySQL database: if ($user != false) { $response["error"] = FALSE; $response["uid"] = $user["unique_id"]; $response["user"]["name"] = $user["name"]; $response["user"]["email"] = $user["email"]; $response["user"]["created_at"] = $user["created_at"]; $response["user"]["updated_at"] = $user["updated_at"]; echo json_encode($response); } – Mitesh Nov 04 '15 at 05:00
  • JSON Response is echoed at the end of each conditional loop like this echo json_encode($response); I don't understand where should I save these JSON Response files – Mitesh Nov 04 '15 at 05:01

1 Answers1

0

The tutorial is not indicating that you should be using JSON files, but that you should use JSON as a language construct when forming your response as a type of Data Interchange Format Language.

It's also saying that the application stack (both ends of the spectrum) should expect to communicate between each other using JSON.

As the article describes using a database, you'll be making a comparison against the Database to authenticate and serving a JSON response back to the application. This is what the PHP side of things might look like.

//assume data passed from app is in JSON format.
$variables = isset($_POST['variables']) : json_decode($_POST['variables']) : false;

//given the above, assume we have 2 keys, username and password.
// as we've applied json_decode above, we can now treat the string as an array with keys to access our values.

//use prepared statements when accepting user input!
$stmt = $mysqli->prepare('select id from user where user = ? and password = MD5(?)');
$stmt->bind_param('ss', $variables['username'], $variables['password']);
$stmt->execute();
$stmt->store_result();

//now we can count the returned rows and then return our response.

$resp = array();
if(count($stmt->num_rows) > 0){
    $resp['msg'] = 'Successfully logged in.';
    $resp['status'] = 1;
} else {
    $resp['msg'] = 'Failed to login! Username or password or both are incorrect.';
    $resp['status'] = 0;
}

return json_encode($resp);

Now inside of your android application you can decode this json result and check the status then display the message.

A rough sketch of that may look something like this:

DefaultHttpClient   httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost(http://path.to.your.site.tld/login-endpoint);
//we will need this so we can send JSON to the server.
httppost.setHeader("Content-type", "application/json");

//other stuff to build out query and send username and password
//not shown for brevity...

InputStream inputStream = null;
String result = null;
try {
    HttpResponse response = httpclient.execute(httppost);           
    HttpEntity entity = response.getEntity();

    inputStream = entity.getContent();
    // json is UTF-8 by default
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
    StringBuilder sb = new StringBuilder();

    String line = null;
    while ((line = reader.readLine()) != null)
    {
        sb.append(line + "\n");
    }
    result = sb.toString();
} catch (Exception e) { 
    // Oops
}
finally {
    try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}

Example copy + pasted from this answer: https://stackoverflow.com/questions/9605913/how-to-parse-json-in-android

Finally with the representation of the JSON object being held within result (as long as no failure occurred) we can parse the result and check the value of the keys the server should respond with, I.E. msg & status.

JSONArray jArray = jObject.getJSONArray(result);
for (int i=0; i < jArray.length(); i++)
{
    try {
        JSONObject oneObject = jArray.getJSONObject(i);
        // Pulling items from the array
        String msg = oneObject.getString("msg");
        String status = oneObject.getString("status");
    } catch (JSONException e) {
        // Oops
    }
}

Now you can do whatever you want given the msg and status response provided from the server after authentication.

Good luck.

Community
  • 1
  • 1
Ohgodwhy
  • 49,779
  • 11
  • 80
  • 110
  • Thank you! :) It took me some repetitions to understand everything explained by you, but it makes sense finally. – Mitesh Nov 04 '15 at 13:00