如何使用Android Studio中的PostResponseAsyncTask将SharedPreferences设置为下一个活动值? [英] How to intent SharedPreferences into next activity value using PostResponseAsyncTask in Android Studio?

查看:95
本文介绍了如何使用Android Studio中的PostResponseAsyncTask将SharedPreferences设置为下一个活动值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是该问题的扩展

my question is the extension of this question here but in this question I added two function which are :

  1. SharedPreferences
  2. 记住我的功能(复选框)

当前,我成功登录了/不记得我的复选框,并打算从mysql数据库中获取其余的JSON对象.

Currently, I managed to login with/without remember me checkbox and intent the rest of the JSON Object fetch from mysql database.

但是问题出在LoginActivity.java PART A块 中.当我重新启动/重建应用程序时,意图数据为空,它不会存储并发送到下一个活动中.数据自动登录后,无法存储并发送到下一个活动.代码如下

But the problem is inside LoginActivity.java PART A block . When I restart/rebuild the apps, the intent data is null which is not stored and sent into next activity. The data could not be stored and sent into next activity when it automatically logged in. The code as below

JSON对象

{
    "access":"PA001",
    "password":"123",
    "fullname":"ARCADE",
    "branch":"HQ",
    "section":"MPR"
}

access.php

<?php
    $conn = mysqli_connect("","","","");
    if(
        isset($_POST['access']) &&
        isset($_POST['password'])
    ){
        $access     = $_POST['access'];
        $password   = $_POST['password'];
        $sql = "SELECT * FROM table WHERE access = '$access' AND password = '$password' ";
        $result = mysqli_query($conn, $sql);
        if($result && mysqli_num_rows($result) > 0){
            while($row = mysqli_fetch_array($result)){

                $accessdb     = $row['access'];
                $passworddb   = $row['password'];
                $fullnamedb   = $row['fullname'];
                $branchdb     = $row['branch'];
                $sectiondb    = $row['section'];

                echo "success_access";

                $response = array('access' => $accessdb, 'password' => $passworddb, 'fullname' => $fullnamedb, 'branch' => $branchdb, 'section' => $sectiondb);
                echo json_encode($response);
            }
        mysqli_free_result($result);
        } else {
            echo "access_failed";
        }
    }
?>

LoginActivity.java

public class LoginActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {

    final String TAG = this.getClass().getName();
    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;

    EditText etLogin, etPassword;
    CheckBox cbRememberMe;
    Button bLogin;
    boolean checkRememberMe;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        etLogin         = (EditText)findViewById(R.id.etLogin);
        etPassword      = (EditText)findViewById(R.id.etPassword);
        cbRememberMe    = (CheckBox)findViewById(R.id.cbRememberMe);
        cbRememberMe.setOnCheckedChangeListener(this);
        checkRememberMe = cbRememberMe.isChecked();

        sharedPreferences = getSharedPreferences("login.conf", Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();

        //////////////////////////////////////// PART A /////////////////////////////////////
        final String  accessdb   = sharedPreferences.getString("access", "");
        final String  passworddb = sharedPreferences.getString("password", "");
        final String  fullnamedb = sharedPreferences.getString("fullname", "");
        final String  branchdb   = sharedPreferences.getString("branch", "");
        final String  sectiondb  = sharedPreferences.getString("branch", "");
        final HashMap data = new HashMap();

        data.put("access", accessdb);
        data.put("password", passworddb);
        data.put("fullname", fullnamedb);
        data.put("branch", branchdb);
        data.put("section", sectiondb);
        if(!(accessdb.contains("") && passworddb.contains("") && fullnamedb.contains("") && branchdb.contains("") && sectiondb.contains(""))){
            PostResponseAsyncTask task = new PostResponseAsyncTask(LoginActivity.this, data, new AsyncResponse() {
                @Override
                public void processFinish(String s) {
                    // edited here ,add Log
                    Log.d(TAG, "processFinish : " + s);
                    String responseToJSONObject = s.substring(s.indexOf("{"));
                    if(s.contains("success_access")){

                        try {
                            JSONObject jsonObject = new JSONObject(responseToJSONObject);

                            final String logindb    = jsonObject.getString("login");
                            final String pwdb       = jsonObject.getString("pw");
                            final String realnamedb = jsonObject.getString("real_name");
                            final String deptdb     = jsonObject.getString("dept");

                            Intent intent = new Intent(LoginActivity.this, NextActivity.class);
                            intent.putExtra("login", logindb);
                            intent.putExtra("pw", pwdb);
                            intent.putExtra("real_name", realnamedb);
                            intent.putExtra("dept", deptdb);
                            LoginActivity.this.startActivity(intent);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }
            });
            task.execute("http://localhost/login.php");
        }
        //////////////////////////////////////// PART A /////////////////////////////////////

        bLogin          = (Button)findViewById(R.id.bLogin);
        bLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String url = "http://localhost/login.php";
                StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        // edited here ,add Log
                        Log.d(TAG, "onResponse : " + response);
                        if(response.contains("success_access")){
                            String resp = response.substring(response.indexOf("{"));

                            // LOGIN WITH CHECK REMEMBER ME
                            if(checkRememberMe){
                                try {
                                    JSONObject jsonObject      = new JSONObject(resp);
                                    final String accessdb      = jsonObject.getString("access");
                                    final String passworddb    = jsonObject.getString("password");
                                    final String fullnamedb    = jsonObject.getString("fullname");
                                    final String branchdb      = jsonObject.getString("branch");
                                    final String sectiondb     = jsonObject.getString("section");

                                    editor.putString("access", etLogin.getText().toString());
                                    editor.putString("password", etPassword.getText().toString());
                                    editor.putString("fullname", fullnamedb);
                                    editor.putString("branch", branchdb);
                                    editor.putString("section", sectiondb);
                                    editor.putBoolean("isLoggedIn", true);
                                    editor.apply();

                                    Intent intent = new Intent(LoginActivity.this, NextActivity.class);
                                    intent.putExtra("access", accessdb);
                                    intent.putExtra("password", passworddb);
                                    intent.putExtra("fullname", fullnamedb);
                                    intent.putExtra("branch", branchdb);
                                    intent.putExtra("section", sectiondb);
                                    LoginActivity.this.startActivity(intent);

                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                            }
                            // LOGIN WITH CHECK REMEMBER ME

                            // LOGIN WITHOUT CHECK REMEMBER ME
                            else {
                                try {
                                    JSONObject jsonObject = new JSONObject(resp);

                                    final String accessdb        = jsonObject.getString("access");
                                    final String passworddb      = jsonObject.getString("password");
                                    final String fullnamedb      = jsonObject.getString("fullname");
                                    final String branchdb        = jsonObject.getString("branch");
                                    final String sectiondb       = jsonObject.getString("section");   

                                    Intent intent = new Intent(LoginActivity.this, NextActivity.class);
                                    intent.putExtra("access", accessdb);
                                    intent.putExtra("password", passworddb);
                                    intent.putExtra("fullname", fullnamedb);
                                    intent.putExtra("branch", branchdb);
                                    intent.putExtra("section", sectiondb);
                                    LoginActivity.this.startActivity(intent);

                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                            // LOGIN WITHOUT CHECK REMEMBER ME

                        } else{
                            Toast.makeText(getApplicationContext(), "Error" , Toast.LENGTH_SHORT).show();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getApplicationContext(), "Error" , Toast.LENGTH_SHORT).show();
                    }
                }){
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String, String> params = new HashMap<>();
                        params.put("login", etLogin.getText().toString());
                        params.put("pw", etPassword.getText().toString());
                        return params;
                    }
                };
                MySingleton.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);
            }
        });
    }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
        checkRememberMe = isChecked;
        Log.d(TAG, "Remember me is = " + checkRememberMe);
    }
}

我的Logcat

08-22 16:50:28.802 21022-21022/? I/art: Not late-enabling -Xcheck:jni (already on)
08-22 16:50:28.802 21022-21022/? W/art: Unexpected CPU variant for X86 using defaults: x86
08-22 16:50:28.822 21022-21029/? I/art: Debugger is no longer active
08-22 16:50:28.822 21022-21029/? I/art: Starting a blocking GC Instrumentation
08-22 16:50:28.895 21022-21022/? W/System: ClassLoader referenced unknown path: /data/app/com.app.test-2/lib/x86
08-22 16:50:28.901 21022-21022/? I/InstantRun: starting instant run server: is main process
08-22 16:50:29.129 21022-21040/? I/OpenGLRenderer: Initialized EGL, version 1.4
08-22 16:50:29.129 21022-21040/? D/OpenGLRenderer: Swap behavior 1
08-22 16:50:29.130 21022-21040/? W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
08-22 16:50:29.130 21022-21040/? D/OpenGLRenderer: Swap behavior 0
08-22 16:50:29.133 21022-21040/? D/EGL_emulation: eglCreateContext: 0xb3305060: maj 2 min 0 rcv 2
08-22 16:50:29.150 21022-21040/? D/EGL_emulation: eglMakeCurrent: 0xb3305060: ver 2 0 (tinfo 0xb3303360)
08-22 16:50:29.156 21022-21040/? D/EGL_emulation: eglMakeCurrent: 0xb3305060: ver 2 0 (tinfo 0xb3303360)
08-22 16:50:29.964 21022-21022/com.app.test W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
08-22 16:50:30.037 21022-21022/com.app.test W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
08-22 16:50:30.040 21022-21040/com.app.test D/EGL_emulation: eglMakeCurrent: 0xb3305060: ver 2 0 (tinfo 0xb3303360)
08-22 16:50:44.279 21022-21022/com.app.test W/IInputConnectionWrapper: finishComposingText on inactive InputConnection
08-22 16:50:46.163 21022-21022/com.app.test D/com.app.test.LoginActivity: Check flag is = true
08-22 16:50:47.820 21022-21323/com.app.test D/NetworkSecurityConfig: No Network Security Config specified, using platform default


// LOG.d after i logged in with remember me check in
08-22 16:50:47.824 21022-21022/com.app.test E/com.app.test.LoginActivity: Response is    = success_access{"access":"ID001","password":"1233","fullname":"ARCADE","branch":"HQ", "section":"MPR"}
08-22 16:50:47.825 21022-21022/com.app.test E/com.app.test.LoginActivity: JSON Object is = {"access":"ID001","password":"1233","fullname":"ARCADE","branch":"HQ", "section":"MPR"}

08-22 16:50:47.825 21022-21022/com.app.test D/com.app.test.LoginActivity: ID001
08-22 16:50:47.825 21022-21022/com.app.test D/com.app.test.LoginActivity: 123
08-22 16:50:47.982 21022-21025/com.app.test I/art: Do partial code cache collection, code=29KB, data=30KB
08-22 16:50:47.982 21022-21025/com.app.test I/art: After code cache collection, code=29KB, data=30KB
08-22 16:50:47.982 21022-21025/com.app.test I/art: Increasing code cache capacity to 128KB
08-22 16:50:47.994 21022-21040/com.app.test D/EGL_emulation: eglMakeCurrent: 0xb3305060: ver 2 0 (tinfo 0xb3303360)
08-22 16:50:48.083 21022-21040/com.app.test D/EGL_emulation: eglMakeCurrent: 0xb3305060: ver 2 0 (tinfo 0xb3303360)
08-22 16:50:48.100 21022-21040/com.app.test D/EGL_emulation: eglMakeCurrent: 0xb3305060: ver 2 0 (tinfo 0xb3303360)
08-22 16:50:48.135 21022-21022/com.app.test W/IInputConnectionWrapper: finishComposingText on inactive InputConnection


// LOG.d when I restarted apps without logout. 
08-22 16:54:32.607 24710-24710/? I/art: Not late-enabling -Xcheck:jni (already on)
08-22 16:54:32.607 24710-24710/? W/art: Unexpected CPU variant for X86 using defaults: x86
08-22 16:54:32.694 24710-24710/com.app.test W/System: ClassLoader referenced unknown path: /data/app/com.app.test-2/lib/x86
08-22 16:54:32.699 24710-24710/com.app.test I/InstantRun: starting instant run server: is main process
08-22 16:54:34.256 24710-24811/com.app.test I/OpenGLRenderer: Initialized EGL, version 1.4
08-22 16:54:34.257 24710-24811/com.app.test D/OpenGLRenderer: Swap behavior 1
08-22 16:54:34.257 24710-24811/com.app.test W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
08-22 16:54:34.257 24710-24811/com.app.test D/OpenGLRenderer: Swap behavior 0
08-22 16:54:34.258 24710-24811/com.app.test D/EGL_emulation: eglCreateContext: 0xb3305360: maj 2 min 0 rcv 2
08-22 16:54:34.266 24710-24811/com.app.test D/EGL_emulation: eglMakeCurrent: 0xb3305360: ver 2 0 (tinfo 0xb3303200)
08-22 16:54:34.274 24710-24811/com.app.test D/EGL_emulation: eglMakeCurrent: 0xb3305360: ver 2 0 (tinfo 0xb3303200)
08-22 16:54:35.124 24710-24710/com.app.test W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
08-22 16:54:35.292 24710-24710/com.app.test W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
08-22 16:54:35.299 24710-24811/com.app.test D/EGL_emulation: eglMakeCurrent: 0xb3305360: ver 2 0 (tinfo 0xb3303200)

感谢有人可以提供帮助.谢谢.

Appreciate if someone can help. Thanks.

推荐答案

根据我对问题的了解和了解,您希望数据被存储并打算在下一次自动登录时进入下一个活动(在A部分内部).

From what I see and understand in your question, you want the data to be stored and intent into next activity on next auto logged in (inside PART A).

根据上面的代码从头开始尝试此操作后,我认为您的"isLoggedIn"来自其他活动文件.

After I tried it from my end based on your code above and I assume your "isLoggedIn" is from other activity file.

您只需要将布尔值"isLoggedIn"更改为 false ,因为每当用户以记住我的身份登录时,它都会存储sharedPreferences数据并将其用于下一个活动.

You just need to change boolean "isLoggedIn" into false because whenever user log in with remember me, it stored the sharedPreferences data and intent it into next activity.

与不记得我的登录相同,它存储了sharedPreferences数据,但isLoggedIn为false.因此,当您的应用重新启动或重建时,它将不再自动登录.当"isLoggedIn"为false时,请不要忘记清除并提交sharedPreferences.

Same as log in without remember me, it stored the sharedPreferences data but isLoggedIn is false. Therefore, when your apps restart or rebuild, it will not auto logged in anymore. Don't forget to clear and commit the sharedPreferences when "isLoggedIn" is false.

这是代码.

LoginActivity.java

if(checkRememberMe){
  // Data added  
} else {
    try {
        JSONObject jsonObject = new JSONObject(resp);

        final String accessdb        = jsonObject.getString("access");
        final String passworddb      = jsonObject.getString("password");
        final String fullnamedb      = jsonObject.getString("fullname");
        final String branchdb        = jsonObject.getString("branch");
        final String sectiondb       = jsonObject.getString("section");   

        editor.putString("access", etLogin.getText().toString());
        editor.putString("password", etPassword.getText().toString());
        editor.putString("fullname", fullnamedb);
        editor.putString("branch", branchdb);
        editor.putString("section", sectiondb);
        editor.putBoolean("isLoggedIn", false);
        editor.apply();

        Intent intent = new Intent(LoginActivity.this, NextActivity.class);
        intent.putExtra("access", accessdb);
        intent.putExtra("password", passworddb);
        intent.putExtra("fullname", fullnamedb);
        intent.putExtra("branch", branchdb);
        intent.putExtra("section", sectiondb);
        LoginActivity.this.startActivity(intent);

    } catch (JSONException e) {
        e.printStackTrace();
    }
}

在NextActivity.java中,添加sharedPreferences并将其设置为String.

And inside NextActivity.java, add sharedPreferences and set it as String.

sharedPreferences sharedPreferences = getSharedPreferences("login.conf", Context.MODE_PRIVATE);

final String accessdb   = sharedPreferences.getString("access","");
final String pwdb       = sharedPreferences.getString("pw","");
final String fullnamedb = sharedPreferences.getString("fullname","");
final String branchdb   = sharedPreferences.getString("branch","");
final String sectiondb  = sharedPreferences.getString("section","");

Intent intent       = getIntent();
String access_db    = intent.getStringExtra("access");
String pw_db        = intent.getStringExtra("pw");
String fullname_db  = intent.getStringExtra("fullname");
String branch_db    = intent.getStringExtra("branch");
String section_db   = intent.getStringExtra("section");

Toast.makeText(getApplicationContext(), "access is = " + accessdb, Toast.makeText.LENGTH_SHORT).show();

这篇关于如何使用Android Studio中的PostResponseAsyncTask将SharedPreferences设置为下一个活动值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆