.Bộ nhớ chia sẻ

Một phần của tài liệu tìm hiểu hệ điều hành android và xây dựng ứng dụng minh họa (Trang 45)

Để lưu trữ dữ liệu trong Android ngồi cách sử dụng SQLite Database như đã nói ở trên, cịn có các cách sau:

3.6.1. Shared Preferences: Lưu trữ dữ liệu nguyên thủy bằng cặp key-value

Trong trường hợp này ta sẽ sử dụng lớp Shared Preferences, có hai phương thức để lấy đối tượng Shared Preferences là:

getSharePreferences(): nếu có nhiều file preference, tham số đầu tiên là tên file getPrefernces(): nếu chỉ có một file preference

Để ghi vào ta mở Shared Preferences.Editor bằng lệnh edit(), thêm vào bằng lệnh putBoolean(),

46 Đọc dữ liệu dùng lệnh getBoolean(), getString(), …

Ví dụ minh họa: TextView text;

@Override

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.ducanh); text = (TextView)findViewById(R.id.text); SharedPreferences sp = getSharedPreferences("demo", 0); Editor editor = sp.edit();

editor.putString("color", "green"); editor.commit();

Button btnGetColor = (Button)findViewById(R.id.btnGetColor); btnGetColor.setOnClickListener(new OnClickListener() {

public void onClick(View v) {

// TODO Auto-generated method stub

SharedPreferences sp = getSharedPreferences("demo", 0); text.setText("Color: "+ sp.getString("color", null)); }

}); }

47

File demo.xml được lưu trong thư mục Data > data > ứng dụng > shared_prefs

Nôi dung file demo.xml

3.6.2. Internal Storeage:

Lưu trữ dùng bộ nhớ trong, chỉ có thể dùng bởi ứng dụng tạo ra nó, khi hủy cài đặt ứng dụng nó sẽ bị xóa theo.

Để tạo file dùng lệnh openFileOutput(FILENAME, MODE), câu lệnh trả về đối tượng

FileOutputStream

Để ghi ta dùng lệnh write() sau đó close() để hồn tất.

Để đọc ta dùng lệnh openFileInput() tham số là tên file nó sẽ trả lại đối tượng FileInputStream, sau đó ta dùng lệnh read(), dùng lệnh close() để đóng.

Ta có thể thêm file trong thời điểm đang tạo ứng dụng bằng cách copy vào thư mục res/raw/ Mở dùng lệnh openRawResourcce(R.id.<fileID>) nó sẽ trả về đối tượng InputStream

48

getFileDir(): đường dẫn đến file đã lưu. deleteFile(): xóa file.

fileList(): trả về mảng các file được lưu trữ

3.6.3. External Storeage: Lưu trữ sử dụng bộ nhớ mở rộng

Để kiểm tra tình trạng xem bộ nhớ mở rộng có thể đọc ghi ta dùng lệnh

getExternalStorageState()

Với API >= 8 ta dùng lệnh getExternalFileDir() để mở file, có tham số type là loại thư mục con trong bộ nhớ mở rộng, ví dụ : DIRECTORY_MUSIC.

Với API <=7 ta dùng lệnh getExternalStorageDirectory() để mở file. File được lưu trong thư mục

/Android/data/<package_name>/files/, thư mục này bị xóa với API >=8;

Để tạo ra file khơng bị xóa khi hủy cài ứng dụng ta có thể dùng

getExternalStoragePublicDirectory() với API >=8 và getExternalStorageDirectory() với API <=

49 IV- ỨNG DỤNG MINH HỌA

1. Giới thiệu ứng dụng

Bài báo cáo xin trình bày minh họa ứng dụng học từ mới với các chức năng:

 Thêm, sửa xóa, tìm kiếm từ mới

 Tạo một bài kiểm tra nhỏ với số câu được nhập bởi người dùng, có thể chọn chế độ có giới hạn thời gian hoặc là không.

2. Thiết kế ứng dụng

Ứng dụng Android được tạo thành từ các Activity (các màn hình tương tác với người dùng), các lớp giao diện sẽ được kế thừa từ lớp Activity gốc, giao diện được định nghĩa trong các file XML riêng biệt.

Đầu tiên là giao diện màn hình chính của ứng dụng như sau:

Màn hình có TextView “Xin chào”, hình chào mừng và các nút (Button) để thêm, tìm kiếm từ mới, vào mục tạo bài kiểm tra, một nút trợ giúp cho biết số từ có trong ứng dụng và một nút thoát khỏi ứng dụng.

Trong file XML ta khai báo một Linearlayout với thuộc tính Vertical xếp các nội dung theo chiều dọc. Để tiện lợi, ta sẽ chỉ định phương thức sẽ thực hiện khi nhấn nút ngay trong file XML (main.xml) chi tiết như sau:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Xin chào !" android:background="#1589FF" android:textColor="#FFFC17" android:textSize="20dp"/>

50 <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/welcome"/> <Button android:id="@+id/home_add" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Thêm từ mới" android:textColor="#0000FF" android:onClick="clickAdd"/> <Button android:id="@+id/home_search" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Tìm kiếm" android:textColor="#0000FF" android:onClick="clickSearch"/> <Button android:id="@+id/home_test" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Bài kiểm tra"

android:textColor="#0000FF" android:onClick="clickTest"/> <Button android:id="@+id/home_help" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Trợ giúp" android:textColor="#0000FF" android:onClick="clickHelp"/> <Button android:id="@+id/home_quit" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Thoát" android:textColor="#0000FF" android:onClick="clickQuit"/> </LinearLayout>

File java chính sẽ có nội dụng như sau: package apt.tutorial.newword; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.View;

51

public class NewWord extends Activity { @Override

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);

setContentView(R.layout.main); }

public void clickAdd(View v) {

Intent add_word = new Intent(this, Add_Word.class); startActivity(add_word);

}

public void clickSearch(View v) {

Intent search_word = new Intent(this, Search_Word.class); startActivity(search_word);

}

public void clickTest(View v) {

Intent test = new Intent(this, Test_Word.class); startActivity(test);

}

public void clickHelp(View v) {

Intent help = new Intent(this, Help.class); startActivity(help);

}

public void clickQuit(View v) {

finish(); }

}

Phương thức clickAdd(View v) được gọi khi nhấn nút “Thêm từ mới” khi đó nó sẽ khởi

tạo một đối tượng Intent gọi đến class Add_Word tức là gọi màn hình thêm từ mới và thực hiện bằng phương thức startActivity().

53

Trong ứng dụng minh họa này ta sẽ sử dụng SQLite để lưu trữ từ mới làm nguồn từ cho bài kiểm tra và lưu trữ kết quả kiểm tra.

Ta tạo một lớp ví dụ là MyDBHelper kế thừa từ lớp SQLiteOpenHelper. Lớp này sẽ cho phép

thao tác chèn, sửa, xóa, truy vấn bảng dữ liệu. Bảng dữ liệu được tạo trong hàm

onCreate(SqliteDatabase db) bằng câu lệnh db.execSQL(“chuỗi lệnh tạo bảng”). Ta cũng viết

trong lớp này các hàm chèn, sửa, xóa, các câu lệnh truy vấn, cập nhật từ mới. Thao tác sử dụng phương thức getReadableDatabase(), hoặc getWriteableDatabase() (trả lại đối tượng thuộc lớp SqliteDatabase ). Ví dụ phương thức thêm từ mới:

public boolean insert(String word, String description) { if(!isExist(word))

{

ContentValues cv = new ContentValues(); cv.put(COL1_TABLE1, word); cv.put(COL2_TABLE1, description); getWritableDatabase().insert(TABLE1, COL2_TABLE1, cv); updateTotal(true); return true; } return false; } Phương thức xóa từ:

public void delete(String word) {

getWritableDatabase().delete(TABLE1, COL1_TABLE1+ " =?",

new String[] { word });

updateTotal(false); }

54 Phương thức cập nhật từ:

public void update(String word, String new_description)

{

ContentValues cv = new ContentValues(); cv.put(COL2_TABLE1, new_description);

getWritableDatabase().update(TABLE1, cv, COL1_TABLE1 + " =? ", new String [] {word});

}

Lấy toàn bộ dữ liệu trong bảng trả về dạng con trỏ:

public Cursor fetchAll(String table)

{

Cursor c = null; String query = null;

if(table.equalsIgnoreCase(TABLE2))

{

query = "SELECT * FROM " + table +";";

c = getReadableDatabase().rawQuery(query, null); }

else if(table.equalsIgnoreCase(TABLE1))

{

query = "SELECT * FROM " + table + " WHERE "+ COL1_TABLE1+ " <>?"; c = getReadableDatabase().rawQuery(query, new String [] {"__"}); }

return c;

}

Với chức năng tạo một bài kiểm tra có giới hạn thời gian, để cập nhật thời gian trên màn hình ta sẽ tạo luồng mới để đếm thời gian. Trong bài báo cáo này minh họa sử dụng lớp AsyncTask để tạo luồng Background và thao tác với giao diện chính như sau:

class MyAsyncTask extends AsyncTask<Void, Integer, Void>

{

int time_update = 0;

@Override

protected Void doInBackground(Void... params) {

// TODO Auto-generated method stub

while(time_update > 0) { SystemClock.sleep(1000); time_update--; publishProgress(time_update); } return null; } @Override

protected void onProgressUpdate(Integer... values) {

// TODO Auto-generated method stub

super.onProgressUpdate(values);

time_view.setText("Time "+ second2minute(values[0])); }

55 @Override

protected void onPreExecute() {

// TODO Auto-generated method stub

super.onPreExecute();

time_update = TIME_PER_TASK*numberTask; }

@Override

protected void onPostExecute(Void result) {

// TODO Auto-generated method stub

super.onPostExecute(result);

flag = false;

task.setText("Hết giờ ! Ấn kết thúc để xem kết quả !"); answer.setEnabled(false);

btn.setText("Kết thúc"); }

}

Hàm onPreExecute() thực hiện các công việc trước khi chạy luồng background và có thể thao tác với dữ liệu trên luồng chính, trong trường hợp này là gán giá trị cho biến time_update.

Hàm doInBackground() làm các công việc của luồng Background và gửi dữ liệu đến giao diện bằng phương thức publishProgress(), trong ví dụ này là gửi biến đếm đến giao diện.

Hàm onProgressUpdate() nhận dữ liệu từ luồng background và cập nhật lên giao diện, trong trường hợp ví dụ là cập nhật thời gian lên giao diện.

Hàm onPostExecute() thực hiện các công việc sau khi luồng background thực hiện xong, trong ví dụ thì nó đưa ra thơng báo hết giờ và khóa các giao diện khơng cho người dùng nhập câu trả lời.

56 V- KẾT LUẬN

Với đặc tính mạnh mẽ là một nền tảng mở, lại được Google hỗ trợ cùng các công cụ tiện lợi, việc phát triển ứng dụng trên hệ điều hành Android có rất nhiều thuận lợi cho các nhà phát triển thỏa sức sáng tạo những ứng dụng phục vụ nhu cầu đa dạng của cuộc sống.

VI- TÀI LIỆU THAM KHẢO 1. Pramatic - Hello Android – 2008 1. Pramatic - Hello Android – 2008

2. Beginning Android 2 - Mark L.Murphy – 2010 3. Android Deverloper Website : developer.android.com

Một phần của tài liệu tìm hiểu hệ điều hành android và xây dựng ứng dụng minh họa (Trang 45)

Tải bản đầy đủ (PDF)

(56 trang)