-1

I have existing jquery code to submit array 'array' as json var in a login process

var array1 = {
"command" : "login",
"username": $("#txt_username").val(),
"password": $("#txt_password").val(),
"remember":  $('#chk_remember').is(':checked')
};

$.ajax({
                url: 'functions.php',
                data : {'array': array1},
                dataType: 'json',
                type: 'POST',
                success: function(data) {
                    if  (data.success == 1 ){

                   $('#result').html("You have been logged in.</br>You will be     redirected to another page");
}
});

and at PHP

if (isset($_POST["array"])) {
$array = $_POST['array'];
switch ($array["command"]) {
    case "login" :
        if (DoLogin($array["username"], $array["password"]) == true) {
            $success = 1;
}
        else {
            $success = 0;
        }
        $arr = array("success" => $success, "redirect" => 1);

        echo json_encode($arr);
break;
}

how to deal with this login process from android?

Eslam Sameh Ahmed
  • 3,792
  • 2
  • 24
  • 40
  • Why not just use `$.ajax()` ?? – Pointy Aug 12 '14 at 22:27
  • It is a javascript but i need to repeate the process in Android code – Eslam Sameh Ahmed Aug 12 '14 at 22:29
  • If you are making a connection in a Java application, you'll need to research how to do that. I'd start with a search for "cURL post Java Android", that should get you lots of good research links. – halfer Aug 12 '14 at 22:31
  • 1
    Oh, you mean you're writing a stand-alone Android **application** and not a web application. Well it's a completely different affair. – Pointy Aug 12 '14 at 22:32
  • I already know how to send list of string variables over Json but what i need is to encode and decode an array object over JSON – Eslam Sameh Ahmed Aug 13 '14 at 08:47

2 Answers2

2
public class Utils {

    public static String POST(String url, Login login){
        InputStream inputStream = null;
        String result = "";
        try {

            // 1. create HttpClient
            HttpClient httpclient = new DefaultHttpClient();

            // 2. make POST request to the given URL
            HttpPost httpPost = new HttpPost(url);

            String json = "";

            // 3. build jsonObject
            JSONObject jsonObject = new JSONObject();
            jsonObject.accumulate("command", login.command);
            jsonObject.accumulate("username", login.username);
            jsonObject.accumulate("password", login.password);
            jsonObject.accumulate("remember", login.remember);

            // 4. convert JSONObject to JSON to String
            json = jsonObject.toString();

            // ** Alternative way to convert Login object to JSON string usin Jackson Lib
            // ObjectMapper mapper = new ObjectMapper();
            // json = mapper.writeValueAsString(login);

            // 5. set json to StringEntity
            StringEntity se = new StringEntity(json);

            // 6. set httpPost Entity
            httpPost.setEntity(se);

            // 7. Set some headers to inform server about the type of the content
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");

            // 8. Execute POST request to the given URL
            HttpResponse httpResponse = httpclient.execute(httpPost);

            // 9. receive response as inputStream
            inputStream = httpResponse.getEntity().getContent();

            // 10. convert inputstream to string
            if(inputStream != null)
            result = convertInputStreamToString(inputStream);
            else
            result = "Did not work!";

            } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
        }

        // 11. return result
        return result;
    }
}

// Model login obj
public class Login {
    public String password;
    public String username;
    public String command;
    public boolean remember;
}

Into Activity

Login login = new Login();

// get reference to the views
login.username = (EditText) findViewById(R.id.user);
login.password = (EditText) findViewById(R.id.pass);
login.command = (EditText) findViewById(R.id.comm);
login.remember = ((CheckBox) findViewById(R.id.rem)).isChecked();

Utils.POST(stringUrl, login) // use AsynckTask for this http://stackoverflow.com/questions/8829135/android-http-request-asynctask
Davide
  • 622
  • 4
  • 10
  • Will not work as the PHP code is looking first for an array called 'array' in the post then it is looking inside th array for 'command' item and user/password items are inside the array – Eslam Sameh Ahmed Aug 13 '14 at 08:50
1

I'd recommend looking into using Volley to handle your web requests. This is a handy guide to get started: http://www.androidhive.info/2014/05/android-working-with-volley-library-1/

Andrew Breen
  • 685
  • 3
  • 11