Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Login Example in Android using POST method using REST API

I am working on my First Android application where we have our own REST API, url will be like. "www.abc.com/abc/def/" . For login activity i need to do httppost by passing 3 parameters as identifier, email and password. Then after getting the http response, i need to show the dialogbox whether Invalid Credentials or Switch to another activity.

Can someone please show me sample code for how to do this?

like image 604
Veer3383 Avatar asked Feb 16 '15 19:02

Veer3383


2 Answers

An easy way to complete this task is to using a library, if your familiar with libraries. I recommend Ion because it's small and easy to work with. Add the library and add the following snippet to the method of your choice.

Ion.with(getApplicationContext())
.load("http://www.example.com/abc/def/")
.setBodyParameter("identifier", "foo")
.setBodyParameter("email", "[email protected]")
.setBodyParameter("password", "p@ssw0rd")
.asString()
.setCallback(new FutureCallback<String>() {
   @Override
    public void onCompleted(Exception e, String result) {
        // Result
    }
});

Notice! If you want to make network calls you must add the following permission to your AndroidManifest.xml outside the <application> tag if you're not aware of that.

<uses-permission android:name="android.permission.INTERNET" />

To check the response for successful login, or failure you can add the following snippet inside the onComplete-method (where the // Result is).:

    try {
        JSONObject json = new JSONObject(result);    // Converts the string "result" to a JSONObject
        String json_result = json.getString("result"); // Get the string "result" inside the Json-object
        if (json_result.equalsIgnoreCase("ok")){ // Checks if the "result"-string is equals to "ok"
            // Result is "OK"
            int customer_id = json.getInt("customer_id"); // Get the int customer_id
            String customer_email = json.getString("customer_email"); // I don't need to explain this one, right?
        } else {
            // Result is NOT "OK"
            String error = json.getString("error");
            Toast.makeText(getApplicationContext(), error, Toast.LENGTH_LONG).show(); // This will show the user what went wrong with a toast
            Intent to_main = new Intent(getApplicationContext(), MainActivity.class); // New intent to MainActivity
            startActivity(to_main); // Starts MainActivity
            finish(); // Add this to prevent the user to go back to this activity when pressing the back button after we've opened MainActivity
        }
    } catch (JSONException e){
        // This method will run if something goes wrong with the json, like a typo to the json-key or a broken JSON.
        Log.e(TAG, e.getMessage());
        Toast.makeText(getApplicationContext(), "Please check your internet connection.", Toast.LENGTH_LONG).show();
    }

Why do we need a try & catch, well first of all we are forced to and on the other hand, it will prevent the application to crash if something goes wrong with the JSON-parsing.

like image 146
timbillstrom Avatar answered Oct 18 '22 07:10

timbillstrom


this is how you can handle this from scratch, in your login Activity use this block of code and if you are using POST method you will modify a little bit because I used a GET Method to check credidentials, LoginHandler extends AsyncTask because it is not allowed to make Network Operations on main Thread...

private class  LoginHandler extends AsyncTask<String, Void, Boolean> {

        @Override
        protected Boolean doInBackground(String... params) {
            // TODO Auto-generated method stub

            String URL = "url to get from ";

            JSONObject jsonReader=null;


            try {

                // TODO Auto-generated method stub
                HttpClient httpclient = new DefaultHttpClient();
                HttpResponse response;
                String responseString = null;
                try {
                    response = httpclient.execute(new HttpGet(URL));
                    StatusLine statusLine = response.getStatusLine();
                    if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
                        ByteArrayOutputStream out = new ByteArrayOutputStream();
                        response.getEntity().writeTo(out);
                        out.close();
                        responseString = out.toString();
                        jsonReader=new JSONObject(responseString);
                    } else {
                        // Closes the connection.
                        response.getEntity().getContent().close();
                        throw new IOException(statusLine.getReasonPhrase());
                    }
                } catch (ClientProtocolException e) {
                    // TODO Handle problems..
                    String er=e.getMessage();
                } catch (IOException e) {
                    // TODO Handle problems..
                    String er=e.getMessage();
                }

                // Show response on activity

                if (!jsonReader.get("UserName").toString().equals("")) {
                    SharedPreferences sp = getSharedPreferences("LoginInfos", 0);
                    Editor editor = sp.edit();

                    editor.putString("email", jsonReader.getString("EmailAddress"));
                    editor.putString("username", jsonReader.getString("UserName"));
                    editor.putString("userid", jsonReader.getString("UserId"));
                    editor.putString("realname", jsonReader.getString("RealName"));
                    editor.putString("realsurname", jsonReader.getString("RealSurname"));
                    editor.putString("userprofileimage", jsonReader.getString("UserProfileImage"));




                    DateFormat dateFormat = new SimpleDateFormat(
                            "yyyy.MM.dd HH:mm:ss");
                    // get current date time with Date()
                    Date date = new Date();

                    editor.putString("LastLogin",
                            dateFormat.format(date.getTime()));
                    editor.commit();
                    return true;
                }
                return false;

            } catch (Exception ex) {

            }

            return false;
        }

        // TODO Auto-generated method stub

        @Override
        protected void onPostExecute(Boolean result) {
            // TODO Auto-generated method stub


            if (result) {
                pdialog.dismiss();
                Intent userMainActivityIntent = new Intent(
                         getApplicationContext(), MainUserActivity.class);
                startActivity(userMainActivityIntent);
            }
            else
            {
                pdialog.dismiss();
                new AlertDialog.Builder(MainActivity.this).setTitle("Login Error")
                .setMessage("Email or password is wrong.").setCancelable(false)
            .setPositiveButton("OK",new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    dialog.cancel();
                }
            } ).show();

            }




            super.onPostExecute(result);


        }

    }
like image 4
katmanco Avatar answered Oct 18 '22 09:10

katmanco