Search code examples
androidhttpandroid-asynctaskslimjsonexception

User Registration using Slim Rest server and android client


I am working on a simple app where I sign up new users. - I am using SLIM PHP framework with MySQL on apache local host - I have a MySQL database with table called tbl_user. I have tested my SLIM implementation using CURL - On Client side, I have three EditView fields named fname, email and password and a sign up button - Its simple, when user click sign up button, the db connection should be made and new user should be added in database. Registration is simple w/o any checks. That I am going to implement once I resolve this issue.

Please help. I have searched a lot and could not resolve the errors.

I am getting following errors:

ERROR

This is my actual error now
01-27 08:42:14.981: D/URL read(6739): Slim Application Errorbody{margin:0;padding:30px;font:12px/1.5 Helvetica,Arial,Verdana,sans-serif;}h1{margin:0;font-size:48px;font-weight:normal;line-height:48px;}strong{display:inline-block;width:65px;}

Slim Application Error

The application could not run because of the following error:

Details:

Message: error_log(/var/tmp/php.log) [function.error-log]: failed to open stream: No such file or directory
File: C:\xampp\htdocs\api\index.php
Line: 105

Stack Trace:

#0 [internal function]: Slim::handleErrors(2, 'error_log(/var/...', 'C:\xampp\htdocs...', 105, Array)
01-27 08:42:14.981: D/URL read(6739): #1 C:\xampp\htdocs\api\index.php(105): error_log('SQLSTATE[23000]...', 3, '/var/tmp/php.lo...')
01-27 08:42:14.981: D/URL read(6739): #2 [internal function]: register()
01-27 08:42:14.981: D/URL read(6739): #3 C:\xampp\htdocs\api\Slim\Route.php(392): call_user_func_array('register', Array)
01-27 08:42:14.981: D/URL read(6739): #4 C:\xampp\htdocs\api\Slim\Slim.php(1052): Slim_Route->dispatch()
01-27 08:42:14.981: D/URL read(6739): #5 C:\xampp\htdocs\api\index.php(26): Slim->run()
01-27 08:42:14.981: D/URL read(6739): #6 {main}

RegisterActivity.java(partial)

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

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(RegisterActivity.this);
        pDialog.setMessage("Signing Up..");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);

        pDialog.show();
    }

    /**
     * Creating User
     * */
    protected String doInBackground(String... args) {
        String fname = mUsername.getText().toString();
        String email = mEmail.getText().toString();
        String password = mPassword.getText().toString();

        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("email", email));
        params.add(new BasicNameValuePair("password", password));
        params.add(new BasicNameValuePair("fname", fname));


        // getting JSON Object
        // Note that create user url accepts POST method
        JSONObject json = jsonParser.makeHttpRequest(url_create_product,
                "POST", params);

        // check log cat from response
        //Log.d("Create Response", json.toString());

        // check for success tag
        try {
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // successfully created USER
                Intent i = new Intent(getApplicationContext(), UserHome.class);
                startActivity(i);

                // closing this screen
               // finish();
            } else {
                // failed to create USER
                 // Log.d("No Sign Up.", json.toString());
            }
        } catch(JSONException e){
           // Log.e("log_tag", "Error parsing data "+e.toString());
           // Log.e("log_tag", "Failed data was:\n" + TAG_SUCCESS);
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once done
        pDialog.dismiss();
    }

}

jsonParser.java(partial)

       public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) {

    // Making HTTP request
    try {

        // check for request method
        if(method == "POST"){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }else if(method == "GET"){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }           

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}

SLIM :index.php

<?php

session_start(); 
require 'Slim/Slim.php';

$app = new Slim();


$app->post('/login', 'login');

$app->post('/register', 'register');

$app->response()->header('Content-Type', 'application/json');

$app->get('/users', 'getUsers');
$app->get('/users/:id', 'getUser');
$app->get('/users/search/:query', 'findByName');
$app->post('/users', 'addUser');
$app->put('/users/:id', 'updateUser');
$app->delete('/users/:id',  'deleteUser');


$app->get('/gametype', 'getgameType');



$app->run();




// AUTHENTICATION START


function login() {
    $request = Slim::getInstance()->request();
    $user = json_decode($request->getBody());
    $email= $user->email;
    $password= $user->password;
    // echo $email;
//   echo $password;
if(!empty($email)&&!empty($password))
    {
        $sql="SELECT email, fname, role FROM tbl_user WHERE email='$email' and password='$password'";
        $db = getConnection();


    try {
        $result=$db->query($sql); 

                if (!$result) { // add this check.
                      die('Invalid query: ' . mysql_error());
                }
        $row["user"]= $result->fetchAll(PDO::FETCH_OBJ);
        $db=null;
        echo json_encode($row);

    } catch(PDOException $e) {
        error_log($e->getMessage(), 3, '/var/tmp/php.log');
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }

    }

} 

// AUTHENTICATION END

//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$



// Register START


function register() {

    $request = Slim::getInstance()->request();
    $user = json_decode($request->getBody());
    $sql = "INSERT INTO tbl_user (email, password, fname) VALUES (:email, :password, :fname)";
    try {
        $db = getConnection();
        $stmt = $db->prepare($sql);  
        $stmt->bindParam("fname", $user->fname);
        $stmt->bindParam("password", $user->password);
        $stmt->bindParam("email", $user->email);
        $stmt->execute();
        $user->id = $db->lastInsertId();
        $db = null;


        print('{"success":1}');

    } catch(PDOException $e) {
        error_log($e->getMessage(), 3, '/var/tmp/php.log');
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
}

    // Register END

Behavior of APP: After clickng signup buttom...app gets stuck here and crashes as "Unfortunately, yourapp has stopped."..

AppSCREEN


Solution

  • When the Slim response object is first created, it sets a content type of "text/html".

    Maybe in your register() method, you should do something like:

    function register()
    {
        $request = Slim::getInstance()->request();
        $response = Slim::getInstance()->response();
        $response['Content-Type'] = 'application/json; charset=utf-8';
    
        /* rest of your function here*/
    }