如何记住Andorid Studio的价值?

时间:2020-07-12 11:44:13

标签: java android

我创建了一个登录页面,用户可以仅输入其用户名(无需密码或身份验证) 它将显示在下一个活动中。但是,每次打开应用程序时,都必须输入用户名。我要如何记住用户名。 (语言Java)

谢谢!

(我是初学者)

package com.example.app;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    Button btn;
    EditText et;
    String st;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn= findViewById(R.id.button);
        et=findViewById(R.id.edittext);

                btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent i=new Intent(MainActivity.this, Welcome.class);
                                st=et.getText().toString();
                                i.putExtra("Value",st);
                                startActivity(i);
                                finish();

(这是用户输入用户名的活动)

package com.example.app;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.TextView;

public class Welcome extends AppCompatActivity {

    TextView tv;
    String st;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);
        tv=findViewById(R.id.textView);

        st=getIntent().getExtras().getString("Value");
        tv.setText(st);

    }
}

(这是欢迎活动)

1 个答案:

答案 0 :(得分:4)

我认为您需要将用户用户名保存在Sharedpreferences中,然后在启动应用程序时从sharedpreferences中获取值,并检查该值是否为null或为空,然后让用户输入其用户名,否则您可以从sharedpreferences中设置用户名

尝试此代码:

   ///save sharedpreferences
        SharedPreferences sharedPreferences = 
         getSharedPreferences("prefs",Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("username","put here your username");
        editor.apply();


        ///get sharedpreferences
        SharedPreferences sharedPreferences1 = 
        getSharedPreferences("prefs",Context.MODE_PRIVATE);
        String username = sharedPreferences1.getString("username","");
        tv.setText(username);
相关问题