Showing posts with label Code Snippets android. Show all posts
Showing posts with label Code Snippets android. Show all posts

Thursday, May 16, 2013

[Android Nâng Cao] Sử Dụng ViewPager Cho Chuyển Đổi View

Xin chào các bạn, hôm nay mình sẽ hướng dẫn các bạn cách sử dụng ViewPager cho việc chuyển Activity đồng thời khi vuốt tay ( giống như khi vào Play Store các bạn vuốt tay qua trái phải để xem Top Paid apps > Top Free apps....).

I. Giới Thiệu ViewPager

Theo android.com, thì ViewPager là một trình quản lý Layout cho phép người dùng vuốt tay qua trái hay qua bên phải để chuyển sang nội dung của trang khác một cách đồng thời. Điểm khác nhau của ViewPager và cách sử dụng Gesture đó là, gesture sẽ chỉ thực hiện khi người dùng thực hiện xong thao tác vuốt tay, trong khi ViewPager thực hiện chuyển màn hình đồng thời với cử chỉ tay người dùng.

II. Code Now


1. Chuẩn bị

ViewPager không phải là một View chuẩn của Android, mà là một thành phần nằm trong gói android.support.v4.View
Nếu bạn chưa có gói này, có thể cài đặt bằng cách, mở Android SDK Manager->Extra-> tick chọn Android Support package->OK

Sau khi cài đặt, các bạn sẽ thấy có thêm một gói android-support-v4.jar nằm trong project của mình.

2. Code Now

a. Tạo mới một project mới, ví dụ đặt tên là MyApps

b. Thay đổi nội dung file main.xml như bên dưới


Mã:
<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"
tools:context=".MainActivity" >

<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
></android.support.v4.view.ViewPager>

</RelativeLayout>

c. Tạo các layout cho các màn hình khác nhau khi vuốt qua trái, qua phải. Ở đây mình tạo 5 file xml cho 5 màn hình.

- layout_1.xml

Mã:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Nhip"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>

- layout_2.xml

Mã:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Song"
android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

- layout_3.xml

Mã:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Di"
android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

- layout_4.xml

Mã:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dong"
android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

- layout_5.xml

Mã:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Nhipsongdidong.vn"
android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

Phần thiết kế màn hình coi như xong.

d. Code

Cũng giống như ListView hay các các thành phần khác, ViewPager bắt buộc phải cần một Adapter để có thể xác định nội dung cần hiển thị lên View.

- Tạo một class mới kế thừa từ PagerAdapter , đặt tên là MyPagerAdapter ( chẳng hạn)

Mã:
public class PagerAdapter extends android.support.v4.view.PagerAdapter{


@Override
public int getCount() {
//Do ở đây mình có 5 Activity nên count trả về là 5
return 5;
}

//Hàm khởi tạo View dùng cho việc hiển thị Activity chính xác
//Hàm có chức năng nôm na như hàm getView thường thấy trong Adapter của ListView, hay chính xác hơn là
//makeView trong ImageSwitcher vậy
@Override
public Object instantiateItem(ViewGroup container, int position) {

LayoutInflater li = (LayoutInflater) container.getContext().
getSystemService(Context.LAYOUT_INFLATER_SERVICE);

int resId=0;
switch(position)
{
case 0:
resId = R.layout.layout_1;
break;
case 1:
resId = R.layout.layout_2;
break;
case 2:
resId = R.layout.layout_3;
break;
case 3:
resId = R.layout.layout_4;
break;
case 4:
resId = R.layout.layout_5;
break;
}

View view = li.inflate(resId, null);
container.addView(view, 0);
return view;
}
//View nào ko còn hiển thị nữa thì xóa đi
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);

}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == (View)arg1;
}
}

- Activity chính của chương trình.

Mã:
public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PagerAdapter a = new PagerAdapter();
ViewPager p = (ViewPager) findViewById(R.id.pager);
p.setAdapter(a);
p.setCurrentItem(2);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

}

3. Chạy chương trình và trải nghiệm


Các bạn có thắc mắc có thể góp ý tại đây luôn nhé.
Chúc vui.

Monday, April 15, 2013

Đọc nội dung file .txt trong sdcard [ For Newbie ]

try{ 
File f = new File(Environment.getExternalStorageDirectory()+"/test.txt");
fileIS = new FileInputStream(f);
BufferedReader buf = new BufferedReader(new InputStreamReader(fileIS));
String readString = new String();
//đọc theo từng dòng
while((readString = buf.readLine())!= null){
// hiển thị ra LOGCAT
Log.d("line: ", readString);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
Khi chạy bạn nhớ bật Logcat để xem kết quả. Đoạn code đặt ngay trong hàm onCreate() nhé.

[Code snippets] Download 1 HTTP file với progess notification

try {
// Khai báo url
URL url = new URL("http://somewhere.com/some/webhosted/file");

//tạo HTTP connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

//setup phương thức cho HTTP connecton
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);

// kết nối
urlConnection.connect();


// khởi tạo sdcard . Lưu ý phương thức Environment.getExternalStorageDirectory(); trả lại đường dẫn đến sdcard
File SDCardRoot = Environment.getExternalStorageDirectory();
// Tạo 1 file để lưu nội dung trang web
File file = new File(SDCardRoot,"somefile.ext");

//Khai báo FileInputStream để tương tác với InputStream
FileOutputStream fileOutput = new FileOutputStream(file);

//InputStream để đọc dẽ liệu từ url
InputStream inputStream = urlConnection.getInputStream();

//lấy size của dữ liệu tải về
int totalSize = urlConnection.getContentLength();
// khai báo 1 biến để biết dữ liệu tải về ( realtime)
int downloadedSize = 0;

//tạo buffer
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer

//đọc dữ liệu từ buffer
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
//ghi từ buffer vào textfile ở sdcard
fileOutput.write(buffer, 0, bufferLength);
//update downloadSize
downloadedSize += bufferLength;
//dựa vào biến downloadSize để update progess
updateProgress(downloadedSize, totalSize);

}
//đóng outputstream khi hoàn thành
fileOutput.close();

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

[Code Snippets] Lấy thông tin về Battery

main.xml
[JAVA]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:eek:rientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Battery Info."
/>
<TextView
android:id="@+id/batterylevel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Battery Level:"
/>
<TextView
android:id="@+id/batteryvoltage"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Battery Voltage:"
/>
<TextView
android:id="@+id/batterytemperature"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Battery Temperature:"
/>
<TextView
android:id="@+id/batterytechology"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Technology:"
/>
<TextView
android:id="@+id/batterystatus"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Status:"
/>
<TextView
android:id="@+id/batteryhealth"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Health:"
/>
</LinearLayout>

[/JAVA]

Main Activity

[JAVA]
package com.exercise.AndroidBattery;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.widget.TextView;

public class AndroidBattery extends Activity {

private TextView batteryLevel, batteryVoltage, batteryTemperature,
batteryTechnology, batteryStatus, batteryHealth;


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

batteryLevel = (TextView)findViewById(R.id.batterylevel);
batteryVoltage = (TextView)findViewById(R.id.batteryvoltage);
batteryTemperature = (TextView)findViewById(R.id.batterytemperature);
batteryTechnology = (TextView)findViewById(R.id.batterytechology);
batteryStatus = (TextView)findViewById(R.id.batterystatus);
batteryHealth = (TextView)findViewById(R.id.batteryhealth);

this.registerReceiver(this.myBatteryReceiver,
new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}

private BroadcastReceiver myBatteryReceiver
= new BroadcastReceiver(){

@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub

if (arg1.getAction().equals(Intent.ACTION_BATTERY_CHANGED)){
batteryLevel.setText("Level: "
+ String.valueOf(arg1.getIntExtra("level", 0)) + "%");
batteryVoltage.setText("Voltage: "
+ String.valueOf((float)arg1.getIntExtra("voltage", 0)/1000) + "V");
batteryTemperature.setText("Temperature: "
+ String.valueOf((float)arg1.getIntExtra("temperature", 0)/10) + "c");
batteryTechnology.setText("Technology: " + arg1.getStringExtra("technology"));

int status = arg1.getIntExtra("status", BatteryManager.BATTERY_STATUS_UNKNOWN);
String strStatus;
if (status == BatteryManager.BATTERY_STATUS_CHARGING){
strStatus = "Charging";
} else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING){
strStatus = "Dis-charging";
} else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING){
strStatus = "Not charging";
} else if (status == BatteryManager.BATTERY_STATUS_FULL){
strStatus = "Full";
} else {
strStatus = "Unknown";
}
batteryStatus.setText("Status: " + strStatus);

int health = arg1.getIntExtra("health", BatteryManager.BATTERY_HEALTH_UNKNOWN);
String strHealth;
if (health == BatteryManager.BATTERY_HEALTH_GOOD){
strHealth = "Good";
} else if (health == BatteryManager.BATTERY_HEALTH_OVERHEAT){
strHealth = "Over Heat";
} else if (health == BatteryManager.BATTERY_HEALTH_DEAD){
strHealth = "Dead";
} else if (health == BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE){
strHealth = "Over Voltage";
} else if (health == BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE){
strHealth = "Unspecified Failure";
} else{
strHealth = "Unknown";
}
batteryHealth.setText("Health: " + strHealth);

}
}

};
}

[Code Snippets] Một cách kiểm tra phiên bản mới của ứng dụng

Có nhiều cách để cho người dùng kiểm tra phiên bản mới ứng dụng. Phương pháp sau đây không cần phải có server riêng để kiểm tra phiên bản mà dùng chính Android Market server (đòi hỏi ứng dụng phải có trên Market). Nguyên lý là bạn truy cập trang thông tin ứng dụng của mình để trích xuất thông tin phiên bản, sau đó so sánh với phiên bản hiện tại trong PackageInfo của ứng dụng.

Đoạn code sau đây mình lấy từ chương trình OptiNews (định danh là vn.zerox.optinews, các bạn sẽ thay bằng cái khác):


Tạo thread để check phiên bản:

Mã:
Thread thr = new LoadVersion();
thr.start();
Thread check phiên bản:
Mã:
private class LoadVersion extends Thread {
@Override
public void run() {
handler.sendEmptyMessage(0);

try {
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 10000);
HttpConnectionParams.setSoTimeout(params, 10000);
HttpClient client = new DefaultHttpClient(params);
HttpGet get = new HttpGet("http://market.android.com/details?id=vn.zerox.optinews");
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
html = EntityUtils.toString(entity, "utf-8");
} catch (Exception e) {
html = null;
}

handler.sendEmptyMessage(1);
}
}
Handler để hiển thị thông tin kiểm tra phiên bản:
Mã:
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
if (oncreate) break;
pd = new ProgressDialog(MainCategory.this);
pd.setMessage("Kiểm tra cập nhật...");
pd.setCancelable(false);
Window window = pd.getWindow();
//window.setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
window.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
pd.show();
break;
case 1:
if (!oncreate) pd.dismiss();
if (html == null) {
if (!oncreate) Toast.makeText(MainCategory.this, "Lỗi truy cập thông tin !", Toast.LENGTH_SHORT).show();
} else {
int i = html.indexOf("<dt>Current Version:</dt><dd>");
int j = html.indexOf("</dd>",i+29);
if (i == -1 || j == -1) {
Toast.makeText(MainCategory.this, "Lỗi truy cập thông tin phiên bản !", Toast.LENGTH_SHORT).show();
break;
}
String ver = html.substring(i+29, j);
float nver = Float.parseFloat(ver);
String cur = "1.0";
try {
cur = getPackageManager().getPackageInfo(getPackageName(),0).versionName;
} catch (NameNotFoundException e) {}
float ncur = Float.parseFloat(cur);
String text;
if (ncur >= nver) {
if (oncreate) break;
text = "Bạn đang dùng phiên bản mới nhất !";
}
else text = "Hiện đã có phiên bản mới là " + ver + " !";
AlertDialog.Builder dialog = new AlertDialog.Builder(MainCategory.this);
dialog.setTitle("Kiểm tra cập nhật");
dialog.setMessage(text);
dialog.setNeutralButton("Đóng", null);
dialog.create().show();
}
break;
default:
super.handleMessage(msg);
}
}
};
Chú ý ở đây mình đặt tên phiên bản có dạng n.m (n,m gồm 1 chữ số). Các bạn có thể sửa code để tương thích dạng phiên bản khác như n.mm-beta ...
(Vì trên Market không hiển thị VersionCode nên mình phải dùng VersionName)