繁体   English   中英

了解 Android 的 SharedPreferences

[英]Understand SharedPreferences Android

在android中,我想制作一个基本的登录和注册应用程序。 我正在关注教程。 该应用程序正常工作并运行。 我现在只是想了解代码,经过多次谷歌搜索后,我无法理解某些代码,想知道是否有人可以帮助我理解它。

下面我发布了我不理解的方法,并在评论中突出显示了我不理解的内容 - 非常感谢任何澄清,我还对代码进行了评论,我认为代码的作用,如果有任何不正确,请告诉我,您还可以在教程网站上查看所有代码。

我主要对 sharedpreferences 的工作方式感到困惑我也遵循了他关于 sharedpreferences 的教程我理解但不理解这一点。 如果问题很基本,谢谢和抱歉

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

这会将用户添加到 SQL 数据库:

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

某处应该有一个定义实际函数的类,然后它创建实际与数据库交互的查询。

意图改变活动(在屏幕上呈现什么以及处理什么逻辑):

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

MainActivity.class:目标活动

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

两种活动的区别可以用游戏的内容来解释。 菜单为“LoginActivity.this”,“MainActivity.class”为实际游戏内容


至于共享首选项,用法非常简单:

要获取共享首选项,请在您的活动中使用以下方法:

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

要阅读首选项:

 String dateTimeKey = "com.example.app.datetime"; // use a default value using new Date() long l = prefs.getLong(dateTimeKey, new Date().getTime());

编辑和保存首选项

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

来源,由naikus发布)

内部机制不是您需要担心的 - 您真正需要知道的是,它能够以不涉及直接访问文件的方式保存您的数据(自 Android 以来这已成为一个迷宫) 10)。


编辑:

根据我在教程中看到的内容,整个过程是检查输入的登录信息是否存在于数据库中。 getParams() 方法定义了表单数据中的内容

暂无
暂无

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

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