-2

I'm suffering for days how with a login for my android application. I want to send a json object with a request to my Webservice. He will check if the user and password are correct and will sned back the users information. I think the webservice is ok because when I do a POST in my terminal like this :

curl -i -X POST http://bomatec.be/android_login_api/login.php  -d '{"password":"xxxxxx","email":"dddd@gmail.com"}'

I get the data back I want :

{"error":false,"user_id":46,"name":"steven","email":"steven@gmail.com"}

I will post my code of the webservice (php) at the end of the question. Because I followed more then 5 tutorials and questions on SO about my problem I think it's maybe a problem with credentials or rights/authentication or something? I still can't get response of my webservice via my android app.

I tried 2 different types. This one i'm using now so:

private void checkLogin(final String email, final String password) {
    pDialog.setMessage("Logging in ...");
    showDialog();
    final String URL = "http://bomatec.be/android_login_api/login.php";

    HashMap<String, String> params = new HashMap<String, String>();
    params.put("email", email);
    params.put("password", password);

    JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    String responses = response.toString();
                    try {
                        VolleyLog.v("Response:%n %s", response.toString(4));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.e("Error: ", error.getMessage());
        }
    });
    ApplicationController.getInstance().addToRequestQueue(req);
}

This is the ApplicationController

package info.androidhive.loginandregistration.helper;

/**
 * Created by stevengerrits on 7/01/16.
 */
import android.app.Application;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.android.volley.Request;
import com.android.volley.VolleyLog;
import android.text.TextUtils;

public class ApplicationController extends Application {

    /**
     * Log or request TAG
     */
    public static final String TAG = "VolleyPatterns";

    /**
     * Global request queue for Volley
     */
    private RequestQueue mRequestQueue;

    /**
     * A singleton instance of the application class for easy access in other places
     */
    private static ApplicationController sInstance;

    @Override
    public void onCreate() {
        super.onCreate();

        // initialize the singleton
        sInstance = this;
    }

    /**
     * @return ApplicationController singleton instance
     */
    public static synchronized ApplicationController getInstance() {
        return sInstance;
    }

    /**
     * @return The Volley Request queue, the queue will be created if it is null
     */
    public RequestQueue getRequestQueue() {
        // lazy initialize the request queue, the queue instance will be
        // created when it is accessed for the first time
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }


    public <T> void addToRequestQueue(Request<T> req, String tag) {
        // set the default tag if tag is empty
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);

        VolleyLog.d("Adding request to queue: %s", req.getUrl());

        getRequestQueue().add(req);
    }

    public <T> void addToRequestQueue(Request<T> req) {
        // set the default tag if tag is empty
        req.setTag(TAG);

        getRequestQueue().add(req);
    }

    /**
     * Cancels all pending requests by the specified TAG, it is important
     * to specify a TAG so that the pending/ongoing requests can be cancelled.
     *
     * @param tag
     */
    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }
}

I also tried to do it with a helperclass like mentioned here (this is my old code): Volley JsonObjectRequest Post request not working

but that didn't work either. code:

private void checkLogin(final String email, final String password) {
        // Tag used to cancel the request
        //String tag_string_req = "req_login";

        pDialog.setMessage("Logging in ...");
        showDialog();

        HashMap<String, String> params = new HashMap<String, String>();
        params.put("email", email);
        params.put("password", password);

        JsonObjectRequest req = new JsonObjectRequest("http://bomatec.be/android_login_api/login.php", new JSONObject(params),
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            VolleyLog.v("Response:%n %s", response.toString(4));
                            JSONObject jObj = response;
                            //hideDialog();

                            try {
                                boolean error = jObj.getBoolean("error");

                                // Check for error node in json
                                if (!error) {
                                    // user successfully logged in
                                    // Create login session
                                    session.setLogin(true);

                                    // Now store the user in SQLite
                                    String uid = jObj.getString("uid");

                                    JSONObject user = jObj.getJSONObject("user");
                                    String name = user.getString("name");
                                    String email = user.getString("email");
                                    String userid = user.getString("user_id");
                                    // Inserting row in users table

                                    // Launch main activity

                                    //Intent intent = new Intent(LoginActivity.class,MainActivity.class);
                                    //startActivity(intent);
                                    //finish();
                                } else {
                                    // Error in login. Get the error message
                                    String errorMsg = jObj.getString("error_msg");
                                    Toast.makeText(getApplicationContext(),
                                          errorMsg, Toast.LENGTH_LONG).show();
                                }
                            } catch (JSONException e) {
                                // JSON error
                                e.printStackTrace();
                                //Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                        public void onErrorResponse(VolleyError error) {
                        VolleyLog.e("Error: ", error.getMessage());
                }
            });
        ApplicationController.getInstance().addToRequestQueue(req);
    }

This is the webservice PHP code :

<?php

/**
 * @author Ravi Tamada
 * @link http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/ Complete tutorial
 */
require_once 'include/DB_Functions.php';
$db = new DB_Functions();

// json response array
$response = array("error" => FALSE);

//function using_json() {
    $json = file_get_contents('php://input');
    $obj = json_decode($json);
//echo json_encode(array('json'=>$obj));
    $email = $obj->email;
    $password = $obj->password;
    // get the user by email and password
    echo $email;
    echo $password;
    $auth = $db->resolve_user_login($email, $password);
    $user_name = $db->get_user_name($email);
    $user_id = $db->get_user_id($email);


    if ($auth) {
        echo "   in auth ::: ";
        // use is found
        $response["error"] = FALSE;
        $response["user_id"] = $user_id;
        $response["name"] = $user_name;
        $response["email"] = $email;
        echo json_encode($response);
    } else {
        echo "    in else   :::    ";
        // user is not found with the credentials
        $response["error"] = TRUE;
        $response["error_msg"] = "Login credentials are wrong. Please try again!";
        echo json_encode($response);
    }
?>

This is my debugger data. So you can see my request object (ignore the / after login.php this was just a test if it will work with the /)

[IMG]http://i63.tinypic.com/155mjba.png[/IMG]

Community
  • 1
  • 1
Coding
  • 59
  • 1
  • 6
  • This is other code. I used his code priviously but that didn't work either. And there is no solution in that question.. just help me pls – Coding Jan 08 '16 at 13:58
  • are you encoding your data so that you have to decode them in php? – Kostas Drak Jan 08 '16 at 14:21
  • no,not yet. But if the email and pass are wrong I still need to get the response "Login credentials are wrong. Please try again" see php webservice. I don't understand – Coding Jan 08 '16 at 14:43
  • @Coding, I could not see how you are posting the credentials, and one more thing, don't delete the question – Pankaj Nimgade Jan 08 '16 at 18:27

1 Answers1

0

Try this code, I don't have the credential so i can't get the output but you can.

I am using this library to common-io which can be imported like this

compile 'org.apache.commons:commons-io:1.3.2'

Following is the code to run the AsyncTask

private class MyTask extends AsyncTask<Void, Void, Void>{

    @Override
    protected Void doInBackground(Void... params) {

        try {
            URL url = new URL("http://www.bomatec.be/android_login_api/login.php");

            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.connect();

            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("email", "dddd@gmail.com");
            jsonObject.addProperty("password", "password");

            DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
            wr.writeBytes(jsonObject.toString());
            wr.flush();
            wr.close();

            Log.d("TAG",""+ IOUtils.toString(httpURLConnection.getInputStream()));


        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}

Output

in else   :::    {"error":true,"error_msg":"Login credentials are wrong. Please try again!  da was de mail, dees is het pass "}
Pankaj Nimgade
  • 4,529
  • 3
  • 20
  • 30