使用 SharedPreferences 创建多个用户

大家好,我正在尝试创建一个小型应用程序。此应用程序最多可保留 3 个用户。我正在使用 aSharedpreferences来保存数据。但我无法保存多个用户我不知道我该怎么做。创建用户后,我想在他们之间进行交换,并且我不使用用户密码,因此系统始终可以在用户之间更改。


有我的主要活动。


public class MainActivity extends AppCompatActivity {


    EditText nameText;

    EditText dateText;



    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        nameText = (EditText) findViewById(R.id.nameText);

        dateText = (EditText) findViewById(R.id.dateText);

    }


    public void saveInfo(View view) {

        SharedPreferences sharedPref = getSharedPreferences("userInfo", Context.MODE_PRIVATE);

        SharedPreferences.Editor editor =  sharedPref.edit();

        editor.putString("username",nameText.getText().toString());

        editor.putString("date",dateText.getText().toString());

        editor.apply();

    }

}

谢谢你的建议。


Cats萌萌
浏览 198回答 3
3回答

烙印99

那么您是否尝试为每个用户的 sharedPreference 数据库设置不同的名称?public void saveInfo(View view,User[] userList)&nbsp;{&nbsp; &nbsp; for (int i = 0, i < userList.count){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;User user = userList[i];&nbsp; &nbsp; &nbsp; &nbsp; // I am creating a new shared prefence for each user!&nbsp; &nbsp; &nbsp; &nbsp; // by their username.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;SharedPreferences sharedPref = getSharedPreferences("userInfo_"+user.username.trim(), Context.MODE_PRIVATE);&nbsp; &nbsp; SharedPreferences.Editor editor =&nbsp; sharedPref.edit();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;editor.putString("username",user.username);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;editor.putString("date",user.date);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;editor.apply();&nbsp; &nbsp; }}之后,要获取特定用户的数据,您只需要他们的用户名:SharedPreferences sharedPref = getSharedPreferences("userInfo_"+user.username.trim(), Context.MODE_PRIVATE);String userDate = sharedPref.getString("date", "unknown");

犯罪嫌疑人X

我认为您应该创建自己的类,该类将保存您需要的字段数据。另外,我建议您创建一个List对象而不是使用数组以获得更舒适的选项,例如List.size():UserData&nbsp;userData&nbsp;=&nbsp;new&nbsp;UserData(View&nbsp;view,&nbsp;List<User>&nbsp;users);然后Map使用您的自定义唯一密钥保存它,以轻松UserData满足各种使用需求:private&nbsp;Map<String,&nbsp;UserData>&nbsp;userDataMap&nbsp;=&nbsp;new&nbsp;HashMap<>();

沧海一幻觉

如何使用数组中的数字来实现这一点?可能是这样的:public void saveInfo(View view,User[] userList)&nbsp;{&nbsp; &nbsp; SharedPreferences sharedPref = getSharedPreferences("userInfo", Context.MODE_PRIVATE);&nbsp; &nbsp; SharedPreferences.Editor editor =&nbsp; sharedPref.edit();&nbsp; &nbsp; for (int i = 0, i < userList.count){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;User user = userList[i]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;editor.putString("username-"+i,user.username);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;editor.putString("date-"+i,user.date);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;editor.apply();&nbsp; &nbsp; }}有了这个,您可以保存三个用户,然后使用用户名-(用户编号)从共享首选项中调用它们
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java