Lưu trữ dữ liệu của một ứng dụng Android- Shared Preference

nuong

Thành viên
Tham gia
16/5/2011
Bài viết
0
Để sử dụng sở thích chia sẻ, bạn phải gọi một phương pháp getSharedPreferences() trả về một thể hiện SharedPreference trỏ đến tập tin có chứa các giá trị ưu đãi.

Mã:
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
Tham số đầu tiên là khóa và tham số thứ hai là MODE. Ngoài phần có chế độ private, có những chế độ có sẵn dưới đây:

STT Mode và mô tả
1 MODE_APPEND
Điều này sẽ nối các ưu đãi mới với những ưu đãi đã được hiện tại
2 MODE_ENABLE_WRITE_AHEAD_LOGGING
Cơ sở dữ liệu cờ mở. Khi nó được thiết lập, nó sẽ cho phép write trước đăng nhập mặc định
3 MODE_MULTI_PROCESS
Phương pháp này sẽ kiểm tra sửa đổi ưu đãi ngay cả khi dụ sharedpreference đã được nạp
4 MODE_PRIVATE
Bằng cách thiết lập chế độ này, các tập tin chỉ có thể được truy cập bằng cách sử dụng ứng dụng gọi điện thoại
5
MODE_WORLD_READABLE
Chế độ này cho phép ứng dụng khác để đọc các sở thích

6 MODE_WORLD_WRITEABLE
Chế độ này cho phép ứng dụng khác để viết các ưu đãi
Bạn có thể lưu trữ một số thứ trong sharedpreferences bằng cách sử dụng lớp SharedPreferences.Editor. Bạn sẽ gọi phương thức chỉnh sửa của trường hợp SharedPreference và sẽ nhận nó trong một đối tượng đã được biên tập. Cú pháp sau:

Mã:
Editor editor = sharedpreferences.edit();
editor.putString("key", "value");
editor.commit();

Ngoài phương pháp putString, dưới đây có những phương thức có sẵn trong lớp editor, cho phép thao tác dữ liệu trong shared preferences. Chúng được liệt kê dưới đây:

STT Mode và mô tả
1 apply()
Nó là một phương pháp trừu tượng. Nó sẽ cam kết thay đổi của bạn trở lại từ trình soạn thảo để các đối tượng sharedPreference bạn đang gọi
2 clear()
Nó sẽ loại bỏ tất cả các giá trị từ các biên tập viên
3 remove(String key)
Nó sẽ loại bỏ các giá trị mà trọng điểm đã được thông qua như là một tham số
4 putLong(String key, long value)
Nó sẽ tiết kiệm được một giá trị lâu dài trong một trình soạn thảo ưa thích
5 putInt(String key, int value)
Nó sẽ tiết kiệm được một giá trị số nguyên trong một trình soạn thảo ưa thích
6 putFloat(String key, float value)
Nó sẽ tiết kiệm được một giá trị float trong một trình soạn sở thích

Ví dụ

Ví dụ dưới đây chứng minh cách sử dụng Shared Preferences. Nó hiển thị một màn hình với một số trường text, nó có giá trị được lưu trữ khi mà ứng dụng được đóng và đưa lại về nơi mà nó được bắt đầu.

Để thử nghiệm với ví dụ này, bạn cần phải chạy trên một thiết bị thực tế trên sau khi phát triển các ứng dụng theo các bước dưới đây:

Các bước Mô tả
1 Bạn sẽ sử dụng Android studio để tạo ra một ứng dụng Android dưới một gói com.example.sairamkrishna.myapplication. Trong khi tạo dự án này, chắc chắn bạn Target SDK và biên dịch với các phiên bản mới nhất của Android SDK sử dụng các cấp cao hơn của các API.
2 Sửa file src/MainActivity.java thêm mã tiến để hiển thị hộp thoại tiến triển kéo sợi.
3 Sửa file res/layout/activity_main.xml thêm mã XML tương ứng.
4 Chạy ứng dụng và chọn một thiết bị Android chạy và cài đặt các ứng dụng trên nó và kiểm tra kết quả.


Nội dung file MainActivity.java.
Mã:
package com.example.sairamkrishna.myapplication;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {
EditText ed1,ed2,ed3;
Button b1;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "nameKey";
public static final String Phone = "phoneKey";
public static final String Email = "emailKey";
SharedPreferences sharedpreferences;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

ed1=(EditText)findViewById(R.id.editText);
ed2=(EditText)findViewById(R.id.editText2);
ed3=(EditText)findViewById(R.id.editText3);

b1=(Button)findViewById(R.id.button);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String n = ed1.getText().toString();
String ph = ed2.getText().toString();
String e = ed3.getText().toString();

SharedPreferences.Editor editor = sharedpreferences.edit();

editor.putString(Name, n);
editor.putString(Phone, ph);
editor.putString(Email, e);
editor.commit();
Toast.makeText(MainActivity.this,"Thanks",Toast.LENGTH_LONG).show();
}
});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.

int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

Nội dung file hoạt động chính res/layout/activiy_main.xml.
Mã:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Shared Preference "
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="35dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials Point"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:textSize="35dp"
android:textColor="#ff16ff01" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_below="@+id/textView2"
android:layout_marginTop="67dp"
android:hint="Name"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText2"
android:layout_below="@+id/editText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:hint="Pass" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText3"
android:layout_below="@+id/editText2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:hint="Email" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:id="@+id/button"
android:layout_below="@+id/editText3"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp" />

</RelativeLayout>

Nội dung file res/values/strings.xml.
Mã:
<resources>
<string name="app_name">My Application</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
</resources>

Dưới đây là file mặc định AndroidManifest.xml.
Mã:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name=".MainActivity"
android:label="@string/app_name" >

<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

</activity>

</application>
</manifest>

Kết quả:
shared-prefernce-1.png



Chọn thiết bị để hiển thị kết quả, chỉ điền vào trường text. Điền nội dung ngẫu nhiên như hình dưới đây:
shared-prefernce-2.jpg


Bây giờ khi bạn ấn nút save, các dòng văn bản sẽ được lưu trữ trong shared preferences. Bây giờ ấn nút back và exit ứng dụng. Bạn mở nó lần nữa và sẽ nhìn thấy các dòng văn bản mà bạn vừa mới viết khi quay trở lại ứng dụng.
shared-prefernce-3-1024x487.png


Trung tâm đào tạo học lap trinh android với đội ngũ giáo viên trẻ, nhiệt tình và đào tạo học php cơ bản nâng cao tại VietPro!
 
×
Quay lại
Top