【问题标题】:How to take username in fragment activity?如何在片段活动中获取用户名?
【发布时间】:2020-06-08 10:49:43
【问题描述】:

我是 android 新手,我使用 MySQL 设计了一个登录表单,现在我想在配置文件片段中显示用户登录名,因为我为登录会话设置了 Sharedprefernces

这是我的登录类

public class LoginActivity extends AppCompatActivity {

    private static final String TAG = RegisterActivity.class.getSimpleName();
    private Button btnLogin;
    private Button btnLinkToRegister;
    private EditText inputEmail;
    private EditText inputPassword;
    private ProgressDialog pDialog;
    private SessionManager session;
    private SQLiteHandler db;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        inputEmail = findViewById(R.id.email);
        inputPassword = findViewById(R.id.password);
        btnLogin = findViewById(R.id.btnLogin);
        btnLinkToRegister = findViewById(R.id.btnLinkToRegisterScreen);

        // Progress dialog
        pDialog = new ProgressDialog(this);
        pDialog.setCancelable(false);

        // SQLite database handler
        db = new SQLiteHandler(getApplicationContext());

        // Session manager
        session = new SessionManager(getApplicationContext());

        // Check if user is already logged in or not
        if (session.isLoggedIn()) {
            // User is already logged in. Take him to main activity
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
        }

        // Login button Click Event
        btnLogin.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                String email = inputEmail.getText().toString().trim();
                String password = inputPassword.getText().toString().trim();

                // Check for empty data in the form
                if (!email.isEmpty() && !password.isEmpty()) {
                    // login user
                    checkLogin(email, password);
                } else {
                    // Prompt user to enter credentials
                    Toast.makeText(getApplicationContext(),
                            "Please enter the credentials!", Toast.LENGTH_LONG)
                            .show();
                }
            }

        });

        // Link to Register Screen
        btnLinkToRegister.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                Intent i = new Intent(getApplicationContext(),
                        RegisterActivity.class);
                startActivity(i);
                finish();
            }
        });

    }

    /**
     * function to verify login details in mysql db
     */
    private void checkLogin(final String email, final String password) {
        // Tag used to cancel the request
        String tag_string_req = "req_login";

        pDialog.setMessage("Logging in ...");
        showDialog();

        StringRequest strReq = new StringRequest(Request.Method.POST,
                AppConfig.URL_LOGIN, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Login Response: " + response);
                hideDialog();

                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");

                    // Check for error node in json
                    if (!error) {
                        // user successfully logged in
                        // Create login session
                        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");

                        // Inserting row in users table
                        db.addUser(name, email, uid, created_at);

                        // Launch main activity
                        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(TAG, "Login Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_LONG).show();
                hideDialog();
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting parameters to login url
                Map<String, String> params = new HashMap<>();
                params.put("email", email);
                params.put("password", password);

                return params;
            }

        };

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }

    private void showDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

    private void hideDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }
}

这里也是 SessionManager 类

public class SessionManager {
    // LogCat tag
    private static String TAG = SessionManager.class.getSimpleName();

    // Shared Preferences
    private SharedPreferences pref;

    private SharedPreferences.Editor editor;

    // Shared preferences file name
    private static final String PREF_NAME = "AndroidHiveLogin";

    private static final String KEY_IS_LOGGEDIN = "isLoggedIn";

    public SessionManager(Context context) {
        // Shared pref mode
        int PRIVATE_MODE = 0;
        pref = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
        editor = pref.edit();
    }

    public void setLogin(boolean isLoggedIn) {

        editor.putBoolean(KEY_IS_LOGGEDIN, isLoggedIn);

        // commit changes
        editor.commit();

        Log.d(TAG, "User login session modified!");
    }

    public boolean isLoggedIn(){
        return pref.getBoolean(KEY_IS_LOGGEDIN, false);
    }
}

这是个人资料片段

public class ProfileFragment extends Fragment {

    private TextView txtName;
    private SessionManager session;

    public ProfileFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_profile, container, false);
    }

}

如何在个人资料片段中显示用户登录名请帮助我提前致谢。

【问题讨论】:

    标签: java android authentication fragment


    【解决方案1】:

    实际上有很多方法可以做到这一点。在您的情况下,我认为这样做的便捷方法是将登录名存储在SharedPreferences 中,然后从SharedPreferences 中的ProfileFragment 中获取值。

    因此,当您执行session.setLogin(true); 时,您可以将另一个具有登录名的键值对保存到SharedPreferences 中,然后您可以稍后从片段中检索来自SharedPreferences 的值。

    因此,在ProfileFragmentonCreateView 函数中,您可能会执行以下操作。

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    
        SessionManager sessionManager = new SessionManager(getActivity());
    
        // Considering you have the function to store and retrieve the login name from the SharedPreferences in your SessionManager class. 
        String loginName = sessionManager.getLoginName(); // get the login name here
    
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_profile, container, false);
    }
    

    如我所见,您将用户配置文件信息存储在数据库中。因此,您也可以在片段中显示数据库中的用户配置文件信息。我有一个github project,您可以在其中查看如何在 SQLite 数据库中存储/读取。

    希望对你有帮助。

    更新

    您的SessionManager 类中可能有以下函数。

    public class SessionManager {
        // LogCat tag
        private static String TAG = SessionManager.class.getSimpleName();
    
        // Shared Preferences
        private SharedPreferences pref;
    
        private SharedPreferences.Editor editor;
    
        // Shared preferences file name
        private static final String PREF_NAME = "AndroidHiveLogin";
    
        private static final String KEY_IS_LOGGEDIN = "isLoggedIn";
        private static final String KEY_LOGIN_NAME = "loginName";
    
        public SessionManager(Context context) {
            // Shared pref mode
            int PRIVATE_MODE = 0;
            pref = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
            editor = pref.edit();
        }
    
        public void setLogin(boolean isLoggedIn) {
    
            editor.putBoolean(KEY_IS_LOGGEDIN, isLoggedIn);
    
            // commit changes
            editor.commit();
    
            Log.d(TAG, "User login session modified!");
        }
    
        public boolean isLoggedIn(){
            return pref.getBoolean(KEY_IS_LOGGEDIN, false);
        }
    
        // These are the new functions that I added in your SessionManager class
        public void setLoginName(String loginName) {
            editor.putString(KEY_LOGIN_NAME, loginName).apply();
        }
    
        public boolean getLoginName(){
            return pref.getString(KEY_LOGIN_NAME, null);
        }
    }
    

    LoginActivity 的 API 请求部分,您可能会考虑执行以下操作。

    if (!error) {
        // user successfully logged in
        // Create login session
        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");
    
        // Save login name in the SharedPreferences here
        session.setLoginName(name);
    
        // Inserting row in users table
        db.addUser(name, email, uid, created_at);
    
        // Launch main activity
        Intent intent = new Intent(LoginActivity.this,
                MainActivity.class);
        startActivity(intent);
        finish();
    }  
    

    【讨论】:

    • 怎么做我不明白请指导我 // 考虑到你有在你的 SessionManager 类的 SharedPreferences 中存储和检索登录名的功能。字符串登录名 = sessionManager.getLoginName(); // 在这里获取登录名
    • 请检查答案的更新。我希望这能澄清困惑。
    • 从未使用过真正的“登录名”。如何使用它?
    • 在您的片段中,使用该变量将文本设置为 TextView 或布局中的其他内容?
    • 我用它作为TextView textView=getView().findViewById(R.id.name); textView.setText(登录名);但应用程序崩溃了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-21
    • 1970-01-01
    相关资源
    最近更新 更多