0

I'm trying to learn remote database connectivity in android. I found a tutorial on the internet which uses PHP and JSON. It works fine. But the PHP script echoes the encoded JSON data in the same webpage. Only then the data is passed to the android application. It might be ok when I use the PHP script only for the mobile app.

But what if I also wanted my idea to be put up as a website. I wouldn't want the json data to be visible on the webpage. All php scripts that I've come across seem to encode the JSON data in the same way.

Is it possible to pass the JSON data to the android application without it being echoed on the webpage ? Or should I have to create separate PHP scripts for the website and the mobile app ? I've added the code, with which I've worked so far, below.

login.php:

<?php

//load and connect to MySQL database stuff
require("config.inc.php");

if (!empty($_POST)) {
//gets user's info based off of a username.
$query = " 
        SELECT 
            id, 
            username, 
            password
        FROM users 
        WHERE 
            username = :username 
    ";

$query_params = array(
    ':username' => $_POST['username']
);

try {
    $stmt   = $db->prepare($query);
    $result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
    // For testing, you could use a die and message. 
    //die("Failed to run query: " . $ex->getMessage());

    //or just use this use this one to product JSON data:
    $response["success"] = 0;
    $response["message"] = "Database Error1. Please Try Again!";
    die(json_encode($response));

}

//This will be the variable to determine whether or not the user's information is correct.
//we initialize it as false.
$login_ok = false;

//fetching all the rows from the query
$row = $stmt->fetch();
if ($row) {
    //if we encrypted the password, we would unencrypt it here, but in our case we just
    //compare the two passwords
    if ($_POST['password'] === $row['password']) {
        $login_ok = true;
    }
}

// If the user logged in successfully, then we send them to the private members-only page 
// Otherwise, we display a login failed message and show the login form again 
if ($login_ok) {
    $response["success"] = 1;
    $response["message"] = "Login successful!";
    die(json_encode($response));

} else {
    $response["success"] = 0;
    $response["message"] = "Invalid Credentials!";
    die(json_encode($response));
}
} else {
?>
    <h1>Login</h1> 
    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post"> 
        Username:<br /> 
        <input type="text" name="username" placeholder="username" /> 
        <br /><br /> 
        Password:<br /> 
        <input type="password" name="password" placeholder="password" value="" /> 
        <br /><br /> 
        <input type="submit" value="Login" /> 
    </form> 
    <a href="register.php">Register</a>
<?php
}

?> 

Android java file- Login.java

package com.example.mysqltest;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Login extends Activity implements OnClickListener{
private EditText user, pass;
private Button mSubmit, mRegister;

 // Progress Dialog
private ProgressDialog pDialog;

// JSON parser class
JSONParser jsonParser = new JSONParser();

//php login script location:

//localhost :
//testing on your device
//put your local ip instead,  on windows, run CMD > ipconfig
//or in mac's terminal type ifconfig and look for the ip under en0 or en1




private static final String LOGIN_URL =     "http://192.168.1.2:8080/webservice/login.php";

//JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);

    //setup input fields
    user = (EditText)findViewById(R.id.username);
    pass = (EditText)findViewById(R.id.password);

    //setup buttons
    mSubmit = (Button)findViewById(R.id.login);
    mRegister = (Button)findViewById(R.id.register);

    //register listeners
    mSubmit.setOnClickListener(this);
    mRegister.setOnClickListener(this);

}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
    case R.id.login:
            new AttemptLogin().execute();
        break;
    case R.id.register:
            Intent i = new Intent(this, Register.class);
            startActivity(i);
        break;

    default:
        break;
    }
}

class AttemptLogin extends AsyncTask<String, String, String> {

     /**
     * Before starting background thread Show Progress Dialog
     * */
    boolean failure = false;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(Login.this);
        pDialog.setMessage("Attempting login...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... args) {
        // TODO Auto-generated method stub
         // Check for success tag
        int success;
        String username = user.getText().toString();
        String password = pass.getText().toString();
        try {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("username", username));
            params.add(new BasicNameValuePair("password", password));

            Log.d("request!", "starting");
            // getting product details by making HTTP request
            JSONObject json = jsonParser.makeHttpRequest(
                   LOGIN_URL, "POST", params);

            // check your log for json response
            Log.d("Login attempt", json.toString());

            // json success tag
            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                Log.d("Login Successful!", json.toString());

                SharedPreferences sp=PreferenceManager.getDefaultSharedPreferences(Login.this);
                Editor edit=sp.edit();
                edit.putString("username", username);
                edit.commit();

                Intent i = new Intent(Login.this, ReadComments.class);
                finish();
                startActivity(i);
                return json.getString(TAG_MESSAGE);
            }else{
                Log.d("Login Failure!", 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(Login.this, file_url, Toast.LENGTH_LONG).show();
        }

    }

}

}

2 Answers 2

2

Is it possible to pass the json data to the android application without it being echoed on the webpage ?

No, because that's how a web server communicates with a client. You can however use much of the same code for both a website and an api for a mobile app. Just separate your logic from your presentation. Do processing in one place, and presentation in another. Perhaps look into a framework that helps you do this, like Laravel. You can do processing in models, and have separate controllers for your api and your website.

Sign up to request clarification or add additional context in comments.

Comments

1

The way i'll write is,

  1. Have a php script which takes user name/pass and returns JSON output , success or failure.
  2. I'll invoke that php script from android app.
  3. For webpage, i'll write a simple html page with username/password form fields and invoke the php script using AJAX.

Your php script is trying to be a web page as well as a service, so i think that needs to be decoupled.

Think of your php as a service provider for Android & HTML Webpage.

3 Comments

But even when I do that, it's going to do the same process again , isn't it ? It will echo the encoded JSON data, won't it ?
So if your objective is to hide the "JSON response generated by php script", then its not possible. HTTP works on request response protocol and response data is visible to the user. At max you can use https protocol, so that no one can spoof data. Still if someone puts your php script in a browser they will be able to see the response data.
One solution i was thinking is to send custom header/cookie data from your apps. On php script if you see the custom header , respond with JSON. If the header is absent , then send some junk data or a redirect to some other url. Although, i'm not sure but may be in http server you can probably put a rule to process only those http request which contains some header.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.