Thứ Hai, 25 tháng 11, 2013

Dùng google translate để dịch trong android

package com.example.studyenglish;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import org.apache.http.ParseException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;







/**
 *
 * @author Code4LifeVn
 */
public class TestTranslate {
   
    private final String googleTranslatorURL = "http://translate.google.com/translate_a/t?";
    private LANGUAGE srcLang = LANGUAGE.AUTO;
    private LANGUAGE destLang = LANGUAGE.VIETNAMESE;
    private String userAgent = "Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16";

    public String translate(String query) throws MalformedURLException, IOException, ParseException {
        URL url = new URL(this.buildURLRequestWith(query));
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.addRequestProperty("User-Agent", this.userAgent);
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(30000);
        conn.connect();

        InputStream inputStream = conn.getInputStream();
        BufferedReader bis = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        String respContent = bis.readLine();
        inputStream.close();
        bis.close();
        conn.disconnect();

        StringBuilder contentBuilder = new StringBuilder();

        try {
        JSONObject jsonData = new JSONObject(respContent);
        JSONArray sentences = (JSONArray) jsonData.get("sentences");
   JSONObject jsondetail = sentences.getJSONObject(0);
   contentBuilder.append(jsondetail.get("trans"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

        return contentBuilder.toString().trim().replace(" .", ". ");
    }

    private String buildURLRequestWith(String query) {
        StringBuilder urlBuilder = new StringBuilder();
        urlBuilder.append(this.googleTranslatorURL);
        urlBuilder.append("client=webapp");
        urlBuilder.append("&sl=auto");
        urlBuilder.append("&tl=").append(this.destLang);
        urlBuilder.append("&hl=").append(this.srcLang);
        urlBuilder.append("&sc=1");
        String queryEncoded = "";
        try {
            queryEncoded = URLEncoder.encode(query, "UTF-8");
            System.out.print(queryEncoded);
        } catch (Exception e) {
        }
        urlBuilder.append("&q=").append(queryEncoded);
        return urlBuilder.toString();
    }

    public LANGUAGE getSrcLang() {
        return srcLang;
    }

    public void setSrcLang(LANGUAGE srcLang) {
        this.srcLang = srcLang;
    }

    public LANGUAGE getDestLang() {
        return destLang;
    }

    public void setDestLang(LANGUAGE destLang) {
        this.destLang = destLang;
    }

    public String getUserAgent() {
        return userAgent;
    }

    public void setUserAgent(String userAgent) {
        this.userAgent = userAgent;
    }
   
    public static enum LANGUAGE {
        ENGLISH("en"),
        VIETNAMESE("vi"),
        AUTO("auto");
       
        private String lang = "";
        private LANGUAGE(String lang) {
            this.lang = lang;
        }
        @Override
        public String toString() {
            return this.lang;
        }
    }
       
}

Cách dùng:
TestTranslate translator = new TestTranslate();
       translator.setSrcLang(LANGUAGE.ENGLISH);
       translator.setDestLang(LANGUAGE.VIETNAMESE);
       String data = null;      
try {
data = translator.translate(url);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (org.apache.http.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Thứ Bảy, 23 tháng 11, 2013

How to copy files in 'assets' to sdcard?

private void copyAssets() {
    AssetManager assetManager = getAssets();
    String[] files = null;
    try {
        files = assetManager.list("");
    } catch (IOException e) {
        Log.e("tag", "Failed to get asset file list.", e);
    }
    for(String filename : files) {
        InputStream in = null;
        OutputStream out = null;
        try {
          in = assetManager.open(filename);
          File outFile = new File(getExternalFilesDir(null), filename);
          out = new FileOutputStream(outFile);
          copyFile(in, out);
          in.close();
          in = null;
          out.flush();
          out.close();
          out = null;
        } catch(IOException e) {
            Log.e("tag", "Failed to copy asset file: " + filename, e);
        }       
    }
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
    byte[] buffer = new byte[1024];
    int read;
    while((read = in.read(buffer)) != -1){
      out.write(buffer, 0, read);
    }
}
Reference : Move file using Java

Thứ Sáu, 22 tháng 11, 2013

Play audio file from the assets directory

public void playBeep() {
    try {

        if (m.isPlaying()) {
            m.stop();
            m.release();
            m = new MediaPlayer();
        }
        AssetFileDescriptor descriptor = getAssets().openFd("beepbeep.mp3");
        m.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
        descriptor.close();

        m.prepare();
        m.setVolume(1f, 1f);
        m.setLooping(true);
        m.start();
    } catch (Exception e) {
    }
Your version would work if you had only one file in the assets directory. The asset directory contents are not actually 'real files' on disk. All of them are put together one after another. So, if you do not specify where to start and how many bytes to read, the player will read up to the end (that is, will keep playing all the files in assets directory)

Thứ Hai, 18 tháng 11, 2013

Listen Scroll in webview

package com.example.studyenglish;

import android.content.Context;
import android.util.AttributeSet;
import android.webkit.WebView;

public class ObservableWebView extends WebView
{
    private OnScrollChangedCallback mOnScrollChangedCallback;

    public ObservableWebView(final Context context)
    {
        super(context);
    }

    public ObservableWebView(final Context context, final AttributeSet attrs)
    {
        super(context, attrs);
    }

    public ObservableWebView(final Context context, final AttributeSet attrs, final int defStyle)
    {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onScrollChanged(final int l, final int t, final int oldl, final int oldt)
    {
        super.onScrollChanged(l, t, oldl, oldt);
        if(mOnScrollChangedCallback != null) mOnScrollChangedCallback.onScroll(l, t);
    }

    public OnScrollChangedCallback getOnScrollChangedCallback()
    {
        return mOnScrollChangedCallback;
    }

    public void setOnScrollChangedCallback(final OnScrollChangedCallback onScrollChangedCallback)
    {
        mOnScrollChangedCallback = onScrollChangedCallback;
    }

    /**
     * Impliment in the activity/fragment/view that you want to listen to the webview
     */
    public static interface OnScrollChangedCallback
    {
        public void onScroll(int l, int t);
    }
}


wv = (ObservableWebView) findViewById(R.id.scorllableWebview); wv.setOnScrollChangedCallback(new OnScrollChangedCallback(){ public void onScroll(int l, int t){ //Do stuff Log.d(TAG,"We Scrolled etc..."); } });

Thứ Tư, 6 tháng 11, 2013

Code import file database từ bên ngoài trong android

package com.example.studyenglish;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import java.util.ArrayList;



import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Environment;
import android.util.Log;

public class DataEnglish extends SQLiteOpenHelper{

    //The Android's default system path of your application database.
    private static String DB_PATH ;

    private static String DB_NAME = "test";

    private SQLiteDatabase myDataBase;

    private final Context myContext;

    /**
     * Constructor
     * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
     * @param context
     */
    public DataEnglish(Context context) {

    super(context, DB_NAME, null, 2);
    DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
    Log.d("phanbom","Link toi thu muc databases"+DB_PATH );
        this.myContext = context;
    }

  /**
     * Creates a empty database on the system and rewrites it with your own database.
     * */
    public void createDataBase() throws IOException{

    boolean dbExist = checkDataBase();
        Log.d("phanbom","Check db ton tai:"+dbExist);
    if(dbExist){
    //do nothing - database already exist
    }else{

    //By calling this method and empty database will be created into the default system path
               //of your application so we are gonna be able to overwrite that database with our database.
        this.getReadableDatabase();

        try {

    copyDataBase();

    } catch (IOException e) {

        throw new Error("Error copying database");

        }
    }

    }

    /**
     * Check if the database already exist to avoid re-copying the file each time you open the application.
     * @return true if it exists, false if it doesn't
     */
    private boolean checkDataBase(){

    SQLiteDatabase checkDB = null;

    try{
    String myPath = DB_PATH + DB_NAME;
    checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

    }catch(SQLiteException e){

    //database does't exist yet.

    }

    if(checkDB != null){

    checkDB.close();

    }

    return checkDB != null ? true : false;
    }

    /**
     * Copies your database from your local assets-folder to the just created empty database in the
     * system folder, from where it can be accessed and handled.
     * This is done by transfering bytestream.
     * */
    private void copyDataBase() throws IOException{
        Log.d("phanbom","Vao ham copyDataBase()" );
    //Open your local db as the input stream
    InputStream myInput = myContext.getAssets().open(DB_NAME);
        Log.d("phanbom","Copy file from asset local" );
    // Path to the just created empty db
    String outFileName = DB_PATH + DB_NAME ;

    //Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);
        Log.d("phanbom","open system file" );
    //transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer))>0){
    myOutput.write(buffer, 0, length);
    }

    //Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();

    }

    public void openDataBase() throws SQLException{

    //Open the database
        String myPath = DB_PATH + DB_NAME ;
    myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
    }

    @Override
public synchronized void close() {

       if(myDataBase != null)
       myDataBase.close();

       super.close();

}

@Override
public void onCreate(SQLiteDatabase db) {

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
         
}

        // Add your public helper methods to access and get content from the database.
       // You could return cursors by doing "return myDataBase.query(....)" so it'd be easy
       // to you to create adapters for your views.
public void getCategory(){


   // Select All Query
   String selectQuery = "SELECT * FROM stream";

 
   Cursor cursor = myDataBase.rawQuery(selectQuery, null);
   Log.d("phanbom","Da query bang stream" );
   // looping through all rows and adding to list
   if (cursor.moveToFirst()) {
       do {
   
       } while (cursor.moveToNext());
   }
   // return contact list

}
}

Day la mot phien ban ngan hon
  package com.javatarts.basketballgm.data;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
 
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
 
public class AssetDatabaseOpenHelper {
 
private static final String DB_NAME = "asset.db";
 
private Context context;
 
public AssetDatabaseOpenHelper(Context context) {
this.context = context;
}
 
public SQLiteDatabase openDatabase() {
File dbFile = context.getDatabasePath(DB_NAME);
 
if (!dbFile.exists()) {
try {
copyDatabase(dbFile);
} catch (IOException e) {
throw new RuntimeException("Error creating source database", e);
}
}
 
return SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.OPEN_READONLY);
}
 
private void copyDatabase(File dbFile) throws IOException {
InputStream is = context.getAssets().open(DB_NAME);
OutputStream os = new FileOutputStream(dbFile);
 
byte[] buffer = new byte[1024];
while (is.read(buffer) > 0) {
os.write(buffer);
}
 
os.flush();
os.close();
is.close();
}
 
}