Trình đơn (menu) và hộp thoại (dialog)

Một phần của tài liệu Bài giảng lập trình di động android (Trang 105)

4.2.1. Sử dụng trình đơn (menu)

Trình đơn dùng để hiển thị các hành động thường ít dùng hơn và không hiển thị trực tiếp lên màn hình. Trong Android có 2 loại trình đơn:

- Trình đơn chính (options menu) – hiển thị các hành động liên quan đến toàn bộ

Activity hiện tại. Trong Android, để kích hoạt trình đơn này, ta bấm phím Menu của thiết bị (phím cứng hoặc phím ảo trên màn hình)

- Trình đơn ngữ cảnh (context menu) – hiển thị các hành động liên quan đến một

view cụ thể trên màn hình, trình đơn này được kích hoạt bằng cách bấm và giữ (long tap) trên view để kích hoạt trình đơn ngữ cảnh.

Về mặt lập trình, 2 loại menu này sử dụng cùng một lớp (android.view.Menu) và chứa các đối tượng giống nhau (android.view.MenuItem), vì vậy ta tạo sẵn 2 phương thức để dùng chung cho 2 loại menu này. Để tạo menu với các item bên trong và xử lý sự kiện bấm vào từng item như dưới đây:

Hàm createMenu() dùng để thêm 7 items vào menu có sẵn:

private void createMenu(Menu menu) {

menu.setQwertyMode(true);

MenuItem mnu1 = menu.add(0, 0, 0, "Item 1"); mnu1.setAlphabeticShortcut('a');

MenuItem mnu2 = menu.add(0, 1, 1, "Item 2"); mnu2.setAlphabeticShortcut('b');

MenuItem mnu3 = menu.add(0, 2, 2, "Item 3"); mnu3.setAlphabeticShortcut('c'); mnu3.setIcon(R.mipmap.ic_launcher); menu.add(0, 3, 3, "Item 4"); menu.add(0, 4, 4, "Item 5"); menu.add(0, 5, 5, "Item 6"); menu.add(0, 6, 6, "Item 7"); }

Hàm menuChoice để xử lý sự kiện tương ứng với menu item được lựa chọn (truyền vào dạng tham số). Với mục đích minh họa, khi một menu item được chọn, ta chỉ đơn gian hiển thị tên của item đó dưới dạng Toast.

private boolean menuChoice(MenuItem item) { switch (item.getItemId()) {

case 0:

Toast.makeText(this, "You choose on Item 1", Toast.LENGTH_LONG).show(); default:

Toast.makeText(this, "You click Item id = " + item.getItemId(), Toast.LENGTH_LONG).show(); return true;

} }

ThS. Bùi Trung Úy 106

Trình đơn chính (options menu)

Để hiển thị trình đơn chính, ta nạp chồng hàm onCreateOptionMenu() của Activity và thêm các menu item vào đối tượng menu (trong tham số của hàm):

@Override

public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu);

// Tạo menu createMenu(menu); return true;

}

Để hiển thị menu này lúc chạy ứng dụng, ta bấm phím MENU của thiết bị hoặc nút More (3 chấm đứng) trên Actionbar.

Để xử lý sự kiện khi chọn một item trong menu, ta cần nạp chồng hàm: @Override

public boolean onOptionsItemSelected(MenuItem item) {

return menuChoice(item); }

Trình đơnngữ cảnh (context menu)

Để hiển thị trình đơn ngữ cảnh, ta nạp chồng hàm onCreateContextMenu() và thêm các menu item vào đối tượng menu (trong tham số của hàm):

@Override

public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {

super.onCreateContextMenu(menu, view, menuInfo); createMenu(menu);

}

ThS. Bùi Trung Úy 107 @Override

public boolean onContextItemSelected (MenuItem item) {

return menuChoice(item); }

Để gắn menu ngữ cảnh này cho một đối tượng (chẳng hạn, nút bấm button), ta thêm code sau vào hàm onCreate của activity:

Button btn = (Button) findViewById(R.id.button1); btn.setOnCreateContextMenuListener(this);

Để hiển thị menu này lúc chạy ứng dụng, ta nhấn và giữ lên trên đối tượng, trình đơn hiện ra như hình bên dưới:

4.2.2. Sử dụng hộp thoại (dialog)

Trong rất nhiều trường hợp chúng ta cần hiển thị thông báo, hỏi xác nhận của người dùng, hiển thị trạng thái chờ… ở dạng hộp thoại nhanh hiện lên trên Activity hiện tại, mà không cần mở ra Activity mới, khi đó ta cần nạp chồng hàm onCreateDialog() của Activity.

Ví dụ dưới đây mô tả cách tạo một hộp thoại cơ bản như vậy: CharSequence[] items = { "Google", "Apple", "Microsoft" };

boolean[] itemsChecked = new boolean [items.length]; @Override

protected Dialog onCreateDialog(int id) { switch (id) {

case 0:

return new AlertDialog.Builder(this) .setIcon(R.mipmap.ic_launcher) .setTitle("This is a dialog") .setPositiveButton("OK",

new DialogInterface.OnClickListener() {

ThS. Bùi Trung Úy 108 Toast.makeText(getBaseContext(), "OK clicked!",

Toast.LENGTH_SHORT).show(); }

})

.setNegativeButton("Cancel",

new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int whichButton) { Toast.makeText(getBaseContext(), "Cancel clicked!", Toast.LENGTH_SHORT).show();

} })

.setMultiChoiceItems(items, itemsChecked,

new DialogInterface.OnMultiChoiceClickListener() { public void onClick(DialogInterface dialog, int which, boolean isChecked) {

Toast.makeText(getBaseContext(), items[which] +

(isChecked ? " checked!":" unchecked!"), Toast.LENGTH_SHORT).show(); }

}).create(); }

return null; }

Để hiển thị dialog ta viết sự kiện cho một nút bấm và gọi hàm showDialog(id). Kết quả chạy ứng dụng và bấm vào nút, hộp thoại như hình bên dưới sẽ hiện ra:

Trong ví dụ trên ta đã nạp chồng phương thức onCreateDialog(int id) để hiển thị hộp thoại khi có yêu cầu. Trong Activity có thể hiển thị nhiều hộp thoại khác nhau tùy vào ngữ cảnh xử lý như hộp thoại thông báo, hộp thoại xác nhận, hộp thoại tiến trình…, tham số id trong phương thức onCreateDialog là để phân biệt hộp thoại nào cần được hiện lên.

Để kích hoạt yêu cầu mở hộp thoại, ta gọi phương thức showDialog(id). Trong hàm onCreateDialog, tùy thuộc vào id truyền vào mà ta hiển thị hộp thoại tương ứng, trong ví dụ trên là hộp thoại có id = 0. Trong trường hợp này ta sử dụng loại hộp thoại đơn giản nhất là AlertDialog, để tạo ra một hộp thoại loại này, ta tạo ra một object của class AlertDialog.Builder và gọi phương thức create() của nó. Đoạn code trên thiết lập

ThS. Bùi Trung Úy 109

2 nút bấm cho hộp thoại cho trường hợp đồng ý (nút “OK” – setPositiveButton) và hủy bỏ (nút “Cancel” – setNegativeButton), cũng như thiết lập các ô checkbox (setMultiChoiceItems)

Các hàm xử lý sự kiện trong Dialog trong ví dụ chỉ đơn giản là hiển thị lên màn hình dòng thông báo dạng text trong một khoảng thời gian ngắn. Dạng thông báo này

trong Android gọi là Toast - là đoạn chữ hiển thị ở giữa, phía dưới màn hình trong

khoảng vài giây. Toast thường được dùng để hiển thị các loại thông báo ngắn, ít quan trọng như thông báo SMS, lưu dữ liệu thành công,…

4.3. Các điều khiển hiển thị dạng danh sách 4.3.1. Sử dụng ListView 4.3.1. Sử dụng ListView

ListView là một view group, hiển thị các thành phần (elements) theo một danh sách, có thể cuộn được theo chiều thẳng đứng. ListView là một view quan trọng, nó được sử dụng rộng rãi trong các ứng dụng Android.

Một ví dụ đơn giản của ListView là danh bạ liên lạc, nơi bạn có một danh sách các số điện thoại liên lạc hiển thị trong một ListView.

Các bước để to và s dng

* Bước 1: Khai báo ListView trong giao diện

Tương tự như các view khác, có thể dùng kéo-thả hoặc viết trong XML: <ListView

android:id="@+id/listProduct"

android:layout_width="match_parent" android:layout_height="match_parent" />

* Bước 2: Xác định cách hiển thỉ các phần tử (List-item)

Một ListView được tạo từ một danh sách các list-item. List-item là một dòng (row) riêng lẻ trong listview nơi mà dữ liệu sẽ được hiển thị. Bất kỳ dữ liệu nào trong listview chỉ được hiển thị thông qua list-item.

* Bước 3: Xây dựng nguồn cấp dữ liệu (Adapter)

Sau khi có một adapter cần thiết lập cho ListView, trong onCreate của Activity, ta gán Adapter này cho listView như sau:

ThS. Bùi Trung Úy 110

listView.setAdapter(productAdapter);

Khi đã gán Adapter vào ListView, thì ListView sẽ dùng Adapter này xác định cần hiển thị bao nhiêu phần tử, mỗi phần tử có view như thế nào (list-item) do Adapter tạo và gắn vào ListView, mỗi khi dữ liệu do Adapter quản lý thay đổi, cần thông báo cho ListView biết mà cập nhật bằng cách gọi:

listAdapter.notifyDataSetChanged();

Xây dựng ListView đơn giản

Ta sẽ xem xét ListView trong trường hợp đơn giản nhất: hiển thị danh sách các phần tử dạng chữ.

- Tạo một Activity mới là ListViewActivity.java. - Tạo giao diện với ListView bên trong như sau:

activity_list_view.xml: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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"> <ListView android:id="@+id/listView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" /> </RelativeLayout>

- Tiếp theo ta sẽ sử dụng Adapter và List-item định nghĩa sẵn trong Android

+ android.R.layout.simple_list_item_1: Là một hằng số list-item định nghĩa sẵn, đây là loại list-item chỉ hiển thị duy nhất một TextView.

+ Sử dụng ArrayAdapter để cung cấp nguồn dữ liệu cho listview. Trong onCreate

của Activity, ta gán adapter này như sau: ArrayAdapter<String> arrayAdapter

ThS. Bùi Trung Úy 111 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1 , <values>);

listView.setAdapter(arrayAdapter);

Code hoàn chỉnh của ListViewActivity là: package com.example.helloandroid;

import android.support.v7.app.AppCompatActivity; import android.os.Bundle;

import android.widget.ArrayAdapter; import android.widget.ListView;

public class ListViewActivity extends AppCompatActivity { @Override

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

setContentView(R.layout.activity_list_view);

ListView listView = (ListView)findViewById(R.id.listView);

String[] users = new String[]{"Tom (Admin)", "Jerry (Users)", "Donald (Guest)"}; ArrayAdapter<String> arrayAdapter

= new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1 , users); listView.setAdapter(arrayAdapter);

} }

Chạy ứng dụng ta có kết quả:

Ngoài ra, Android còn cung cấp một số các list-item đơn giản khác để sử dụng với ArrayAdapter là:

+ android.R.layout.simple_list_item_checked

ThS. Bùi Trung Úy 112

Xây dng tùy biến ListView nâng cao

Xét ví dụ, để hiển thị danh sách các quốc gia. Với các listItem và adapter như sau:

ThS. Bùi Trung Úy 113 list_item_layout.xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:id="@+id/imageView_flag" android:layout_width="64dp" android:layout_height="64dp" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_marginLeft="5dp" android:layout_marginRight="5dp" android:layout_marginTop="5dp" /> <TextView android:id="@+id/textView_countryName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="Country Name" android:layout_alignParentTop="true" android:layout_toRightOf="@+id/imageView_flag" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:layout_above="@+id/textView_population" android:layout_margin="5dp" /> <TextView android:id="@+id/textView_population" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceSmall" android:text="Population: ..." android:layout_alignBottom="@+id/imageView_flag" android:layout_alignLeft="@+id/textView_countryName" android:layout_alignStart="@+id/textView_countryName" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:layout_margin="5dp" /> </RelativeLayout>

- Xây dựng lớp CustomListAdapter tùy biến thừa kế từ lớp BaseAdapter, nó làm nhiệm vụ hiển thị dữ liệu lên các List-item. Ta cũng tạo lớp Country để chứa dữ liệu của mỗi country trên mỗi hàng.

ThS. Bùi Trung Úy 114

Country.java

package com.example.helloandroid; public class Country {

private String countryName; private String flagName; private int population;

public Country(String countryName, String flagName, int population) { this.countryName= countryName;

this.flagName= flagName; this.population= population; }

public int getPopulation() { return population; }

public String getCountryName() { return countryName;

}

public String getFlagName() { return flagName;

}

@Override

public String toString() {

return this.countryName+" (Population: "+ this.population+")"; } } CustomListAdapter.java package com.example.helloandroid; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View;

ThS. Bùi Trung Úy 115 import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import java.util.List;

public class CustomListAdapter extends BaseAdapter { private List<Country> listData;

private LayoutInflater layoutInflater; private Context context;

public CustomListAdapter(Context ctx, List<Country> listData) { this.context = ctx;

this.listData = listData;

layoutInflater = LayoutInflater.from(ctx); }

@Override

public int getCount() { return listData.size(); }

@Override

public Object getItem(int position) { return listData.get(position); }

@Override

public long getItemId(int position) { return position;

}

public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder;

if (convertView == null) {

convertView = layoutInflater.inflate(R.layout.list_item_layout, null); holder = new ViewHolder();

holder.flagView = (ImageView) convertView.findViewById(R.id.imageView_flag); holder.countryNameView = (TextView)

convertView.findViewById(R.id.textView_countryName);

holder.populationView = (TextView) convertView.findViewById(R.id.textView_population); convertView.setTag(holder);

} else {

holder = (ViewHolder) convertView.getTag(); }

Country country = this.listData.get(position);

holder.countryNameView.setText(country.getCountryName());

holder.populationView.setText("Population: " + country.getPopulation()); int imageId = this.getImageResIdByName(country.getFlagName()); holder.flagView.setImageResource(imageId);

return convertView; }

ThS. Bùi Trung Úy 116 public int getImageResIdByName(String resName) {

String pkgName = context.getPackageName();

int resID = context.getResources().getIdentifier(resName, "drawable", pkgName); return resID;

}

static class ViewHolder { ImageView flagView; TextView countryNameView; TextView populationView; } } ListViewActivity.java package com.example.helloandroid; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import java.util.List;

public class ListViewActivity extends AppCompatActivity {

@Override

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

setContentView(R.layout.activity_list_view);

final ListView listView = (ListView)findViewById(R.id.listView); List<Country> countries = getListCountries();

listView.setAdapter(new CustomListAdapter(this, countries)); // Khi người dùng click vào các ListItem

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override

public void onItemClick(AdapterView<?> a, View v, int position, long id) { Object obj = listView.getItemAtPosition(position);

Country country = (Country) obj;

Toast.makeText(getBaseContext(), "Selected item " + country.getCountryName(), Toast.LENGTH_LONG).show();

} }); }

ThS. Bùi Trung Úy 117 private List<Country> getListCountries() {

List<Country> list = new ArrayList<Country>();

Country vietnam = new Country("Vietnam", "vi", 98000000); Country usa = new Country("United States", "us", 320000000); Country russia = new Country("Russia", "ru", 142000000); list.add(vietnam); list.add(usa); list.add(russia); return list; } } Chạy ứng dụng ta có kết quả: 4.3.2. Sử dụng SpinnerView

ListView rất tiện dụng cho việc hiển thị danh sách các phần tử đồng dạng. Tuy nhiên ListView chiếm tương đối nhiều diện tích trên màn hình. Trong thực tế có nhiều trường hợp ta chỉ cần hiển thị phần tử đang chọn của danh sách, khi bấm vào phần tử này, sẽ hiện ra danh sách đầy đủ các phần tử còn lại để ta lựa chọn. Để làm được việc này, ta dùng SpinnerView. Để dễ hình dung, ta có thể hiểu SpinnerView chính là ComboBox trong lập trình web và Windows Form.

Trong ví dụ dưới đây, ta hiển thị danh sách các phần tử đơn giản dạng chữ như ví dụ trước, tuy nhiên dùng SpinerView thay cho ListView.

Trước tiên ta thêm khai báo một SpinnerView trong file layout của Activity: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Spinner android:id="@+id/spinner1"

ThS. Bùi Trung Úy 118 android:layout_width="wrap_content"

android:layout_height="wrap_content" android:drawSelectorOnTop="true" /> </LinearLayout>

Sau đó, trong hàm onCreate của Activity, ta cần thêm mã nguồn để truy xuất đến SpinnerView này, đặt adapter cho nó và thêm hàm xử lý sự kiện khi ta chọn một phần tử của spinner: package com.example.helloandroid; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.Toast;

public class MainActivity extends AppCompatActivity { @Override

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

setContentView(R.layout.activity_main); // Spinner

Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);

final String[] users = new String[]{"Tom (Admin)", "Jerry (Users)", "Donald (Guest)"}; ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,

android.R.layout.simple_spinner_item, users); spinner1.setAdapter(adapter);

spinner1.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {

@Override

public void onItemSelected(AdapterView<?> arg0, View v, int position, long id) {

Toast.makeText(getBaseContext(), "You have selected item : " + users[position], Toast.LENGTH_SHORT).show();

}

@Override

public void onNothingSelected(AdapterView<?> arg0) { } });

} }

Khi một phần tử của SpinnerView được chọn, ta chỉ đơn thuần in lên màn hình thông báo dạng Toast. Chạy ứng dụng vừa tạo lên thiết bị hoặc emulator, ta sẽ quan sát thấy spinner view sẽ có dạng như sau:

ThS. Bùi Trung Úy 119

4.3.3. Sử dụng GridView

GridView giống với ListView nhưng có chức năng hỗ trợ hiển thị dữ liệu theo dạng lưới. GridView cũng dựa vào Adapter để gắn kết các dữ liệu bên dưới, điểm khác nhau là GridView có thiết lập số cột. Dữ liệu đưa vào dưới dạng mảng hay danh

sách, nhưng dựa vào số cột ta thiết lập mà nó tự động ngắt hàng dựa vào thuộc tính

numColums trong layout.

Ví dụ, tạo một gridView đơn giản hiển thị các phần tử dạng chử: - Thêm GridView vào layout của Activity:

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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"> <GridView

ThS. Bùi Trung Úy 120 android:id="@+id/gridView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:numColumns="3" > </GridView> </RelativeLayout>

- Trong hàm onCreate của Activity gắn apdapter cho GridView để hiển thị dữ liệu: @Override

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

setContentView(R.layout.activity_main);

final String[] users = new String[]{"Tom (Admin)", "Jerry (Users)", "Donald (Guest)", "Bui (Admin)", "Trung (Guest)", "Uy (Users)"};

// GridView

GridView gridView1 = (GridView) findViewById(R.id.gridView1); ArrayAdapter<String> adapter1 = new ArrayAdapter<String> (this, android.R.layout.simple_list_item_1, users); gridView1.setAdapter(adapter1);

// Khi người dùng click vào một phần tử

gridView1.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override

public void onItemClick(AdapterView<?> arg0, View v, int position, long id) { Toast.makeText(getBaseContext(), "You have selected item : " + users[position], Toast.LENGTH_SHORT).show();

} }); }

ThS. Bùi Trung Úy 121

Chương 5. QUẢN LÝ DỮ LIỆU TRONG ANDROID

Trong chương này, chúng ta s xem xét các cách thức lưu trữ d liu trong

Android. Lưu trữ d liu là mt tính năng quan trọng đối vi ng dng, giúp cho

người dùng có th dùng lại được nhng d liệu trước đó mà không cần ti li.

5.1. Dữ liệu trong Assets

Android Assets là thư mục chứa dữ liệu đầu vào. Chẳng hạn như âm thanh, hình ảnh, cơ sở dữ liệu hoặc các tập tin khác,... Những tập tin này sẽ không được biên dịch khi ứng dụng được đóng gói.

Để truy xuất được những tập tin trong thư mục assets, ta phải sử dụng bộ quản lý asset do Android cung cấp. Lớp này tên là AssetManager.

AssetManager assetManager = Context.getAssets();

AssetManager là lớp cung cấp quyền truy cập vào các tập tin không biên dịch của ứng dụng, cho phép bạn mở và đọc file nguyên gốc dưới dạng một luồng byte. Chẳng hạn, để truy xuất font chữ lưu trong thư mục Asset ta sử dụng như sau:

Typeface arial = Typeface.createFromAsset(assetManager, “font/arial.ttf”);

textView.setTypeface(arial);

Ví dụ, sau đây sẽ cho ta cái nhìn tổng quát về cách thức sử dụng AssetManager để truy xuất tập tin trên thư mục assets.

public void loadAssetsData() {

AssetManager assetManager = getAssets(); // To get names of all files inside the "Files" folder try {

String[] files = assetManager.list("Files"); for(int i=0; i<files.length; i++){

txtFileName.append("\n File :"+i+" Name => "+files[i]);} } catch (IOException e1) {

e1.printStackTrace(); }

ThS. Bùi Trung Úy 122 // To load text file

InputStream input; try {

input = assetManager.open("helloworld.txt"); int size = input.available();

byte[] buffer = new byte[size]; input.read(buffer);

input.close();

// byte buffer into a string String text = new String(buffer) txtView.setText(text); } catch (IOException e) { e.printStackTrace(); } // To load image try {

InputStream ims = assetManager.open("android_logo_small.jpg"); // create drawable from stream

Drawable d = Drawable.createFromStream(ims, null);

// set the drawable to imageview imageView.setImageDrawable(d); } catch(IOException ex) { e.printStackTrace(); } }

5.2. Dữ liệu trong SharedPreferences

SharedPreferences là một cơ chế cho phép bạn lưu trữ và đọc dữ liệu bằng các cặp khóa-giá trị (key-value), dữ liệu nó có thể lưu là ở dạng nguyên thuỷ như: int, float, string, boolean, long. Dữ liệu của Shared Preferences sẽ được lưu cục bộ ở trong

phạm vi ứng dụng, chính vì thế nếu xoá ứng dụng hoặc xoá dữ liệu của ứng dụng thì

dữ liệu này cũng sẽ bị xóa.

Đầu tiên, để lưu dữ liệu bạn cần khởi tạo một biến đối tượng kiểu Shared Preferences như sau:

SharedPreferences sharedPrefs = getSharedPreferences(<SharedName>, Context.MODE_PRIVATE);

Trong đó:

ThS. Bùi Trung Úy 123

Context.MODE_PRIVATE: là chế độ bảo mật dữ liêu trong Android, khi bạn để như vậy có nghĩa là bạn chỉ cho ứng dụng hiện tại truy cập vào file Shared Preferences này

Một phần của tài liệu Bài giảng lập trình di động android (Trang 105)