Xây dựng ứng dụng Android sử dụng SharedPreferences để lưu trữ dữ liệu


XÂY DỰNG ỨNG DỤNG LƯU TRỮ DỮ LIỆU VỚI SHARED PREFERENCES

I. Mục tiêu

Giúp sinh viên hiểu rõ và lập trình với Shared Preferences để lưu trữ dữ liệu.

II. Nội dung

1. Yêu cầu: Viết ứng dụng như sau:

 

          Trong đó sử dụng Shared Preferences để lưu lại lịch sử tính toán và hiển thị trên TextView

          Button Clear để xóa lịch sử

 

2. Các bước thực hiện:

Bước 1: Tạo project mới và xây dựng giao diện activity_main.xml như sau:

 

Bước 2: Code java trong MainActivity.java

public class MainActivity extends AppCompatActivity {
    EditText
edta, edtb, edtkq;
    Button
btntong, btnclear;
    TextView
txtlichsu;
    String
lichsu = "";
   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView(R.layout.
activity_main);
       
edta = findViewById(R.id.edta);
       
edtb = findViewById(R.id.edtb);
       
edtkq = findViewById(R.id.edtkq);
       
btntong = findViewById(R.id.btntong);
       
btnclear = findViewById(R.id.btnclear);
       
txtlichsu = findViewById(R.id.txtlichsu);
       
//------Lấy lại dữ liệu trong SharedPreferences--------
       
SharedPreferences myprefs = getSharedPreferences("mysave",MODE_PRIVATE);
       
lichsu = myprefs.getString("ls","");
       
txtlichsu.setText(lichsu);
       
//------------------------------------------
       
btntong.setOnClickListener(new View.OnClickListener() {
           
@Override
           
public void onClick(View v) {
               
int a = Integer.parseInt(edta.getText().toString());
               
int b = Integer.parseInt(edtb.getText().toString());
               
int kq = a + b;
               
edtkq.setText(kq+"");
               
lichsu += a+" + "+b+" = "+kq;
               
txtlichsu.setText(lichsu);
                
lichsu +="\n"; // Xuống dòng
           
}
        });
       
btnclear.setOnClickListener(new View.OnClickListener() {
           
@Override
           
public void onClick(View v) {
               
lichsu ="";
               
txtlichsu.setText(lichsu);
            }
        });

    }
   
@Override
   
protected void onPause() {
       
super.onPause();
        SharedPreferences myprefs = getSharedPreferences(
"mysave",MODE_PRIVATE);
        SharedPreferences.Editor myedit = myprefs.edit();
        myedit.putString(
"ls",lichsu);
        myedit.commit();
    }
}

 

---------------------END -----------------

A - Z Sitemap /

Đào tạo, nghiên cứu gắn liền với khoa học và công nghệ nhằm tạo ra những sinh viên và học viên có lòng yêu nước, có phẩm chất nhân văn mang đậm bản sắc Việt Nam, có ý thức sinh hoạt cộng đồng, có sức khỏe, có năng lực và kỹ năng toàn diện, tự tin, năng động, sáng tạo và trở thành công dân khởi nghiệp mang tính toàn cầu.