如何在片段活动中使用用户名?

来源:爱站网时间:2021-12-14编辑:网友分享
如何在片段活动中使用用户名?这个是爱站技术小编最近常常想的一个问题,爱站技术小编觉得这个问题不能单方面的去想,应该要多次的实验证明,这次小编就用用了多次方法去证明和实验了,现在才写了一篇文章发上来供大家参考,希望大家能有一定的帮助吧。

问题描述


[我是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() {

            @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 getParams() {
                // Posting parameters to login url
                Map 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);
    }

}

如何在个人资料片段中显示用户登录名,请先帮助我。

思路:


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

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

因此,在onCreateViewProfileFragment功能中,您可能会执行以下操作。

@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, isLoggedIn).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();
}  

以上内容就是爱站技术频道小编为大家分享的关于如何在片段活动中使用用户名?看完以上分享之后,大家应该都知道如何在片段活动中使用用户名了吧。 这个问题大家都有了一定的答案吧,希望这篇文章能给你们带来一定的帮助。

上一篇:怎么将类转换为服务

下一篇:要添加到Java类中的数组列表中吗?

您可能感兴趣的文章

相关阅读

热门软件源码

最新软件源码下载