You are on page 1of 25

MỘT SỐ HÀM THƯ VIỆN THÔNG DỤNG

1. Validation
package chaudh.android.Libraries; 

import java.util.regex.Matcher; 
import java.util.regex.Pattern; 

public class Validation { 
    // Check Email Address 
    public static boolean valid_Email(String _Email) { 
        Pattern pattern = Pattern.compile("^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]
+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*((\\.[A-Za-z]{2,}){1}$)"); 
        Matcher matcher = pattern.matcher(_Email); 
        if (matcher.matches()) { 
            return true; 
        } else { 
            return false; 
        } 
    } 

    // Check Phone Number 
    public static boolean valid_Phone(String str) { 
        String pat = "^\\d{3}[-]\\d{3}[-]\\d{4}$"; 
        Pattern p = Pattern.compile(pat); 
        // Match the given string with the pattern 
        Matcher m = p.matcher(str); 
        boolean matchFound = m.matches(); 
        return matchFound; 
    } 

2. MD5 Encoding
package chaudh.android.Libraries; 

import java.security.MessageDigest; 
import java.security.NoSuchAlgorithmException; 

public class MD5 { 
    public static String md5(String s) { 
        try { 
            // Create MD5 Hash 
            MessageDigest digest = java.security.MessageDigest 
                    .getInstance("MD5"); 
            digest.update(s.getBytes()); 
            byte messageDigest[] = digest.digest(); 

            // Create Hex String 
            StringBuffer hexString = new StringBuffer(); 
            for (int i = 0; i < messageDigest.length; i++) { 
                String hex=Integer.toHexString(0xFF & messageDigest[i]); 
                if(hex.length()==1) hexString.append('0'); 
                hexString.append(hex); 
            } 
            return hexString.toString(); 

        } catch (NoSuchAlgorithmException e) { 
            e.printStackTrace(); 
        } 
        return ""; 
    } 
}
3. Bitmap Image Processing
package chaudh.android.Libraries; 

import java.io.ByteArrayOutputStream; 
import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.net.HttpURLConnection; 
import java.net.URL; 

import org.kobjects.base64.Base64; 
import org.ksoap2.SoapEnvelope; 
import org.ksoap2.serialization.SoapObject; 
import org.ksoap2.serialization.SoapPrimitive; 
import org.ksoap2.serialization.SoapSerializationEnvelope; 
import org.ksoap2.transport.HttpTransportSE; 
import thelinh.android.Config.Config; 

import android.content.Context; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.graphics.Matrix; 
import android.graphics.drawable.BitmapDrawable; 

public class ImageProcess { 
    public static byte[] BitmaptoByte(Bitmap bitmap) { 
        ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
        bitmap.compress(Bitmap.CompressFormat.PNG, 90, baos); 
        byte[] data = baos.toByteArray(); 
        return data; 
    } 

    public static String BytetoString(byte[] bytes) { 
        String strbytes = Base64.encode(bytes); 
        SoapPrimitive oPrimitive = new SoapPrimitive(SoapEnvelope.ENC, 
                "base64", strbytes); 
        return oPrimitive.toString(); 
    } 

    public static String BitmaptoString(Bitmap bitmap) { 
        byte[] bytes = BitmaptoByte(bitmap); 
        return BytetoString(bytes); 
    } 

    public static Bitmap StringtoBitmap(String strBitmap) { 
        byte[] bytes = Base64.decode(strBitmap); 
        Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); 
        return bitmap; 
    } 

    public static Bitmap BytetoBitmap(byte[] bytes) { 
        Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); 
        return bitmap; 
    } 

    public static Bitmap getBitmapfromURL(String url) { 
        try { 
            HttpURLConnection conn = (HttpURLConnection) (new URL(url)) 
                    .openConnection(); 
            conn.connect(); 
            return BitmapFactory.decodeStream(conn.getInputStream()); 
        } catch (Exception ex) { 
            return null; 
        } 
    } 

    public static byte[] fileToBytes(String path) throws IOException { 

        File file = new File(path); 
        java.io.FileInputStream fis = new java.io.FileInputStream(file); 
        byte[] b = new byte[(int) file.length()]; 
        fis.read(b); 
        fis.close(); 
        return b; 
    } 

    public static Bitmap BitmapResize(Bitmap bitmap, int newWidth, int newHeight) { 

        int width = bitmap.getWidth(); 
        int height = bitmap.getHeight(); 
        // calculate the scale - in this case = 0.4f 
        float scaleWidth = ((float) newWidth) / width; 
        float scaleHeight = ((float) newHeight) / height; 

        // createa matrix for the manipulation 
        Matrix matrix = new Matrix(); 
        // resize the bit map 
        matrix.postScale(scaleWidth, scaleHeight); 

        // recreate the new Bitmap 
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, 
                matrix, true); 
        return resizedBitmap; 
    } 

    public static Bitmap WidthBitmapResize(Bitmap bitmap, int newWidth) { 

        int width = bitmap.getWidth(); 
        int height = bitmap.getHeight(); 
        // calculate the scale - in this case = 0.4f 
        float scaleWidth = ((float) newWidth) / width; 

        // createa matrix for the manipulation 
        Matrix matrix = new Matrix(); 
        // resize the bit map 
        matrix.postScale(scaleWidth, scaleWidth); 
        // recreate the new Bitmap 
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, 
                matrix, true); 
        return resizedBitmap; 
    } 

    public static BitmapDrawable BitmaptoDrawable(Bitmap bitmap) { 
        BitmapDrawable bmd = new BitmapDrawable(bitmap); 
        return bmd; 
    } 
    public static boolean SaveBitmap(Context context, Bitmap bitmap, 
            String filename)  
    { 
        FileOutputStream fos = null; 
        try { 
            fos = context.openFileOutput(filename, Context.MODE_PRIVATE); 
            bitmap.compress(Bitmap.CompressFormat.PNG,100, fos); 
            return true; 
        } catch (FileNotFoundException e) { 
            return false; 
        } finally { 
            if (fos != null) { 
                try { 
                    fos.flush(); 
                    fos.close(); 
                } catch (IOException e) { 
                    return false; 
                } 
            } 
        } 

    } 

}  

***************************************
ĐỌC GHI CONTACT/SMS TRONG ANDROID
1. Contact API
package chaudh.android.DAL; 
import java.util.ArrayList; 
import thelinh.android.Entities.Address; 
import thelinh.android.Entities.Contact; 
import thelinh.android.Entities.ContactList; 
import thelinh.android.Entities.Email; 
import thelinh.android.Entities.IM; 
import thelinh.android.Entities.Organization; 
import thelinh.android.Entities.Phone; 
import android.content.ContentResolver; 
import android.content.ContentUris; 
import android.content.ContentValues; 
import android.database.Cursor; 
import android.net.Uri; 
import android.provider.ContactsContract; 
import android.provider.ContactsContract.RawContacts; 
import android.provider.ContactsContract.CommonDataKinds.StructuredName; 
import android.util.Log; 

public class ContactAPI { 

    private Cursor cur; 
    private ContentResolver cr; 

    public Cursor getCur() { 
        return cur; 
    } 

    public void setCur(Cursor cur) { 
        this.cur = cur; 
    } 

    public ContentResolver getCr() { 
        return cr; 
    } 

    public void setCr(ContentResolver cr) { 
        this.cr = cr; 
    } 

    // Get Contact List 
    public ContactList getContactList() { 
        ContactList contacts = new ContactList(); 
        String id; 
        this.cur = this.cr.query(ContactsContract.Contacts.CONTENT_URI, null, 
                null, null, null); 
        if (this.cur.getCount() > 0) { 
            while (cur.moveToNext()) { 
                Contact c = new Contact(); 
                id = cur.getString(cur 
                        .getColumnIndex(ContactsContract.Contacts._ID)); 
                c.setId(id); 
                c.setDisplayName(cur.getString(cur.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME))); 
                if (Integer.parseInt(cur.getString(cur.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) { 
                    c.setPhone(this.getPhoneNumbers(id)); 
                } 
                c.setEmail(this.getEmailAddresses(id)); 
                c.setNotes(this.getContactNotes(id)); 
                c.setAddresses(this.getContactAddresses(id)); 
                c.setImAddresses(this.getIM(id)); 
                c.setOrganization(this.getContactOrg(id)); 
                contacts.addContact(c); 
            } 
        } 
        return (contacts); 
    } 

    public ArrayList<Phone> getPhoneNumbers(String id) { 
        ArrayList<Phone> phones = new ArrayList<Phone>(); 

        Cursor pCur = this.cr.query( 
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, 
                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", 
                new String[] { id }, null); 
        while (pCur.moveToNext()) { 
            phones 
                    .add(new Phone( 
                            pCur 
                                    .getString(pCur 
                                            .getColumnIndex(ContactsContract.CommonDataKin
ds.Phone.NUMBER)), 
                            pCur 
                                    .getString(pCur 
                                            .getColumnIndex(ContactsContract.CommonDataKin
ds.Phone.TYPE)))); 

        } 
        pCur.close(); 
        return (phones); 
    } 

    public ArrayList<Email> getEmailAddresses(String id) { 
        ArrayList<Email> emails = new ArrayList<Email>(); 

        Cursor emailCur = this.cr.query( 
                ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, 
                ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", 
                new String[] { id }, null); 
        while (emailCur.moveToNext()) { 
            // This would allow you get several email addresses 
            Email e = new Email( 
                    emailCur 
                            .getString(emailCur 
                                    .getColumnIndex(ContactsContract.CommonDataKinds.Email
.DATA)), 
                    emailCur 
                            .getString(emailCur 
                                    .getColumnIndex(ContactsContract.CommonDataKinds.Email
.TYPE))); 
            emails.add(e); 
        } 
        emailCur.close(); 
        return (emails); 
    } 

    public ArrayList<String> getContactNotes(String id) { 
        ArrayList<String> notes = new ArrayList<String>(); 
        String where = ContactsContract.Data.CONTACT_ID + " = ? AND " 
                + ContactsContract.Data.MIMETYPE + " = ?"; 
        String[] whereParameters = new String[] { id, 
                ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE }; 
        Cursor noteCur = this.cr.query(ContactsContract.Data.CONTENT_URI, null, 
                where, whereParameters, null); 
        while (noteCur.moveToNext()) { 
            String note = noteCur 
                    .getString(noteCur 
                            .getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE)); 
            if (note.length() > 0) { 
                notes.add(note); 
            } 
        } 
        noteCur.close(); 
        return (notes); 
    } 

    public ArrayList<Address> getContactAddresses(String id) { 
        ArrayList<Address> addrList = new ArrayList<Address>(); 

        String where = ContactsContract.Data.CONTACT_ID + " = ? AND " 
                + ContactsContract.Data.MIMETYPE + " = ?"; 
        String[] whereParameters = new String[] { 
                id, 
                ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE }; 

        Cursor addrCur = this.cr.query(ContactsContract.Data.CONTENT_URI, null, 
                where, whereParameters, null); 
        while (addrCur.moveToNext()) { 
            String poBox = addrCur 
                    .getString(addrCur 
                            .getColumnIndex(ContactsContract.CommonDataKinds.StructuredPos
tal.POBOX)); 
            String street = addrCur 
                    .getString(addrCur 
                            .getColumnIndex(ContactsContract.CommonDataKinds.StructuredPos
tal.STREET)); 
            String city = addrCur 
                    .getString(addrCur 
                            .getColumnIndex(ContactsContract.CommonDataKinds.StructuredPos
tal.CITY)); 
            String state = addrCur 
                    .getString(addrCur 
                            .getColumnIndex(ContactsContract.CommonDataKinds.StructuredPos
tal.REGION)); 
            String postalCode = addrCur 
                    .getString(addrCur 
                            .getColumnIndex(ContactsContract.CommonDataKinds.StructuredPos
tal.POSTCODE)); 
            String country = addrCur 
                    .getString(addrCur 
                            .getColumnIndex(ContactsContract.CommonDataKinds.StructuredPos
tal.COUNTRY)); 
            String type = addrCur 
                    .getString(addrCur 
                            .getColumnIndex(ContactsContract.CommonDataKinds.StructuredPos
tal.TYPE)); 
            Address a = new Address(poBox, street, city, state, postalCode, 
                    country, type); 
            addrList.add(a); 
        } 
        addrCur.close(); 
        return (addrList); 
    } 

    public ArrayList<IM> getIM(String id) { 
        ArrayList<IM> imList = new ArrayList<IM>(); 
        String where = ContactsContract.Data.CONTACT_ID + " = ? AND " 
                + ContactsContract.Data.MIMETYPE + " = ?"; 
        String[] whereParameters = new String[] { id, 
                ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE }; 

        Cursor imCur = this.cr.query(ContactsContract.Data.CONTENT_URI, null, 
                where, whereParameters, null); 
        while (imCur.moveToNext()) { 
            String imName = imCur.getString(imCur 
                    .getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA)); 
            String imType; 
            imType = imCur 
                    .getString(imCur 
                            .getColumnIndex(ContactsContract.CommonDataKinds.Im.PROTOCOL))

            if (imName.length() > 0) { 
                IM im = new IM(imName, imType); 
                imList.add(im); 
            } 
        } 
        imCur.close(); 
        return (imList); 
    } 

    public ArrayList<Organization> getContactOrg(String id) { 
        ArrayList<Organization> orgs = new ArrayList<Organization>(); 
        String where = ContactsContract.Data.CONTACT_ID + " = ? AND " 
                + ContactsContract.Data.MIMETYPE + " = ?"; 
        String[] whereParameters = new String[] { id, 
                ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE }; 

        Cursor orgCur = this.cr.query(ContactsContract.Data.CONTENT_URI, null, 
                where, whereParameters, null); 

        while (orgCur.moveToNext()) { 
            String orgName = orgCur 
                    .getString(orgCur 
                            .getColumnIndex(ContactsContract.CommonDataKinds.Organization.
DATA)); 
            String title = orgCur 
                    .getString(orgCur 
                            .getColumnIndex(ContactsContract.CommonDataKinds.Organization.
TITLE)); 
            String type = orgCur 
                    .getString(orgCur 
                            .getColumnIndex(ContactsContract.CommonDataKinds.Organization.
TYPE)); 
            if (orgName.length() > 0) { 
                Organization org = new Organization(orgName, title, type); 
                orgs.add(org); 
            } 
        } 
        orgCur.close(); 
        return (orgs); 
    } 

    private void WriteSingleContact(Contact contact) 
    { 
        // DELETE CONTACT 
        Uri personUri = ContactsContract.RawContacts.CONTENT_URI; 
        String where =ContactsContract.Contacts.DISPLAY_NAME+"=?"; 
        cr.delete(personUri,where,new String[] {contact.getDisplayName()}); 
        ContentValues values = new ContentValues(); 
        values.put(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, contact 
                .getDisplayName()); 
        Uri rawContactUri = cr.insert(RawContacts.CONTENT_URI, values); 
        long rawContactId = ContentUris.parseId(rawContactUri); 

        values.clear(); 
        values.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId); 
        values.put(ContactsContract.Data.MIMETYPE, 
                StructuredName.CONTENT_ITEM_TYPE); 
        values.put(StructuredName.DISPLAY_NAME, contact.getDisplayName()); 
        cr.insert(ContactsContract.Data.CONTENT_URI, values); 
        Uri phoneUri = null; 
        Uri emailUri = null; 
        Uri addressUri = null; 
        Uri imUri = null; 
        Uri orgUri = null; 
        Uri noteUri = null; 
        for (Phone aPhone : contact.getPhone()) { 

            phoneUri = Uri.withAppendedPath(rawContactUri, 
                    ContactsContract.Contacts.Data.CONTENT_DIRECTORY); 
            values.clear(); 
            values.put(ContactsContract.CommonDataKinds.Phone.TYPE, aPhone 
                    .getType()); 
            values.put(ContactsContract.CommonDataKinds.Phone.IS_SUPER_PRIMARY, 
                    1); 
            values.put(ContactsContract.Data.MIMETYPE, 
                    ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE); 
            values.put(ContactsContract.CommonDataKinds.Phone.NUMBER, aPhone 
                    .getNumber()); 
            cr.insert(phoneUri, values); 
        } 
        for (Email aEmail : contact.getEmail()) { 
            emailUri = Uri.withAppendedPath(rawContactUri, 
                    ContactsContract.Contacts.Data.CONTENT_DIRECTORY); 

            values.clear(); 
            values.put(ContactsContract.CommonDataKinds.Email.TYPE, aEmail 
                    .getType()); 
            values.put(ContactsContract.Data.MIMETYPE, 
                    ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE); 
            values.put(ContactsContract.CommonDataKinds.Email.DATA, aEmail 
                    .getAddress()); 
            cr.insert(emailUri, values); 
        } 
        for (String aNote : contact.getNotes()) { 
            noteUri = Uri.withAppendedPath(rawContactUri, 
                    ContactsContract.Contacts.Data.CONTENT_DIRECTORY); 
            values.clear(); 
            values.put(ContactsContract.Data.MIMETYPE, 
                    ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE); 
            values.put(ContactsContract.CommonDataKinds.Note.NOTE, aNote); 
            cr.insert(noteUri, values); 
        } 
        for (IM aIM : contact.getImAddresses()) { 
            imUri = Uri.withAppendedPath(rawContactUri, 
                    ContactsContract.Contacts.Data.CONTENT_DIRECTORY); 
            values.clear(); 
            values.put(ContactsContract.CommonDataKinds.Im.PROTOCOL, aIM 
                    .getType()); 
            values.put(ContactsContract.Data.MIMETYPE, 
                    ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE); 
            values.put(ContactsContract.CommonDataKinds.Im.DATA, aIM.getName()); 
            cr.insert(imUri, values); 
        } 
        for (Organization aORG : contact.getOrganization()) { 
            orgUri = Uri.withAppendedPath(rawContactUri, 
                    ContactsContract.Contacts.Data.CONTENT_DIRECTORY); 
            values.clear(); 
            values.put(ContactsContract.CommonDataKinds.Organization.TYPE, aORG 
                    .getType()); 
            values.put(ContactsContract.CommonDataKinds.Organization.TITLE, 
                    aORG.getTitle()); 
            values 
                    .put( 
                            ContactsContract.Data.MIMETYPE, 
                            ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYP
E); 
            values.put(ContactsContract.CommonDataKinds.Organization.DATA, aORG 
                    .getOrganization()); 
            cr.insert(orgUri, values); 
        } 
        for (Address aAdd : contact.getAddresses()) { 
            addressUri = Uri.withAppendedPath(rawContactUri, 
                    ContactsContract.Contacts.Data.CONTENT_DIRECTORY); 
            values.clear(); 
            values 
                    .put( 
                            ContactsContract.Data.MIMETYPE, 
                            ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM
_TYPE); 
            if (aAdd.getCity() != null) 
                values.put( 
                        ContactsContract.CommonDataKinds.StructuredPostal.CITY, 
                        aAdd.getCity()); 
            if (aAdd.getCountry() != null) 
                values 
                        .put( 
                                ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY, 

                                aAdd.getCountry()); 
            if (aAdd.getPoBox() != null) 
                values 
                        .put( 
                                ContactsContract.CommonDataKinds.StructuredPostal.POBOX, 
                                aAdd.getPoBox()); 
            if (aAdd.getPostalCode() != null) 
                values 
                        .put( 
                                ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE

                                aAdd.getPostalCode()); 
            if (aAdd.getStreet() != null) 
                values 
                        .put( 
                                ContactsContract.CommonDataKinds.StructuredPostal.STREET, 
                                aAdd.getStreet()); 
            if (aAdd.getState() != null) 
                values 
                        .put( 
                                ContactsContract.CommonDataKinds.StructuredPostal.REGION, 
                                aAdd.getState()); 
            values.put(ContactsContract.CommonDataKinds.StructuredPostal.TYPE, 
                    aAdd.getType()); 
            cr.insert(addressUri, values); 
        } 

    } 
    public boolean WriteContact(ArrayList<Contact> LstContact) { 
        try { 
            for (Contact contact : LstContact) { 
                WriteSingleContact(contact); 
            } 
            return true; 
        } catch (Exception ex) { 
            Log.d("ERROR", ex.toString()); 
            return false; 
        } 
    } 

2. SMS API
package chaudh.android.DAL; 

import java.text.SimpleDateFormat; 
import java.util.ArrayList; 
import java.util.Date; 

import thelinh.android.Entities.SMS; 
import android.content.ContentResolver; 
import android.database.Cursor; 
import android.net.Uri; 

public class SMSAPI { 

    private ContentResolver cr; 

    public ContentResolver getCr() { 
        return cr; 
    } 

    public void setCr(ContentResolver cr) { 
        this.cr = cr; 
    } 

    public ArrayList<SMS> getSMSList() { 
        ArrayList<SMS> LstSMS = new ArrayList<SMS>(); 
        Uri mInboxURI = Uri.parse("content://sms/inbox"); 
        Cursor c = this.cr.query(mInboxURI, null, null, null, "date DESC"); 
        while (c.moveToNext()) { 
            SMS aSMS = new SMS(); 
            String id = c.getString(c.getColumnIndex("_id")); 
            String thread_id = c.getString(c.getColumnIndex("thread_id")); 
            String address = c.getString(c.getColumnIndex("address")); 
            String person = c.getString(c.getColumnIndex("person")); 
            long ldate = c.getLong(c.getColumnIndex("date")); 
            Date aDate = new Date(ldate); 
            SimpleDateFormat formatter = new SimpleDateFormat( 
                    "dd-MM-yyyy 'at' h:mm a"); 
            String date = formatter.format(aDate).toString(); 
            String body = c.getString(c.getColumnIndex("body")); 
            aSMS.setid(id); 
            aSMS.setthread_id(thread_id); 
            aSMS.setaddress(address); 
            aSMS.setperson(person); 
            aSMS.setdate(date); 
            aSMS.setbody(body); 
            LstSMS.add(aSMS); 
        } 
        c.close(); 
        return LstSMS; 
    } 
}

***************************************
XML PARSER
Đầu tiền là phân tích XML và load lên ListView.

Ví dụ bạn có file XML thế này.


<?xml version="1.0" encoding="UTF-8"?> 
<topics> 
    <topic id="1"> 
        <title>Title 1</title> 
        <url>http://goole.com</url> 
    </topic> 
    <topic id="2"> 
        <title>Title 2</title> 
        <url>http://www.voanews.com/specialenglish/customCF/RecentStoriesRSS.cfm?
keyword=American%20History</url> 
    </topic> 
</topics>

Các bạn tạo một class là TopicHandler để phân tích XML và trả về ArrayList
import java.util.ArrayList; 

import org.xml.sax.Attributes; 
import org.xml.sax.SAXException; 
import org.xml.sax.helpers.DefaultHandler; 

import developer.android.aVOA.Entities.Topic; 

public class TopicHandler extends DefaultHandler { 
    private boolean in_topic=false; 
    private boolean in_title=false; 
    private boolean in_url=false; 
    private ArrayList<Topic> LstTopic=new ArrayList<Topic>(); 
    private Topic aTopic; 
    public ArrayList<Topic> getTopics() 
    { 
        return this.LstTopic; 
    } 
    @Override  
    public void startDocument() throws SAXException {  
           
    }  

    @Override  
    public void endDocument() throws SAXException {  
         // Nothing to do  
    }  
    @Override  
    public void startElement(String n, String l,String q, Attributes a) throws SAXExceptio
n  
    { 
        if(l.equals("topic")) 
        { 
            this.in_topic=true; 
            this.aTopic=new Topic(); 
        } 
        else if(l.equals("title")) 
            this.in_title=true; 
        else if(l.equals("url")) 
            this.in_url=true; 
    } 
    @Override  
    public void endElement(String n, String l,String q) throws SAXException  
    {         
        if(l.equals("topic")) 
        { 
            this.LstTopic.add(aTopic); 
            this.in_topic=false; 
        } 
        else if(l.equals("title")) 
            this.in_title=false; 
        else if(l.equals("url")) 
            this.in_url=false; 
    } 
    @Override  
    public void characters(char ch[], int start, int length)  
    { 
        if(this.in_title==true && this.in_topic==true) 
        { 
            this.aTopic.settitle(new String(ch,start,length)); 
        } 
        else if(this.in_url==true && this.in_topic==true) 
        { 
            this.aTopic.seturl(new String(ch,start,length)); 
        } 
    } 

}  

File Topic.java
public class Topic { 
    private String title; 
    private String url; 
    public void settitle(String _title) 
    { 
        this.title=_title; 
    } 
    public String gettitle(){ 
        return this.title; 
    } 
    public void seturl(String _url) 
    { 
        this.url=_url; 
    } 
    public String geturl(){ 
        return this.url; 
    }
}  

Bạn sử dụng hàm read() dạng như sau để đọc XML và trả về arrayList
    private ArrayList<Topic> read(InputStream in)  
    { 
         
        SAXParserFactory spf = SAXParserFactory.newInstance(); 
        SAXParser sp; 
        try { 
            sp = spf.newSAXParser(); 
            XMLReader xr = sp.getXMLReader(); 
            TopicHandler handler = new TopicHandler(); 
            xr.setContentHandler(handler); 
            xr.parse(new InputSource(in)); 
            return handler.getTopics(); 
        } catch (ParserConfigurationException e) { 
        } catch (SAXException e) { 
        } catch (IOException e) { 
        } 
        return null; 
    }  

InputStream có thể là một file trong source của bạn hoặc một url
Nếu là file trong source:
this.Topics = read(getResources().openRawResource(R.raw.topics));  
File này được đặt trong folder raw...

Nếu là một URL:


URL myurl=new URL(link);             
URLConnection conn = myurl.openConnection(); 
InputStream is = conn.getInputStream();  

Sau khi đã lấy được dữ liệu vô ArrayList Topics thì bạn load nó lên ListView nhứ sau :
a/ Tạo một class TopicAdapter
import java.util.ArrayList; 

import developer.android.aVOA.Entities.Topic; 

import android.content.Context; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.ArrayAdapter; 
import android.widget.TextView; 
import developer.android.aVOA.ControllerLayer.R; 

public class TopicAdapter extends ArrayAdapter<Topic> { 

    private ArrayList<Topic> items; 
    private final LayoutInflater mInflater; 
    private final int mLayoutRes; 
    public TopicAdapter(Context context, int textViewResourceId, 
            ArrayList<Topic> _items) { 
        super(context, textViewResourceId,_items); 
        items = _items; 
        this.mLayoutRes = textViewResourceId; 
        this.mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_
SERVICE); 
    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
        View v; 
        if (convertView == null) { 
            v= mInflater.inflate(mLayoutRes, parent, false); 
        } 
        else 
            v=convertView; 
        Topic o = items.get(position); 
        if (o != null)  
        { 
            TextView tt = (TextView)v.findViewById(R.id.toptext); 
            if (tt != null)  
            { 
                tt.setText(o.gettitle()); 
            } 
            TextView bt = (TextView)v.findViewById(R.id.bottomtext); 
            if (bt != null)  
            { 
                bt.setText("aVOA. Developed by LINHNT"); 
            } 
        } 
        return v; 
    } 
}

b/ Và cuối cùng bạn chỉ cần setadapter cho Listview cần hiển thị.
this.t_adapter = new TopicAdapter(this, R.layout.topic_item, Topics);         
this.LstTopic=(ListView)findViewById(R.id.list); 
this.LstTopic.setAdapter(this.t_adapter);  

******************************************
LƯU THÔNG TIN CẤU HÌNH ỨNG DỤNG TRONG ANDROID
Mình xin chia sẻ với các bạn đoạn code ngắn sau đây để giải quyết nhu cầu lưu thông tin setting cho ứng dụng android
của bạn.

Bài toán:
- ứng dụng android của bạn có phần thiết lập cấu hình để cung cấp cho người dùng các tùy chọn khi sử dụng, vậy chúng
ta sẽ lưu và đọc những thông tin này vào đâu và như thế nào ?

Phương án:

-Phương án mà tôi đưa ra ở đây là chúng ta sử dụng đến SharedPreferences lớp này cho phép chúng ta tương tác với
CSDL mà hệ điều hành cấp phát cho ứng dụng của chúng ta.

SharedPreferences là lớp con của android.content vì vậy trong code bạn phải


import android.content.SharedPreferences.

Nhưng để thực sự làm được việc lưu và đọc thông tin thì chúng ta lại phải dùng một lớp con nữa có tên là Editor lớp này
lại là con của SharedPreferences vì vậy trong phần import chúng ta sẽ làm như sau:

Mã:

import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

Tôi có đoạn code như sau:

Mã:

.....
//Tôi định nghĩa hằng số này dùng để định nghĩa tên cho vùng thông tin mà chúng ta sẽ
dùng để lưu các thông số (trong 1 vùng sẽ có nhiều trường thông tin khác nhau)
private static final String STRING_NAME_USERSETTING = "USER REFERENCES";

//Khai báo biến mShareRefs làm instance của SharedPreferences


private SharedPreferences mShareRefs = null;

/*
*Tôi định nghĩa hàm này để giúp chúng ta lưu thông tin
* Tham số key : kiểu String, là một chuỗi được dùng làm khóa để ta có thể dễ *dàng
tương tác với thông tin, và khóa này phải là duy nhất cho mỗi *trường thông tin mà bạn
muốn lưu
* Tham số value: giá trị / thông tin mà bạn muốn lưu
* vì tôi chỉ muốn lưu lại thông tin có dạng logic (boolean) nên kiểu dữ liệu *cho tham số
value tôi sẽ khai báo là boolean - đương nhiên là bạn có thể *khai báo kiểu dữ liệu theo ý
của mình (vd: String, Int,...)
*/
public void saveSetting(String key, boolean value) {

//Khởi tạo giá trị cho mShareRefs bằng cách gán cho nó giá trị trả về //từ hàm
getSharedPreferences(Tên vùng dữ liệu, Quyền truy cập)
//ở đây tôi chỉ cho phép truy cập trong phạm vi của chương trình mà thôi nên tôi dùng tham
số Activity.MODE_PRIVATE
mShareRefs = getSharedPreferences(STRING_NAME_USERSETTING,
Activity.MODE_PRIVATE);

//Khai báo editor và khởi tạo giá trị cho nó từ giá trị trả về của hàm edit() từ
mShareRefs
Editor editor = mShareRefs.edit();
//dùng phương thức putBoolean(Khóa, Giá trị) để lưu thông tin
//Lưu ý: tùy vào kiểu thông tin bạn muốn lưu mà bạn sẽ gọi một phương thức put tương ứng ,
vd: Int thì dùng putInt(), String thì dùng putString(),...
editor.putBoolean(key, value);

//sau đó chúng ta gọi thủ tục commit() để hoàn tất việc lưu dữ liệu và đóng editor.
editor.commit();

//Tôi định nghĩa hàm getSetting (khóa đã dung để lưu ) để đọc ra thông tin tương ứng
//vì ở trên tôi đã lưu thông tin kiểu boolean nên giá trị trả về của hàm này cũng phải là
boolean
public boolean getSetting(String key)
{
//Giống như ở phần lưu thông tin, chúng ta phải khởi tạo giá trị cho mShareRefs
trỏ tới vùng thông tin mà ta đã tạo ra để lưu các thông số
mShareRefs = getSharedPreferences(STRING_NAME_USERSETTING,
Activity.MODE_PRIVATE);

//ta dùng các thủ tục get...để lấy về thông tin tương ứng qua khóa
return mShareRefs.getBoolean(key, false);

}
....

**Đương nhiên là khi bạn tắt ứng dụng hay reboot lại hệ điều hành thì các thông số trên không bị mất đi , trừ khi bạn gỡ
bỏ ứng dụng.
**Và các bạn có thể ghi đè (thay đổi ) thông tin đã có bằng thông tin mới qua các khóa, nếu thông tin cũ là rỗng thì quá
trình tạo mới sẽ xảy ra.

Mong rằng đoạn code trên sẽ giúp các bạn dễ dàng lưu thông tin hệ thống cho ứng dụng của mình.
******************************************
XÁC ĐỊNH VÀ ĐỌC/GHI SD CARD
Sau đây tôi xin chia sẻ với các bạn giải pháp xác định sdcard đã được cài đặt chưa hoặc có sử dụng được không và cách
xác định đường dẫn chính xác tới sdcard để phục vụ cho các mục đích đọc/ghi dữ liệu:

1. Xác định xem máy đã cắm sdcard hay chưa:

Chúng ta import gói sau vào :


PHP Code:
import android.os.Environment;  
tiếp đến sử dụng hàm sau để xác định trạng thái của sdcard:
PHP Code:
android.os.Environment.getExternalStorageState();  
Hàm getExternalStorageState() sẽ return một chuỗi thông báo trạng thái hiện tại của sdcard, chuỗi này có thể là:
- "mounted" (MEDIA_MOUNTED): thẻ sẵn sàng cho việc đọc ghi
- "mounted_ro" (MEDIA_MOUNTED_READ_ONLY) : thẻ chỉ cho phép đọc
- "bad_removal" (MEDIA_BAD_REMOVAL): sdcard đã bị tháo ra không đúng cách
- "checking" (MEDIA_CHECKING): sdcard đang trong quá trình kiểm tra lỗi
- "removed" (MEDIA_REMOVED): sdcard đã được tháo ra
- "nofs" (MEDIA_NOFS): sdcard đang rỗng hoặc sử dụng định dạng không phù hợp
- "unmountable" (MEDIA_UNMOUNTABLE): sdcard không thể sử dụng được do bị lỗi
- "unmounted" (MEDIA_UNMOUNTED): sdard có trong máy nhưng đã được gỡ bằng lệnh

Từ những thông số trên chúng ta có thể viết một đoạn code để check trạng thái hiện tại của sdcard như sau:

PHP Code:
String state = android.os.Environment.getExternalStorageState(); 
if(state.equals(android.os.Environment.MEDIA_MOUNTED))   

           //Chúng ta sẽ làm gì đó tương ứng ở đây 
}  
*** Trước khi đọc/ghi data lên sdcard chúng ta nên check trạng thái của sdcard trước .

2. Lấy đường dẫn đến sdcard:


Hiện tại đang có rất nhiều bạn thắc mắc về đương dẫn tới sdcard là như thế nào, nhiều bạn không biết nên việc tạo file,
đọc file là rất khó khăn và bug mất thời gian.

Chúng ta có cách đơn giản sau để lấy về đường dẫn chính xác đến thư mục gốc của sdcard:

PHP Code:
Environment.getExternalStorageDirectory().getAbsolutePath();  
sửu dụng hàm trên sẽ trả về cho chúng ta đường dẫn tuyệt đối tới sdcard, sau đó chúng ta sử dụng đường dẫn này và
cộng thêm tên các thư mục bên trong nếu có để tạo đường dẫn mà bạn muốn truy cập vào.

Ví dụ: 

PHP Code:
String sdcard_path = Environment.getExternalStorageDirectory().getAbsolutePath(); 
String media_path = sdcard_path + "/" + "media"; 
//làm những việc liên quan ở đây  
Chúc các bạn vui vẻ!
************************************
LÀM ỨNG DỤNG HIỂN THỊ FULLSCREEN
Rất ngắn và hiệu quả 

PHP Code:
  public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState);         
        requestWindowFeature(Window.FEATURE_NO_TITLE); 
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.Lay
outParams.FLAG_FULLSCREEN); 
        setContentView(R.layout.main); 
    }  
Cách thứ 2 là thêm vào dòng sau ở trong AndroidManifest.xml phần khai báo Activity:
Mã:

android:theme="@android:style/Theme.NoTitleBar.Fullscreen"

VD:
Mã:

<activity android:name=".TooDo"
android:label="@string/app_name"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
>

*******************************
KILL APPLICATION
Để tắt hoàn toàn 1 ứng dụng hay 1 tiến trình đang hoạt động bạn sử dụng :
PHP Code:
android.os.Process.killProcess(android.os.Process.myPid())  
myPid() ở đây trả về id của tiến trình ( ProcessID ).
Chỉ 1 dòng lệnh thôi nhưng các bạn có thể đã nghĩ đến nhiều ý tưởng, chẳng hạn như viết 1 ứng dụng quản lý các tiến
trình , sau khi list ra các tiến trình trong hệ thống thì người sử dụng có thể tắt các ứng dụng không cần thiết . Các bạn có
thể tham khảo ứng dụng "Advanced Task Killer" trên Market

***************************************
MỞ FILE BẰNG ỨNG DỤNG MẶC ĐỊNH SỬ DỤNG INTENT
Mở 1 file Video:

PHP Code:
        Intent intent = new Intent();
        intent.setAction(android.content.Intent.ACTION_VIEW);
        File file = new File("/sdcard/VideoFileName.mp4");
        intent.setDataAndType(Uri.fromFile(file), "video/*");
        startActivity(intent);  
Hoặc 1 file Audio:

PHP Code:
        Intent intent = new Intent();
        intent.setAction(android.content.Intent.ACTION_VIEW);
        File file = new File("/sdcard/AudioFileName.mp3");
        intent.setDataAndType(Uri.fromFile(file), "audio/*");
        startActivity(intent);  

**********************************
KIỂM TRA CÓ TỒN TẠI SD CARD
Rất ngắn gọn nhưng đôi khi rất cần thiết 

Mã:

public static boolean isSdPresent() {


return
android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNT
ED);
}

*********************************
ĐỌC FILE .TXT TRONG SD CARD
Giả sử bạn muốn đọc nội dung file test.txt để trong sdcard ( /sdcard/test.txt )

Mã:

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é.
****************************************
GỌI CONTACT LIST VÀ TƯƠNG TÁC
Sau đây tôi xin chia sẻ với các bạn đoạn code cho phép chúng ta gọi contact list của Android OS và xử lý nó theo ý của
ta.

Các bạn làm theo 3 bước sau đây:

Bước 1:
Thêm READ_CONTACTS để hệ thống cho phép bạn đọc Contact từ code:
Mã:

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

Bước 2:
Viết code để gọi Contact Picker sử dụng Intent.ACTION_PICK
Mã:

//Tạo mới Intent và báo cho nó việc truy cập vào contact list
Intent intent = new Intent(Intent.ACTION_PICK, People.CONTENT_URI);

//Start Activity và đợi kết quả trả về (chúng ta sẽ nhận và xử lý kết


quả trả về qua event "onActivityResult"

startActivityForResult(intent, PICK_CONTACT);

Bước 3:
Nhận kết quả trả về nếu quá trình truy vấn là OK, sau đó bạn có thể xử lý dữ liệu đó theo ý riêng của bạn.
Mã:

@Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);

switch (reqCode) {
case (PICK_CONTACT) :
//Nếu kết quả truy vấn == Activity.RESULT_OK (thành công)
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
if (c.moveToFirst()) {
String name = c.getString(c.getColumnIndexOrThrow(People.NAME));
// Làm những việc mà bạn muốn đối với dữ liệu này
}
}
break;
}
}

***Hy vọng các bạn thấy thích thú đoạn code này 

**************************************
ỨNG DỤNG KHÔNG KẾT NỐI ĐƯỢC INTERNET
Mặc định khi bạn tạo một android project thì nó sẽ không có quyền (permission) để truy cập tới internet qua các giao
thức (http,socket), nên để ứng dụng của bạn có thể connect được thì bạn cần làm một thao tác đơn giản như sau:

-Mở tệp AndroidManifest.xml trong dự án của bạn (mở ở chế độ planttext nhé)
-Sau đó thêm vào một đoạn cấu hình như sau:
Mã:

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
**Lưu ý: nên thêm nó vào dòng cuối cùng nhưng nằm trên </manifest> 
-Sau đây là đoạn code mẫu:
Mã:

<?xml version="1.0" encoding="utf-8"?>


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="vad.tabdemo"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".cotainer"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="Tab1Activity"></activity>
<activity android:name="Tab2Activity"></activity>

</application>
<uses-sdk android:minSdkVersion="4" />

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>

***************************************
GỬI MAIL TỪ ANDROID CODE
Tôi xin chia sẻ với các bạn đoạn code giúp tự động mở ứng dụng send mail có sẵn trên Android OS từ Android code.

Đoạn code này sẽ yêu cầu Intent gửi một thông báo tới hệ thống là mở ứng dụng gửi mail mặc định (gmail) mà không
cần phải quay ra menu chính.

Mã:

Intent intent = new Intent(Intent.ACTION_SENDTO,


Uri.fromParts("mailto", "test@test.com", null));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);

***Chúng ta dùng ACTION_SENDTO của Intent để làm việc này.

Chúc các bạn vui vẻ!

*********************************************
TRANSPARENT HÌNH

public static Bitmap transparency(Bitmap seed) {


int mWidth = seed.getWidth();
int mHeight = seed.getHeight();
int[] mArrayColor = new int[mWidth * mHeight];

Bitmap bitmap = Bitmap.createBitmap(mWidth, mHeight, Config.ARGB_4444);

int mColor = seed.getPixel(0, 0);


seed.getPixels(mArrayColor, 0, mWidth, 0, 0, mWidth, mHeight);

for (int i = 0; i < mArrayColor.length; i++) {


if(mArrayColor[i] == mColor) {
mArrayColor[i] = 0; // transparent
}
}
bitmap.setPixels(mArrayColor, 0, mWidth, 0, 0, mWidth, mHeight);
seed = null;

return bitmap;
}

note: không hiển thị được indent mặc dù có

**********************************
THÊM WEB LINK VÀO LISTVIEW
Mình xin chia sẻ với các bạn cách chèn một link tới trang web nào đó vào listview item :
-Bạn dùng textview để hiển thị link và sau đó bind listview với một custom adaper.
-Bạn đặt đoạn code sau trong thủ tục getView.
Mã:

textcontent.setText(Html.fromHtml(item.get_text()));
textcontent.setAutoLinkMask(Linkify.WEB_URLS);

*Lưu ý:
Thiết lập thuộc tính autoLink="web" của textview như sau:
<TextView
android:id="@+id/txtview"
android:autoLink="web"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="put your link here"
/>

*******************************
QUERY SỐ SMS CHƯA ĐỌC TRONG INBOX
Sau đây mình xin hướng dẫn các bạn cách query (truy vấn) số lượng SMS chưa đọc từ inbox của android phone.

Mã:

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsMessage;
import android.widget.Toast;

public class SMSReceiver extends BroadcastReceiver


{
public void onReceive(Context context, Intent intent)
{
Bundle myBundle = intent.getExtras();
SmsMessage [] messages = null;
String strMessage = "";

if (myBundle != null)
{
Object [] pdus = (Object[]) myBundle.get("pdus");
messages = new SmsMessage[pdus.length];

for (int i = 0; i < messages.length; i++)


{
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
strMessage += "SMS From: " + messages[i].getOriginatingAddress();
strMessage += " : ";
strMessage += messages[i].getMessageBody();
strMessage += "\n";
}

Toast.makeText(context, strMessage, Toast.LENGTH_SHORT).show();


}
}
}

***Copy->paste và chạy test đc luôn nhé!

**********************************
GỬI SMS VỚI ANDROID CODE
Sau đây tôi xin hướng dẫn các bạn cách gửi SMS bằng Android code.

Chúng ta sử dụng "SMS content provider" để đọc và ghi nội dung SMS:
Mã:

ContentValues values = new ContentValues();


values.put("address", "123456789");
values.put("body", "Nội dung cần gửi");
getContentResolver().insert(Uri.parse("content://sms/sent"), values);

hoặc sử dụng cách sau:

Mã:

Intent sendIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("sms://"));


sendIntent.putExtra("address", "123456789");
sendIntent.putExtra("sms_body", "Nội dung cần gửi");
startActivity(sendIntent);

Chúc cả nhả vui vẻ!

*********************************
ỨNG DỤNG MẪU
Yêu Cầu : Tạo 1 Gui gồm có 9 ô 3x3 sau đó khởi tạo các số từ 1->8 vào các ô 1 cách ngẫu nhiên , Khi ta clik vao 1 ô nếu
là ô trôngs thì k có gì xẩy ra nếu clik vào 1 ô mà ô bên cạnh nó trống thì đổi chỗ ô đó , nếu k thì giữ nguyên ! Kết thúc
khi các số theo thứ tự 1 2 3 4 5 6 7 8 
Code
Quote:

package com.Viet.TraoSo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import java.util.*;
public class TraoSo extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
change();
}
public void init()

Button button1 = (Button)findViewById(R.id.button1);
Button button2 = (Button)findViewById(R.id.button2);
Button button3 = (Button)findViewById(R.id.button3);
Button button4 = (Button)findViewById(R.id.button4);
Button button5 = (Button)findViewById(R.id.button5);
Button button6 = (Button)findViewById(R.id.button6);
Button button7 = (Button)findViewById(R.id.button7);
Button button8 = (Button)findViewById(R.id.button8);
Button button9 = (Button)findViewById(R.id.button9);
String tu = "12345678 ";
StringBuffer settext = new StringBuffer(tu.length());
StringBuffer change = new StringBuffer(tu);
while(change.length()!=0)
{
Random random = new Random();
int i = random.nextInt(change.length());
settext.append(change.charAt(i));
change.delete(i,i+1);
}
String tam = settext.toString();
Button listButton[] = {button1,button2,button3,button4,button5,button6,b utton7,button8,button9};
for(int i =0 ; i<9;++i)
{
listButton[i].setText(tam.substring(i,i+1));
}
}
public void change()
{
final Button button1 = (Button)findViewById(R.id.button1);
final Button button2 = (Button)findViewById(R.id.button2);
Button button3 = (Button)findViewById(R.id.button3);
final Button button4 = (Button)findViewById(R.id.button4);
Button button5 = (Button)findViewById(R.id.button5);
Button button6 = (Button)findViewById(R.id.button6);
Button button7 = (Button)findViewById(R.id.button7);
Button button8 = (Button)findViewById(R.id.button8);
Button button9 = (Button)findViewById(R.id.button9);
final Button listButton[] = {button1,button2,button3,button4,button5,button6,b utton7,button8,button9}; 
Button reset = (Button)findViewById(R.id.reset);
reset.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v) {
init();
}
});
listButton[0].setOnClickListener(new Button.OnClickListener(){ // neu click chuot vao button thu nhat(listButton[0])
public void onClick( View v){ 
if(listButton[1].getText().equals(" ")){ // neu button thu 2 la o trong
listButton[1].setText(listButton[0].getText()) ; // doi gia tri o thu 2 va o thu nhat
listButton[0].setText(" ") ; // dua o thu 1 ve o trong
}
if(listButton[3].getText().equals(" ")){ // neu o thu 4 la o trong
listButton[3].setText(listButton[0].getText()) ; // doi gtri o thu 1 vao o thu 4
listButton[0].setText(" ") ;
}
}
});
listButton[1].setOnClickListener(new Button.OnClickListener(){ // neu click chuot vao button thu hai(listButton[0])
public void onClick( View v){ 
if(listButton[0].getText().equals(" ")){
listButton[0].setText(listButton[1].getText().toString()) ;
listButton[1].setText(" ") ;
}
// gtri o thu 3 = gtri o thu 2
if(listButton[2].getText().equals(" ")){
listButton[2].setText(listButton[1].getText().toString()) ; 
listButton[1].setText(" ") ;
}
if(listButton[4].getText().equals(" ")){
listButton[4].setText(listButton[1].getText().toString()) ;
listButton[1].setText(" ") ;
}
}
});
listButton[2].setOnClickListener(new Button.OnClickListener(){ // neu click chuot vao button thu ba(listButton[2])
public void onClick( View v){ 
if(listButton[1].getText().equals(" ")){ // neu o thu 2 la o trong
listButton[1].setText(listButton[2].getText().toString()) ;
listButton[2].setText(" ") ; // cho o thu 3 la o trong

if(listButton[5].getText().equals(" ")){
listButton[5].setText(listButton[2].getText().toString()); // cho o thu 6 nhan gtri cua o thu 3
listButton[2].setText(" ") ; // choo thu 3 la o trong
}
}
});
listButton[3].setOnClickListener(new Button.OnClickListener(){ // neu click chuot vao button thu tu(listButton[4])
public void onClick( View v){ 
if( listButton[0].getText().equals(" ")){
listButton[0].setText(listButton[3].getText().toString()) ;
listButton[3].setText(" ") ;
}
if(listButton[4].getText().equals(" ")){
listButton[4].setText(listButton[3].getText().toString()) ;
listButton[3].setText(" ") ;
}
if(listButton[6].getText().equals(" ")){
listButton[6].setText(listButton[3].getText().toString()) ;
listButton[3].setText(" ") ;
}

}
}) ;
listButton[4].setOnClickListener(new Button.OnClickListener(){ // neu click chuot vao button thu nam(listButton[4])
public void onClick( View v){ 
if(listButton[1].getText().equals(" ")){
listButton[1].setText(listButton[4].getText().toString()) ;
listButton[4].setText(" ") ;
}
if(listButton[5].getText().equals(" ")){
listButton[5].setText(listButton[4].getText().toString()) ;
listButton[4].setText(" ") ;
}
if(listButton[7].getText().equals(" ")){
listButton[7].setText(listButton[4].getText().toString()) ;
listButton[4].setText(" ") ;
}
if(listButton[3].getText().equals(" ")) {
listButton[3].setText(listButton[4].getText().toString()) ;
listButton[4].setText(" ") ;
}
}
});
listButton[5].setOnClickListener(new Button.OnClickListener(){ // neu click chuot vao button thu sau(listButton[0])
public void onClick( View v){ 
if(listButton[2].getText().equals(" ")){
listButton[2].setText(listButton[5].getText().toString()) ;
listButton[5].setText(" ") ;
}
if(listButton[4].getText().equals(" ")){
listButton[4].setText(listButton[5].getText().toString()) ;
listButton[5].setText(" ") ;
}
if(listButton[8].getText().equals(" ")){
listButton[8].setText(listButton[5].getText().toString()) ;
listButton[5].setText(" ") ;
}
}
});
listButton[6].setOnClickListener(new Button.OnClickListener(){ // neu click chuot vao button thu bay(listButton[6])
public void onClick( View v){ 
if(listButton[3].getText().equals(" ")){
listButton[3].setText(listButton[6].getText().toString()) ;
listButton[6].setText(" ") ;
}
if(listButton[7].getText().equals(" ")){
listButton[7].setText(listButton[6].getText().toString()) ;
listButton[6].setText(" ") ;
}
}
});
listButton[7].setOnClickListener(new Button.OnClickListener(){ // neu click chuot vao button thu tam(listButton[7])
public void onClick( View v){ 
if(listButton[4].getText().equals(" ")){
listButton[4].setText(listButton[7].getText().toString()) ;
listButton[7].setText(" ") ;
}
if(listButton[6].getText().equals(" ")){
listButton[6].setText(listButton[7].getText().toString()) ;
listButton[7].setText(" ") ;
}
if(listButton[8].getText().equals(" ")){
listButton[8].setText(listButton[7].getText().toString()) ;
listButton[7].setText(" ") ;
}
}
});
listButton[8].setOnClickListener(new Button.OnClickListener(){ // neu click chuot vao button thu 9(listButton[9])
public void onClick( View v){ 
if(listButton[5].getText().equals(" ")){
listButton[5].setText(listButton[8].getText().toString()) ;
listButton[8].setText(" ") ;
}
if(listButton[7].getText().equals(" ")){
listButton[7].setText(listButton[8].getText().toString()) ;
listButton[8].setText(" ") ;
}
}
});

}
}
Đây là file TraoSo.java 
Còn các file main.xml sẽ là tạo 9 cái button và set 1 số các hiệu ứng . Các bạn có thể phát triển lên đây chỉ là 1 bài mình
làm cũng lâu lâu rồi 

You might also like