Các điều khiển hiển thị dạng danh sách

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

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 và không một ứng dụng nào có quyền truy cập vào được.

Tiếp theo, tạo đối tượng editor từ biến sharedPrefs đã tạo ở trên, mục đích là để có thể mở file và đưa dữ liệu vào:

SharedPreferences.Editor editor = sharedPrefs.edit(); Để đưa dữ liệu vào chúng ta sử dụng như sau: editor.put<X>(String key, value)

Trong đó:

<X>: là kiểu dữ liệu bạn đưa vào, với Shared Preferences bạn có thể lưu ở nhưng kiểu dữ liệu như : float, string, int, boolean, long.

key: là tên đặt cho biến bạn sẽ lưu xuống. value: giá trị cần lưu.

Ví dụ:

SharedPreferences sharedPrefs = getSharedPreferences(“appSettings”, Context.MODE_PRIVATE);

SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putString("appName", "HelloAndroid"); editor.putBoolean("FirstLaunch", true); editor.putInt("HighScore",100); editor.putFloat("Mark", 9.5f); editor.putLong("Sound",90); editor.commit(); // hoặc: editor.apply();

Sau khi đã put dữ liệu xong thì bạn gọi hàm commit() hoặc là apply() để xác nhận những thay đổi. Sự khác nhau giữa commit() và apply() là:

commit(): hoạt động theo cơ chế đồng bộ, nếu như bạn khởi tạo 2 editor để chỉnh sửa dữ liệu thì editor nào thực hiện trước sẽ làm trước và cái nào đến sau sẽ làm sau. Và bạn sẽ được thông báo là true hay false nếu như thành công hoặc thất bại.

apply() : hoạt động theo cơ chế không đồng bộ, và dù có thành công hay không thì sẽ không nhận được kết quả trả về.

Thc hành vi shared Preferences:

Đây là một ví dụ về màn hình thiết lập thông số của một trò chơi trên Android, trước khi chơi bạn lựa chọn các thông số như độ sáng, mức độ âm lượng, và độ khó. Sau khi chơi xong bạn tắt trò chơi và có thể tiếp tục chơi vào ngày hôm sau. SharedPreferences cho phép bạn lưu lại các các thông số đã thiết lập trước đó, để cho phép khi chơi lại các thiết lập đó có thể sử dụng mà không cần phải thiết lập lại.

ThS. Bùi Trung Úy 124

Đọc dữ liệu settings từ Shared preferences:

private void loadGameSetting() {

SharedPreferences sharedPrefs = this.getSharedPreferences("gameSettings", Context.MODE_PRIVATE);

if(sharedPreferences!= null) {

int brightness = sharedPrefs.getInt("brightness", 90); int sound = sharedPrefs.getInt("sound",95);

int checkedRadioButtonId = sharedPrefs.getInt("checkedRadioButtonId", R.id.radioButton_medium); this.seekBarSound.setProgress(sound); this.seekBarBrightness.setProgress(brightness); this.radioGroupDiffLevel.check(checkedRadioButtonId); } }

Lưu dữ liệu setting vào Shared preferences.

public void saveGameSettings() {

SharedPreferences sharedPrefs= this.getSharedPreferences("gameSettings", Context.MODE_PRIVATE);

SharedPreferences.Editor editor = sharedPrefs.edit();

editor.putInt("brightness", this.seekBarBrightness.getProgress()); editor.putInt("sound", this.seekBarSound.getProgress());

// ID của RadioButton đang được chọn.

int checkedRadioButtonId = radioGroupDiffLevel.getCheckedRadioButtonId(); editor.putInt("checkedRadioButtonId", checkedRadioButtonId);

// Save. editor.apply(); }

ThS. Bùi Trung Úy 125

Việc lưu trữ dữ liệu Shared preferences là trong suốt với người dùng. Trên thực tế chúng được lưu trong một file xml nằm trên bộ nhớ trong, trong vùng nhớ chỉ có thể truy cập được bởi ứng dụng (/data/data/ {package-name} /shared_prefs/ gameSettings.xml), và với máy ảo Android ta có thể xem được cụ thể các giá trị này.

5.3. Lưu trữ dữ liệu trên bộ nhớ SD

Trong trường hợp cần lưu lại dữ liệu tương đối phức tạp hơn (khó có thể lưu lại dạng key-value trong shared preference), ta có thể dùng hệ thống file. Trong Android, để làm việc (nhập/xuất) với file, ta có thể sử dụng các lớp của gói java.io. Trong phần này ta sẽ xem cách làm việc với file trong bộ nhớ trong lẫn bộ nhớ ngoài.

5.3.1. Sử dụngbộ nhớ trong

Android Internal Storage là nơi lưu trữ các dữ liệu cá nhân của từng ứng dụng, mà các dữ liệu này được lưu trữ và 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. Các files của ứng dụng sẽ được lưu trong thư mục riêng tư /data/data/{package_name}.

Một đặc điểm khi bạn làm việc với các file dữ liệu ở bộ nhớ trong là bạn chỉ cần dùng tên file đơn giản mà không phải thêm đường dẫn.

- Mở file ghi dữ liệu.

String simpleFileName ="note.txt";

FileOutputStream out = openFileOutput(simpleFileName, MODE_PRIVATE);

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. - Mở file đọc dữ liệu:

ThS. Bùi Trung Úy 126

String simpleFileName = "note.txt";

FileInputStream in = this.openFileInput(simpleFileName); Ví dụ đoạn code mẫu đọc/ghi dữ liệu:

Lưu dữ liu vào b nh trong:

private void saveData() {

String data = this.editText.getText().toString(); try {

// Mở một luồng ghi file.

FileOutputStream out = this.openFileOutput(simpleFileName, MODE_PRIVATE); // Ghi dữ liệu. out.write(data.getBytes()); out.close(); Toast.makeText(this,"File saved!",Toast.LENGTH_SHORT).show(); } catch (Exception e) { Toast.makeText(this,"Error:"+ e.getMessage(),Toast.LENGTH_SHORT).show(); } } Đọc dữ liệu từ bộ nhớ trong:

private void readData() { try {

// Mở một luồng đọc file.

FileInputStream in = this.openFileInput(simpleFileName);

BufferedReader br= new BufferedReader(new InputStreamReader(in)); StringBuilder sb= new StringBuilder();

String s= null;

while((s= br.readLine())!= null) { sb.append(s).append("\n"); } this.textView.setText(sb.toString()); } catch (Exception e) { Toast.makeText(this,"Error:"+ e.getMessage(),Toast.LENGTH_SHORT).show(); } } 5.2.2. Sử dụngbộ nhớ ngoài

Android External Storage là nơi lưu trữ dữ liệu ngoài của Android, các file dữ liệu mà bạn lưu trữ tại đây có thể được truy xuất bởi ứng dụng khác.

Để đọc ghi dữ liệu trên bộ lưu trữ ngoài bạn phải khai báo quyền sử dụng trong file AndroidManifest.xml như sau:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

ThS. Bùi Trung Úy 127

Sử dụng các phương tĩnh của lớp Environment bạn có thể lấy được các thông tin

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