Lập trình di động - Lab07: Data Storage

SharedPreferences dùng để lưu trạng thái của ứng dụng, dạng file xml. Lớp

SharedPreferences cung cấp một framework giúp bạn có thể lưu trữ và đọc lên

những cặp key-value liên tục dữ liệu đơn giản. Có thể dùng SharedPreferences với

những kiểu dữ liệu như: booleans, floats, ints, longs, strings.

pdf10 trang | Chia sẻ: tieuaka001 | Lượt xem: 626 | Lượt tải: 0download
Nội dung tài liệu Lập trình di động - Lab07: Data Storage, để tải tài liệu về máy bạn click vào nút DOWNLOAD ở trên
Ver 1.0 – 2016, FIT - HCMUP Lab 07: Data Storage Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 1 1 Thao tác dữ liệu với SharedPreferences SharedPreferences dùng để lưu trạng thái của ứng dụng, dạng file xml. Lớp SharedPreferences cung cấp một framework giúp bạn có thể lưu trữ và đọc lên những cặp key-value liên tục dữ liệu đơn giản. Có thể dùng SharedPreferences với những kiểu dữ liệu như: booleans, floats, ints, longs, strings. 1.1 Thao tác đọc/ghi 1.1.1 Ghi dữ liệu //Tạo đối tượng SharedPreferences SharedPreferences sp = getSharedPreferences(fileName, MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); //Lưu dữ liệu editor.putX(key, value); //X là kiểu dữ liệu //Ví dụ kiểu string editor.putString(“ten”,”kylh”); //Hoàn thành editor.commit(); 1.1.2 Đọc dữ liệu //Tạo đối tượng SharedPreferences SharedPreferences sp = getSharedPreferences(fileName, MODE_PRIVATE); //Đọc dữ liệu sp.getX(key, default); //X là kiểu dữ liệu //Ví dụ kiểu string String t = sp.getString(“ten”, “”); Ver 1.0 – 2016, FIT - HCMUP Lab 07: Data Storage Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 2 1.2 Thiết kế giao diện 1.3 Xử lý code đọc/ghi Nếu người dùng check chọn ghi nhớ: Tiến hành kiểm tra đăng nhập thành công (nếu có), lưu thông tin và mở màn hình (Activity) cá nhân. Ver 1.0 – 2016, FIT - HCMUP Lab 07: Data Storage Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 3 private void restoringPreferences() { SharedPreferences pre = this.getSharedPreferences(prefname, Context.MODE_PRIVATE); if(pre != null) { //lấy giá trị checked ra, nếu không thấy thì giá trị mặc định là false boolean bchk = pre.getBoolean("checked", false); if (bchk) { //lấy user, pwd, nếu không thấy giá trị mặc định là rỗng String user = pre.getString("user", "admin"); String pwd = pre.getString("pwd", "123"); txtUser.setText(user); txtPass.setText(pwd); } chkGhiNho.setChecked(bchk); } } private void savingPreferences(){ //tạo đối tượng getSharedPreferences SharedPreferences pre = this.getSharedPreferences(prefname, Context.MODE_PRIVATE); //tạo đối tượng Editor để lưu thay đổi SharedPreferences.Editor editor = pre.edit(); //Lưu trữ dữ liệu dạng key/value String user = txtUser.getText().toString(); String pwd = txtPass.getText().toString(); boolean bchk = chkGhiNho.isChecked(); if(!bchk) { //xóa mọi lưu trữ trước đó editor.clear(); } Ver 1.0 – 2016, FIT - HCMUP Lab 07: Data Storage Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 4 else { //lưu vào editor editor.putString("user", user); editor.putString("pwd", pwd); editor.putBoolean("checked", bchk); } //chấp nhận lưu xuống file editor.commit(); } 1.4 Gắn code cho các sự kiện 1.4.1 Xử lý cho LoginActivity @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); btnDangNhap = (Button)findViewById(R.id.btnDangNhap); txtUser = (TextView)findViewById(R.id.txtUser); txtPass = (TextView)findViewById(R.id.txtPass); chkGhiNho = (CheckBox)findViewById(R.id.chkGhiNho); btnDangNhap.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //luu trang thai savingPreferences(); finish();//đóng màn hình hiện tại Intent mh = new Intent(LoginActivity.this, LoginSuccessActivity.class); //truyền dữ liệu qua màn hình mới mh.putExtra("user", txtUser.getText().toString()); startActivity(mh);//mở màn hình mới } }); } @Override protected void onPause() { Ver 1.0 – 2016, FIT - HCMUP Lab 07: Data Storage Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 5 super.onPause(); //gọi hàm lưu trạng thái savingPreferences(); } @Override protected void onResume() { super.onResume(); //gọi hàm đọc trạng thái ở đây restoringPreferences(); } 1.4.2 LoginSuccessActivity protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login_success); txtMsg=(TextView) findViewById(R.id.txtmsg); btnThoat=(Button) findViewById(R.id.btnThoat); btnThoat.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub finish(); } }); Intent i = getIntent(); txtMsg.setText("Hello : " + i.getStringExtra("user")); } Ver 1.0 – 2016, FIT - HCMUP Lab 07: Data Storage Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 6 1.5 Nơi lưu file Mở cửa sổ Android Device Monitor. Chọn thiết bị, mở Tab File Explorer; thư mục data/data//shared_prefs 2 Đọc ghi file Internal Storage – Bộ nhớ trong Android Internal Storage: Lưu trữ các dữ liệu cá nhân của từng ứng dụng và chỉ sử dụng cho riêng ứng dụng đó, các ứng dụng khác không thể truy cập vào được. Thông thường khi ứng dụng bị gỡ bỏ khỏi thiết bị Android, các file dữ liệu liên quan cũng bị xóa bỏ theo. 2.1 Mô tả kịch bản Ver 1.0 – 2016, FIT - HCMUP Lab 07: Data Storage Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 7  Bấm nút Write sẽ ghi thông tin xuống file ở bộ nhớ trong.  Bấm nút Read sẽ đọc thông tin từ file ở bộ nhớ trong hiển thị ra. 2.2 Thiết kế màn hình 2.3 Xử lý nút Read btnReadIS.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { FileInputStream fis = openFileInput("data.txt"); byte[] buffer = new byte[fis.available()]; fis.read(buffer); String data = new String(buffer); tvIS.setText(data); fis.close(); } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }); 2.4 Xử lý nút Write btnWriteIS.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { Ver 1.0 – 2016, FIT - HCMUP Lab 07: Data Storage Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 8 FileOutputStream fos = openFileOutput("data.txt", MODE_PRIVATE); fos.write((editText.getText() + "").getBytes()); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }); 2.5 Một số lưu ý 2.5.1 Các chế độ ghi Chế độ tạo file Mô tả MODE_PRIVATE Đây là chế độ mặc định, file ghi ra chỉ được sử dụng bởi ứng dụng tạo ra nó, hoặc chia sẻ với cùng User ID. MODE_APPEND Chế độ nối thêm dữ liệu vào file nếu nó đã tồn tại. MODE_WORLD_READABLE Các chế độ này rất nguy hiểm, nó giống như một lỗ hổng bảo mật trong Android, tốt nhất không nên sử dụng, bạn có thể sử dụng các kỹ thuật khác thay thế như:  ContentProvider  BroadcastReceiver  Service MODE_WORLD_WRITEABLE MODE_MULTI_PROCESS Chế độ cho phép nhiều tiến trình (process) có thể ghi vào file. Tuy nhiên khuyến nghị không sử dụng chế độ này vì nó không làm việc trên một số phiên bản của Android. Bạn có thể sử dụng kỹ thuật khác để thay thế, chẳng hạn:  ContentProvider 2.5.2 File đã tạo nằm ở đâu Vào menu Tool  Android  Android Device Monitor. Ver 1.0 – 2016, FIT - HCMUP Lab 07: Data Storage Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 9 Sau đó chọn thiết bị tương ứng (nếu có nhiều thiết bị) Ở cửa sổ File Explorer, chọn thư mục data/data//files 3 AutoComplete Bổ sung thêm control dạng AutoCompleteTextView. Thiết lập nguồn dữ liệu cho AutoCompleteTextView. txtAuto = (AutoCompleteTextView)findViewById(R.id.autoCompleteTextView); Ver 1.0 – 2016, FIT - HCMUP Lab 07: Data Storage Ths. Lương Trần Hy Hiến, KHOA CNTT – TRƯỜNG ĐH SƯ PHẠM TP. HCM 10 //set dữ liệu cho AutoCompleteTextView String[] dulieu = {"Quang Nam", "Quang Ngai", "Quang Binh", "Quang Tri", "Phan Rang", "Phu Quoc", "Binh Thuan", "Binh Thanh", "Binh Dai"}; ArrayAdapter adapter = new ArrayAdapter( MainActivity.this, android.R.layout.simple_list_item_1, dulieu ); txtAuto.setAdapter(adapter); Chạy thử ứng dụng: Bổ sung sự kiện TextChanged: txtAuto.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { txtDoc.setText(txtAuto.getText().toString()); } });

Các file đính kèm theo tài liệu này:

  • pdfmad_lab07_datastorage_992.pdf
Tài liệu liên quan