1

This is my coding. That's work on Localhost. When I'm hosting this code doesn't works. Please, how to solve this problem? Thanks

Login.java, this code for Sign In on Android. This code contain of How to get some variables from MySQL.

package com.sudotech.go_learn;

    import java.util.HashMap;
    import java.util.Map;

    import org.json.JSONException;
    import org.json.JSONObject;

    import com.android.volley.Response;
    import com.android.volley.VolleyError;
    import com.android.volley.Request.Method;
    import com.android.volley.toolbox.StringRequest;

    import com.sudotech.go_learn.AppConfig;
    import com.sudotech.go_learn.AppController;
    import com.sudotech.go_learn.Login;
    import com.sudotech.go_learn.MainActivity;
    import com.sudotech.go_learn.R;
    import com.sudotech.go_learn.SQLiteHandler;
    import com.sudotech.go_learn.SessionManager;

    import android.app.Activity;
    import android.app.ProgressDialog;
    import android.content.Intent;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;

    public class Login extends Activity {
        private static final String TAG = RegisterActivity.class.getSimpleName();
        private Button btnLogin;
        private Button btnLinkToRegister;
        private EditText inputEmail;
        private EditText inputPassword;
        private ProgressDialog pDialog;
        private SessionManager session;
        private SQLiteHandler db;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_login);

            inputEmail = (EditText) findViewById(R.id.email);
            inputPassword = (EditText) findViewById(R.id.password);
            btnLogin = (Button) findViewById(R.id.btnLogin);
            btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);

            // Progress dialog
            pDialog = new ProgressDialog(this);
            pDialog.setCancelable(false);

            // SQLite database handler
            db = new SQLiteHandler(getApplicationContext());

            // Session manager
            session = new SessionManager(getApplicationContext());

            // Check if user is already logged in or not
            if (session.isLoggedIn()) {
                // User is already logged in. Take him to main activity
                Intent intent = new Intent(Login.this, MainActivity.class);
                startActivity(intent);
                finish();
            }

            // Login button Click Event
            btnLogin.setOnClickListener(new View.OnClickListener() {

                public void onClick(View view) {
                    String email = inputEmail.getText().toString().trim();
                    String password = inputPassword.getText().toString().trim();

                    // Check for empty data in the form
                    if (!email.isEmpty() && !password.isEmpty()) {
                        // login user
                        checkLogin(email, password);
                    } else {
                        // Prompt user to enter credentials
                        Toast.makeText(getApplicationContext(),
                                "Please enter the credentials!", Toast.LENGTH_LONG)
                                .show();
                    }
                }

            });

            // Link to Register Screen
            btnLinkToRegister.setOnClickListener(new View.OnClickListener() {

                public void onClick(View view) {
                    Intent i = new Intent(getApplicationContext(),
                            SignUpActivity.class);
                    startActivity(i);
                    finish();
                }
            });

        }

        /**
         * function to verify login details in mysql db
         * */
        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();

            StringRequest strReq = new StringRequest(Method.POST,
                    AppConfig.URL_LOGIN, new Response.Listener<String>() {

                @Override
                public void onResponse(String response) {
                    Log.d(TAG, "Login Response: " + response.toString());
                    hideDialog();

                    try {
                        JSONObject jObj = new JSONObject(response);
                        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 username = user.getString("username");
                            String name = user.getString("name");
                            String email = user.getString("email");
                            String created_at = user
                                    .getString("created_at");

                            // Inserting row in users table
                            db.addUser(username, name, email, uid, created_at);

                            // Launch main activity
                            Intent intent = new Intent(Login.this,
                                    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();
                    }

                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e(TAG, "Login Error: " + error.getMessage());
                    Toast.makeText(getApplicationContext(),
                            error.getMessage(), Toast.LENGTH_LONG).show();
                    hideDialog();
                }
            }) {

                @Override
                protected Map<String, String> getParams() {
                    // Posting parameters to login url
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("email", email);
                    params.put("password", password);

                    return params;
                }

            };

            // Adding request to request queue
            AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
        }

        private void showDialog() {
            if (!pDialog.isShowing())
                pDialog.show();
        }

        private void hideDialog() {
            if (pDialog.isShowing())
                pDialog.dismiss();
        }

    }

Login.php this is for converted json from Android.

<?php
require_once 'include/DB_Functions.php';
$db = new DB_Functions();

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

if (isset($_POST['email']) && isset($_POST['password'])) {

    // receiving the post params
    $email = $_POST['email'];
    $password = $_POST['password'];

    // get the user by email and password
    $user = $db->getUserByEmailAndPassword($email, $password);

    if ($user != false) {
        // use is found
        $response["error"] = FALSE;
        $response["uid"] = $user["unique_id"];
        $response["user"]["username"] = $user["username"];
        $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);
    } 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);
    }
} else {
    // required post params is missing
    $response["error"] = TRUE;
    $response["error_msg"] = "Required parameters email or password is missing!";
    echo json_encode($response);
}
?>

AppConfig.java. This code for connection. When i'm hosting in "IDHOSTINGER" and change this URL on the code. This code doesn't works.

    package com.sudotech.go_learn;

    public class AppConfig {
        // Server user login url
        public static String URL_LOGIN = "http://www.sudotech.pe.hu/login.php";

        // Server user register url
        public static String URL_REGISTER = "http://www.sudotech.pe.hu/register.php";

        // Server user register url
            public static String URL_REGISTERTEACHER = "

http://www.sudotech.pe.hu/registerteacher.php";

}
Vedda
  • 7,066
  • 6
  • 42
  • 77

3 Answers3

1

Using org.json library: use this lib unless it wont work

JsonObject object = new JSONObject(EscapedStringHere);
mohit gupta
  • 160
  • 1
  • 8
0

When I visited your login.php link, it showed this enter image description here

I suggest you, do these things:

  1. Change your mysql_connect() to mysqli_connect() in DB_Connect.php
  2. Make sure, you have granted the access for the mysql user, at your hosting server
  3. Change your mysql_select_db() to mysqli_select_db() in DB_Connect.php
  4. Access issue again, please refer to point 2
  5. Try adding mysql_error() after mysql_select_db(), like this

    mysqli_select_db('your_database_name') or die('error : ' . mysqli_error());

Webster
  • 1,113
  • 2
  • 19
  • 39
0

You uses json StringRequest that's are for response of server String request ,

StringRequest strReq = new StringRequest(Method.POST,
                    AppConfig.URL_LOGIN, new Response.Listener<String>() {

}

Use it for case of Json Object Request :

JSONObject jObj = new JSONObject(response);

JsonObjectRequest strReq = new JsonObjectRequest(Method.POST,
                    AppConfig.URL_LOGIN, new Response.Listener<String>() {

}

Extra : If you use JsonArrayRequest than you should use :

 JsonArrayRequest strReq = new JsonArrayRequest(Method.POST,
                    AppConfig.URL_LOGIN, new Response.Listener<String>() {
}

In your Code You uses

JSONObject jObj = new JSONObject(response);

So I think you should use JsonObjectRequest

Here you can get details idea :)

http://developer.android.com/training/volley/request.html#request-json

arifhasnat
  • 93
  • 1
  • 2
  • 10