Gaz003 Gaz003 - 5 months ago 36
Java Question

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

Answer
    @Override
    protected Map<String, String> getParams() {
        //Initializes the map of the returning data
        Map<String, String> params = new HashMap<String, String>();
        //Adds a parameter to the map
        params.put("email", email);
        params.put("password", password);
        //returns the map
        return params;
    }

I do not understand where this is used, so to get an even better explanation you have to post some more code


This adds a user to an SQL database:

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

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

LoginActivity.this: the current class

MainActivity.class: 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


This is taken from http://stackoverflow.com/a/3624358/6296561:

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

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 is to push the two required fields into a map that the PHP part of the code can understand