Search code examples
javaandroidsharedpreferences

Understand SharedPreferences Android


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);
}

Solution

  • 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