简体   繁体   中英

My data saves after I leave the app the first time, but after the second time, it doesn't save

I'm creating an app on android studio and I want to store user input into textview even after they close the app. I used SharedPreferences to store, load, and update data, but after I close the app the second time, it does not save the data I stored and instead shows: {}.

Is there a way I can fix this?

My code:

private String getUserName;

listTitle = (TextView)findViewById(R.id.listTitle);

    listTitle.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            View view = getLayoutInflater().inflate(R.layout.input_name_edittext, null);
            EditText name = (EditText)view.findViewById(R.id.name);

            builder.setView(view)
                    .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    })
                    .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                        @RequiresApi(api = Build.VERSION_CODES.N)
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            String nameInputted = name.getText().toString();
                            if(nameInputted.chars().filter(ch -> ch != ' ').count() <= 15){
                                saveName(nameInputted);
                                listTitle.setText(nameInputted);
                            }
                            else{
                                Toast.makeText(MainActivity.this,
                                        "Name is too long",
                                        Toast.LENGTH_LONG).show();
                            }
                        }
                    });
            builder.show();
        }

   loadName();
   updateName();

The methods:

public void saveName(String name) {
    SharedPreferences sharedPreferences = getSharedPreferences(preferenceName, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();

    editor.putString(HASHMAP_KEY, name);
    editor.apply();
}

public void loadName() {
    SharedPreferences sharedPreferences = getSharedPreferences(preferenceName, Context.MODE_PRIVATE);
    getUserName = sharedPreferences.getString(HASHMAP_KEY, "Name");
}

public void updateName() {
    listTitle.setText(getUserName);
}

Here is a way to do this in Kotlin using Shared Preferences

//get and set cache
        fun setCache(key: String, value: String) {
            val pref = context.getSharedPreferences(context.packageName, Context.MODE_PRIVATE)
            val editor = pref.edit()
            editor.putString(key, value)
            editor.apply()
        }

    fun getCache(key: String): String {
        val pref = context.getSharedPreferences(context.packageName, Context.MODE_PRIVATE)
        val defaultValue = "0"
        return pref.getString(key, defaultValue).toString()
    }

Then you can use them as

val textView = findViewById<TextView>(R.id.someTextView)
val someBtn = findViewById<Button>(R.id.someButton)

//save data from text view
someBtn.setOnClickListner{
    setCache("oldData", textView.text.toString())
}

//set data to text view
if (getCache("oldData").toInt() != 0) {
    //means there is some old data already, so use it
    textView.text = getCache("oldData")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM