1

In android I want to make a basic login and registration application. I am following this tutorial. The application works properly and runs. I am just trying to understand the code now and after many google searches I can not understand some of the code and was wondering if somebody could help me understand it.

Below I have posted the method I do not understand and in comments highlighted what I do not understand - any clarification is much appreciated, I have also commented the code to what I believe the code does, if any of it is incorrect please tell me, you can also view all of the code on the tutorial website.

I am mainly confused about how the sharedpreferences works I have followed his tutorial on sharedpreferences too I understand that but do not understand this. Thank you and sorry if the problem is very basic

   private void checkLogin(final String email, final String password) {

    // Tag used to cancel the request
    String tag_string_req = "req_login";

    // Dialog stating trying to login
    pDialog.setMessage("Logging in ...");
    showDialog();

    // Send the request over to the database to check details
    StringRequest strReq = new StringRequest(Method.POST,
            AppConfig.URL_LOGIN, new Response.Listener<String>() {

        // Do this once you get a response
        @Override
        public void onResponse(String response) {
            Log.d(loginName, "Login Response: " + response.toString());
            hideDialog();

            // Break the response up into individual things and store in variables
            try {
                JSONObject jObj = new JSONObject(response);
                boolean error = jObj.getBoolean("error");

                // Check for error node in json
                if (!error) {

                   // I DO NOT UNDERSTAND THIS!!! how does this bit work?
                        // it sets the shared preferences login to true correct?
                        // but how does it set it true to only this particular user? 
                        // Because it doesnt store the email and password along with it
                        // and sets its tag "isLoggedIn" and then saves it to the shared
                        // preferences 
                    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 created_at = user
                            .getString("created_at");



                    //I DO NOT UNDERSTAND THIS!!! Why do you need to do this & does this 
                    //affect the MySQL DB at all?
                    db.addUser(name, email, uid, created_at);

                    // I DO NOT UNDERSTAND THIS!!! Why do you need to write LoginActivity.this
                    // do you not just write MainActivity?
                    Intent intent = new Intent(LoginActivity.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(loginName, "Login Error: " + error.getMessage());
            Toast.makeText(getApplicationContext(),
                    error.getMessage(), Toast.LENGTH_LONG).show();
            hideDialog();
        }
    }) {


        /***************************************************************/
        //I DO NOT UNDERSTAND THIS WHOLE METHOD WHY DO YOU DO THIS?!!!
        /***************************************************************/
        @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;
        }

    };

    // FINALLY I ALSO DO NOT UNDERSTAND WHY YOU DO THIS! AND WHAT DOES IT DO
    AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
Zoe
  • 27,060
  • 21
  • 118
  • 148
Gaz003
  • 15
  • 4
  • 1
    You wrote that you are new to Android. The tutorial you are following is not for beginner, it has some other bits too. If you really looking to understand SharedPreferences, try this : http://www.tutorialspoint.com/android/android_shared_preferences.htm – intellignt_idiot Jul 03 '16 at 17:35

1 Answers1

0

This adds a user to an SQL database:

 db.addUser(name, email, uid, created_at);

There should be a class somewhere that defines the actual function, which then creates the query that actually interacts with the database.

The intent changes the activity (what is rendered on the screen and what logic is handled):

LoginActivity.this: the context in the current class - this can be simplified to just this, but it's a bit of syntactic sugar in Java that attempts to clarify which this is being referred to.

MainActivity.class: the target activity

 Intent intent = new Intent(LoginActivity.this,
                        MainActivity.class);

The difference between two activities can be explained with the content of a game. The menu is "LoginActivity.this" and "MainActivity.class" is the actual game content


As for shared preferences, the usage is pretty straight-forward:

To obtain shared preferences, use the following method In your activity:

SharedPreferences prefs = this.getSharedPreferences(
  "com.example.app", Context.MODE_PRIVATE);

To read preferences:

String dateTimeKey = "com.example.app.datetime";

// use a default value using new Date()
long l = prefs.getLong(dateTimeKey, new Date().getTime()); 

To edit and save preferences

Date dt = getSomeDate();
prefs.edit().putLong(dateTimeKey, dt.getTime()).apply();

(Source, posted by naikus)

The internal mechanics aren't something you need to worry about - the thing you really need to know is that it's able to save your data in a way you can use that doesn't involve directly accessing files (which has become a maze since Android 10).


EDIT:

Based on what I saw at the tutorial, the entire thing is to check if the login information entered exists in the database. The getParams() method defines what goes into the form data

Zoe
  • 27,060
  • 21
  • 118
  • 148
  • thank you i really appreicate this detailed explanation – Gaz003 Jul 03 '16 at 18:28
  • can you give a bit more detail on how the param thing works? i still dont fullly understand it, also why would you add someone to the db if they are already in there? arent you trying to login – Gaz003 Jul 03 '16 at 18:30
  • the getParams() creates a map of two values, in this case it is two string values. It takes in the password and the email and a different part of the code transmits a request to the PHP part of the code, in which it asks: Does this user exist? If yes, is the password correct? If yes, it completes the login and you access whatever is after that – Zoe Jul 03 '16 at 18:32
  • 1 last question! Why do I need to add a user to the SQL database again if they are already in there? because i am trying to login – Gaz003 Jul 03 '16 at 18:51
  • I just realised you missed one, why do you do this? AppController.getInstance().addToRequestQueue(strReq, tag_string_req); – Gaz003 Jul 03 '16 at 18:56
  • I am not really sure, gotta check the tutorial. but that does not add a user – Zoe Jul 03 '16 at 18:58
  • It adds a request to the SQL database which handles checking if 1) the user exists and 2) if the login creditentials is correct – Zoe Jul 03 '16 at 18:59
  • I made it clearer what I do not understand http://pastebin.com/LK8Y3n6y – Gaz003 Jul 03 '16 at 19:30
  • That thing is what requests the indexing of the database which checks: is there a user with that email. If yes, is the password correct? If yes log in – Zoe Jul 03 '16 at 19:37