[:en]SharedPreferences
Step 1: activity_main.xml
Step 2: MainActivity.java
package com.example.cambridge.sharedpreferences; import android.content.Context; import android.content.SharedPreferences; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { EditText usernameInput; EditText passwordInput; TextView displaylabel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); usernameInput = (EditText)findViewById(R.id.userid); passwordInput = (EditText)findViewById(R.id.passwordid); displaylabel = (TextView)findViewById(R.id.displayid); } // Save the users login info public void saveData(View view){ // Create a private file SharedPreferences sharedPref = getSharedPreferences("userInfo", Context.MODE_PRIVATE); // Create an object SharedPreferences.Editor editor = sharedPref.edit(); //Store data with a key editor.putString("username", usernameInput.getText().toString()); editor.putString("password", passwordInput.getText().toString()); editor.apply(); Toast.makeText(this,"Saved!",Toast.LENGTH_LONG).show(); } // Print out the saved data public void displayData(View view){ SharedPreferences sharedPref = getSharedPreferences("userInfo", Context.MODE_PRIVATE); String name = sharedPref.getString("username", ""); String pw = sharedPref.getString("password", ""); displaylabel.setText(name + " " + pw); } }
Or simple way to remember:
//Store data with a key SharedPreferences sharedPref = getSharedPreferences("userInfo", Context.MODE_PRIVATE); loginstatus = "in"; SharedPreferences.Editor editor2 = sharedPref.edit(); editor2.putString("loginkey", loginstatus); editor2.apply(); // Recall stored data SharedPreferences sharedPref = getSharedPreferences("userInfo", Context.MODE_PRIVATE); loginstatus = sharedPref.getString("loginkey", ""); if (loginstatus.equals("in")){ startActivity(new Intent(MainActivity.this, menu.class)); } else { // do nothing }
[:]