14 thg 3, 2012

[Networking Tut] Làm việc với networking trong Android


Bài này mình sẽ hướng dẫn các bạn thao tác với networking cơ bản nhất.
Khi làm việc với môi trường networking trên android, có 1 điều bạn luôn phải nhớ là cấp quyền truy cập Internet cho ứng dụng của bạn. bằng cách vào trong file AndroidManifest.xml. Chọn thẻ Permision -> Chọn Add -> Uses Permision -> ở ô Name chọn quyền android.permission.INTERNET.
Ý tưởng : các bạn sẽ lấy dữ liệu của 1 file xml trên môi trường mạng và hiển thị lên EditText. Và dữ liệu 1 images và hiển thị lên 1 imageView.

File main.xml trong thư mục res có dạng như sau :

<?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="wrap_content"
    android:orientation="vertical" >
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
    <LinearLayout
        android:id="@+id/ll_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >
        <Button
            android:id="@+id/button2"
            android:layout_width="115dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.29"
            android:onClick="clickMe"
            android:text="Load Image" />

        <Button
            android:id="@+id/button1"
            android:layout_width="118dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.34"
            android:onClick="clickMe"
            android:text="Connect" />
    </LinearLayout>
    <EditText
        android:id="@+id/edtExt"
        android:layout_width="match_parent"
        android:layout_height="196dp" >
       <requestFocus />
    </EditText>
    <ImageView
        android:id="@+id/imgv"
        android:layout_width="match_parent"
        android:layout_height="220dp"
        android:src="@drawable/ic_launcher" />
</LinearLayout>

Chúng ta tạo ra 1 phương thức để lấy dữ liệu theo dạng text như sau :

Với tham số truyển vào là 1 biến String chính là URL đến file xml.
Kết quả trả về cũng là 1 biến kiểu String.



public String getData(String urlStr) {
StringBuilder result = new StringBuilder();
try {
URL url = new URL(urlStr);
httpcon = (HttpURLConnection) url.openConnection();
int requestCode = httpcon.getResponseCode();
if(requestCode == HttpURLConnection.HTTP_OK){
InputStream is = httpcon.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
result.append(line).append("\n");
}
br.close();
isr.close();
is.close();

}
httpcon.disconnect();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


return result.toString();
}


Phương thức lấy dữ liệu kiểu image.
Tham số là 1 biến kiểu String
Kết quả trả ra là 1 bitmap.

public Bitmap getImageData(String urlStr) {
try {
URI uri = new URI(urlStr);
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(uri);
HttpResponse reponse = client.execute(get);
HttpEntity entity = reponse.getEntity();
InputStream is = entity.getContent();
bitmap = BitmapFactory.decodeStream(is);
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return bitmap;
}


Hoàn thành project này các bạn lấy được thông tin như hình sau :
Chúc vui. thân mến. 

Vậy khuyết điểm của phương pháp này là gì ? Đó là khi đang trong quá trình load dữ liệu về. các control của giao diện màn hình sẽ bị đứng, ko xử lý nhạy được.Chính vì vậy thông thường người ta sẽ dùng Thread để truy xuất. Bài sau mình sẽ làm demo về Thread làm việc trên môi trường networking.

Download Project này tại đây . 


Không có nhận xét nào:

Đăng nhận xét

Bản beta đầu tiên

Sau 6 tháng cả team cặm cụi làm việc điên cuồng, bản alpha cũng được giới thiệu ra toàn bộ công ty và được testing nội bộ công ty mà thôi. ...