简体   繁体   English

了解 Android 的 SharedPreferences

[英]Understand SharedPreferences Android

In android I want to make a basic login and registration application.在android中,我想制作一个基本的登录和注册应用程序。 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.我主要对 sharedpreferences 的工作方式感到困惑我也遵循了他关于 sharedpreferences 的教程我理解但不理解这一点。 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);
}

This adds a user to an SQL database:这会将用户添加到 SQL 数据库:

 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. LoginActivity.this:当前类中的上下文 - 这可以简化为this ,但它是 Java 中的一些语法糖,试图阐明this指的是哪个。

MainActivity.class: the target activity MainActivity.class:目标活动

 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菜单为“LoginActivity.this”,“MainActivity.class”为实际游戏内容


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 ) 来源,由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).内部机制不是您需要担心的 - 您真正需要知道的是,它能够以不涉及直接访问文件的方式保存您的数据(自 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 getParams() 方法定义了表单数据中的内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM