Chủ Nhật, 30 tháng 6, 2013

Example Hander and Thread,AsyncTask

Example 1:
<?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" >

    <ProgressBar
        android:id="@+id/progressBar1"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:indeterminate="false"
        android:max="10"
        android:padding="4dip" >
    </ProgressBar>
    
   <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" >
   </TextView>
      
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="startProgress"
        android:text="Start Progress" >
    </Button>

</LinearLayout> 

package example.storage;
import com.example.test.R;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;


public class HandlerActivity extends Activity{
private ProgressBar progress;
private TextView text;

 @Override
 public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.example_store_hander);
   progress = (ProgressBar) findViewById(R.id.progressBar1);
   text = (TextView) findViewById(R.id.textView1);
        Button button = (Button)findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
startProgress(arg0);
}
});
 }

 public void startProgress(View view) {
   // Do something long
   Runnable runnable = new Runnable() {
     @Override
     public void run() {
       for (int i = 0; i <= 10; i++) {
         final int value = i;
          doFakeWork();
         progress.post(new Runnable() {
           @Override
           public void run() {
             text.setText("Updating");
             progress.setProgress(value);
           }
         });
       }
     }
   };
   new Thread(runnable).start();
 }

 // Simulating something timeconsuming
 private void doFakeWork() {
   try {
     Thread.sleep(2000);
   } catch (InterruptedException e) {
     e.printStackTrace();
   }
 }


}

Example 2:
  <?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" >

    <ProgressBar
        android:id="@+id/progressBar1"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:indeterminate="false"
        android:max="10"
        android:padding="4dip" >
    </ProgressBar>
    
   <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" >
   </TextView>
      
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="startProgress"
        android:text="Start Progress" >
    </Button>

</LinearLayout> 


 package example.storage;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.example.test.R;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;


public class HandlerActivity extends Activity{
private ProgressBar progress;
private TextView text;

 @Override
 public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.example_store_hander);
   progress = (ProgressBar) findViewById(R.id.progressBar1);
   text = (TextView) findViewById(R.id.textView1);
        Button button = (Button)findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
startProgress(arg0);
}
});
 }
     
 private class DownloadWebpage extends AsyncTask<String, Void, String>
 {
 @Override
protected String doInBackground(String... urls) {
// TODO Auto-generated method stub
String response="";
for(String url : urls){
DefaultHttpClient client =new DefaultHttpClient();
HttpGet get = new HttpGet(url);
try{
HttpResponse respont = client.execute(get);
InputStream content = respont.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s="";
while ((s=buffer.readLine())!=null){
response +=s;
}
}catch(Exception e){ e.printStackTrace();};
}

return response;

}
 @Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
TextView text = (TextView)findViewById(R.id.textView1);
text.setText(result);
super.onPostExecute(result);
}
 }
 public void startProgress(View view) {
   DownloadWebpage web = new DownloadWebpage();
   web.execute("http://androidexample.com/");
 }

}


 



Thứ Bảy, 29 tháng 6, 2013

Lưu trữ internal sd(vùng nhớ trong) và external sd(vùng nhớ ngoài)

Hôm nay vọc về vấn đề lưu file trong bộ nhớ trong và bộ nhớ ngoài trong android ,test được ví dụ thấy hay hay : Đây là giao diện:

<?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="wrap_content"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="53dp"
        android:text="Android Storage" />

    <EditText
        android:id="@+id/inputstore"
        android:layout_width="match_parent"
        android:layout_height="86dp"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Save Internal" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Get Internal" />

    <Button
        android:id="@+id/button3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Save External" />

    <Button
        android:id="@+id/button4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Get External" />

    <TextView
        android:id="@+id/outputstore"
        android:layout_width="match_parent"
        android:layout_height="92dp"
        android:ems="10" />

</LinearLayout>

      
Sau đó mình tạo một Activity để lưu trữ và đọc file từ bộ nhớ trong và ngoài:

package example.storage;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import com.example.test.R;

import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.view.View.OnClickListener;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class AndroidStorageActivity extends Activity implements OnClickListener{
private final String filename = "bom.txt";
private final String dirname = "MyFolderBom";
File myInternal;
File myExternal;
File directory ;
  @Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.example_storage_android_storage);
ContextWrapper context = new ContextWrapper(getApplicationContext());
directory = context.getDir(dirname,Context.MODE_PRIVATE);
myInternal = new File(directory,filename);

Button saveInternal = (Button)findViewById(R.id.button1);
saveInternal.setOnClickListener(this);

Button getInternal = (Button)findViewById(R.id.button2);
getInternal.setOnClickListener((android.view.View.OnClickListener) this);

Button saveExternal = (Button)findViewById(R.id.button3);
saveExternal.setOnClickListener((android.view.View.OnClickListener) this);

Button getExternal = (Button)findViewById(R.id.button4);
getExternal.setOnClickListener((android.view.View.OnClickListener) this);

}
  

public void onClick(View v) {
// TODO Auto-generated method stub
EditText inputtext = (EditText)findViewById(R.id.inputstore);
TextView outputtext = (TextView)findViewById(R.id.outputstore);
String myData="";
myExternal = new File(getExternalFilesDir(dirname),filename);
switch(v.getId())
{
case R.id.button1:
 try {
 FileOutputStream fos = new FileOutputStream(myInternal);
 fos.write(inputtext.getText().toString().getBytes());
 fos.close();
 } catch(IOException e){
 e.printStackTrace();
 }
inputtext.setText("");
outputtext.setText("MyFolder is saved internal"+directory);break;
case R.id.button2:
try{ 
FileInputStream fis = new FileInputStream(myInternal);
DataInputStream fi = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(fi)); 
  
String strLine ; 
while((strLine = br.readLine())!=null){
myData = myData + strLine;
}
    fi.close();
}catch(IOException e){
e.printStackTrace();
}
inputtext.setText(myData);
outputtext.setText("Data duoc lay tu internal storage");break;
case R.id.button3:
 
try{
FileOutputStream fo = new FileOutputStream(myExternal);
fo.write(inputtext.getText().toString().getBytes());
}catch (IOException e)
{
e.printStackTrace();
}
    inputtext.setText("");
    outputtext.setText("bom.txt save to External "+getExternalFilesDir(dirname));
    break;
 
case R.id.button4:
 try {
   FileInputStream fis = new FileInputStream(myExternal);
   DataInputStream in = new DataInputStream(fis);
   BufferedReader br = 
    new BufferedReader(new InputStreamReader(in));
   String strLine;
   while ((strLine = br.readLine()) != null) {
    myData = myData + strLine;
   }
   in.close();
  } catch (IOException e) {
   e.printStackTrace();
  }
  inputtext.setText(myData);
  outputtext
  .setText("bom.txt data retrieved from Internal Storage...");
  break;
 
}
}


}

 Cái này thì cũng đơn giản ,quan trọng nhất là các dòng:
  * ContextWrapper context = new ContextWrapper(getApplicationContext());
directory = context.getDir(dirname,Context.MODE_PRIVATE);

ContextWrapper dùng để lấy phạm vi trong application đang chạy của bạn,từ đó mình dùng getDir() để lấy đường dẫn đến bộ nhớ trong,đồng thời tạo luôn thư mục và đường dẫn từ dirname.

  * myExternal = new File(getExternalFilesDir(dirname),filename);

    Mình dùng hàm getExternalFilesDir() để lấy đường dẫn đến bộ nhớ ngoài.

Các hàm còn lại chủ yếu là đọc ,xuất file nguồn như trong java thôi.

Thứ Sáu, 28 tháng 6, 2013

Về HashMap trong java,android

Hôm nay nhìn thấy mấy đoạn code hơi lạ,chắc do chưa học java ,mày mò thử thì thấy họ áp dụng thế này:
 Ví dụ trong file arrays.xml mình có thế này :
   <?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="countries_names">
        <item>USA</item>
        <item>Russia</item>
    </string-array>

    <integer-array name="countries_codes">
        <item>1</item>
        <item>7</item>
    </integer-array>
</resources>

Vậy để mình có thế lấy được các giá trị trong  một cách linh hoạt thì dùng thế này :


String[] countriesNames = getResources().getStringArray(R.array.countries_names);
int[] countriesCodes = getResources().getIntArray(R.array.countries_codes);

HashMap<String, Integer> myMap = new HashMap<String, Integer>();
for (int i = 0; i < countriesNames.length; i++) {
    myMap.put(countriesNames[i], countriesCodes[i]);
}
Cách này thấy hay thật trong C++ ko biết có không ,giống như mình tạo một bản đồ tùy thích để lưu giá trị.

Để lấy giá trị từ hashmap ,dùng :
 HashMap<String, String> meMap=new HashMap<String, String>();
meMap.put("Color1","Red");
meMap.put("Color2","Blue");
meMap.put("Color3","Green");
meMap.put("Color4","White");
Iterator iterator = meMap.keySet().iterator();
while( iterator. hasNext() ){
    Toast.makeText(getBaseContext(), meMap.get(iterator.next().toString()), 
    Toast.LENGTH_SHORT).show();
}


Cái này thấy bên android khác java thì phải.Hoa xem cho ý kiến thêm .@_@

Gửi tin nhắn trong android

Đây là code gửi tin nhắn đơn giản nhất,đã test thành công :
Đầu tiên là giao diện:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
     >

 <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="To"
    android:textSize="15sp"  
    android:textColor="@android:color/white"
    android:background="@android:color/black"
    />

 <EditText
     android:id="@+id/phno"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:background="@android:color/darker_gray"
     android:ems="10" >      
 </EditText>

 <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Message"
    android:textSize="15sp"  
    android:textColor="@android:color/white"
    android:background="@android:color/black"
    />
  <EditText
        android:id="@+id/smstxt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="textMultiLine"
          android:background="@android:color/darker_gray"
        android:lines="5"
        android:gravity="top" />
 <Button
        android:id="@+id/send"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Send" />

   </LinearLayout>


Sau đó là một Activity:

package com.bom.test;

import com.example.test.R;

import android.app.Activity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SendSMSActivity extends Activity {
@Override

protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.bom_send_sms);

 Button btnSend = (Button) findViewById(R.id.send);
 final EditText etPhoneNo = (EditText) findViewById(R.id.phno);
 final EditText etMsg = (EditText) findViewById(R.id.smstxt);

 btnSend.setOnClickListener(new OnClickListener() {

  @Override
  public void onClick(View v) {
    String phoneNo = etPhoneNo.getText().toString();
    String msg = etMsg.getText().toString();
    try {    
   SmsManager smsManager = SmsManager.getDefault();
   smsManager.sendTextMessage(phoneNo, null, msg, null, null);  
   Toast.makeText(getApplicationContext(), "Message Sent",
      Toast.LENGTH_LONG).show();
    } catch (Exception ex) {
   Toast.makeText(getApplicationContext(),
    ex.getMessage().toString(),
    Toast.LENGTH_LONG).show();
   ex.printStackTrace();
    }
  }
 });
}

}


Cái này dùng lớp SmsManager để gửi tin nhắn , SmsManager.getDefault() dùng để lấy instance (tức là biến this trong class của lớp SmsManager ) ,sau đó chúng ta dùng hàm sendTextMessage để gửi. phoneNo :là số điện thọai cần gửi tới. msg :là tin nhắn văn bản cần gửi. Những giá trị này mình lấy từ các ô mà ngươi dùng nhập vào.

SharedPreference android là gì

Dùng để lưu trữ data trong file xml, có thể được dùng bởi application hoặc package khác. Khởi động ta dùng cách thức getSharedPreferences() .

SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
  Để lưu trữ data mình dùng:
editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "string value"); // Storing string
editor.putInt("key_name", "int value"); // Storing integer
editor.putFloat("key_name", "float value"); // Storing float
editor.putLong("key_name", "long value"); // Storing long
 
editor.commit(); // commit changes
 Mình tạo biến editor để có thể edit giá trị trong object SharedPreferences. Lệnh commit() để lưu thay đổi.
  Để lấy lại data mình dùng 
// returns stored preference value
// If value is not present return second param value - In this case null
pref.getString("key_name", null); // getting String
pref.getInt("key_name", null); // getting Integer
pref.getFloat("key_name", null); // getting Float
pref.getLong("key_name", null); // getting Long
pref.getBoolean("key_name", null); // getting boolean
  Để clear tất cả data dùng :
editor.remove("name"); // will delete key name
editor.remove("email"); // will delete key email
 
editor.commit(); // commit changes