Official Site

click here to view our new site launched

Pages

Monday, May 21, 2012

Database helper class in Android


import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class Database{
SQLiteDatabase db;
String DB_NAME="test.db";
String root="data/data/com.example.test/";
 
String DB_FULL_PATH=root+"databases/"+DB_NAME;
int Rcount=0;
public void CreateDB(Activity a) {
 
        this.db = a.openOrCreateDatabase(
        DB_NAME
      , SQLiteDatabase.CREATE_IF_NECESSARY
      , null
      );
       
       
        db.setVersion(1);
        db.setLocale(Locale.getDefault());
        db.setLockingEnabled(true);
       
}
 
public void OpenDB(Activity a) {
 
this.db = SQLiteDatabase.openDatabase(DB_FULL_PATH, null,
                SQLiteDatabase.OPEN_READWRITE);
       
}
 
 public void CloseDB(Activity a) { 
this.db.close();       
}

public boolean checkDataBase() {
    SQLiteDatabase checkDB = null;
    try {
       
checkDB = SQLiteDatabase.openDatabase(DB_FULL_PATH, null,
                SQLiteDatabase.OPEN_READONLY);
        checkDB.close();
    } catch (Exception e) {
        // database doesn't exist yet.
    }
    return checkDB != null ? true : false;
}

public void CreateTable( String CREATE_TABLE){
db.execSQL(CREATE_TABLE);
}
//String s="CREATE TABLE user (ID INTEGER PRIMARY KEY, phone NUMERIC, Name TEXT)";
public void insertDB(ContentValues values,String table) {
//db.insert(table, null, values); // it will create new rows and wont merge if already exist. i.e. insert
db.replace(table, null, values); // it will merge data in existing rows or else creates new row .i.e insert or update
}
public Cursor resultDB(String query) {
//Vector vector = new Vector();
String res="";
Cursor cur = db.rawQuery(query,new String[]{});
Rcount=cur.getCount();      
return cur;
}

public String[] getAllResultStr(String query,int pos)
    {
        Cursor cursor = db.rawQuery(query,new String[]{});

        if(cursor.getCount() >0)
        {
            String[] str = new String[cursor.getCount()];
            int i = 0;

            while (cursor.moveToNext())
            {
                 str[i] = cursor.getString(pos);
                 i++;
             }
            cursor.close();
            return str;
        }
        else
        {  cursor.close();
            return new String[] {};
        }
    }

public List getAllResultList(String query,int pos)
    {
        Cursor cursor = db.rawQuery(query,new String[]{});
        List list=new ArrayList(10);

        if(cursor.getCount() >0)
        while (cursor.moveToNext())
                list.add( cursor.getString(pos)) ;
        
        return list;

    }

public int getRowCount() {
return Rcount;
}


public void updateDB(ContentValues values,String tbname,String whereClause,String [] whereArgs) {
db.update(tbname,values, whereClause, whereArgs);
}

public void deleteDB(String TABLE_NAME,String WHERE,String[] args) {
db.delete(TABLE_NAME,WHERE,args);
}
}

Thursday, May 17, 2012

RandomFileWriter in Andriod



import java.io.File;
import java.io.RandomAccessFile;

import android.os.Environment;
import android.util.Log;

public class RandomFileWriter {
public long writeData(String text,String path,long seek){
try {
// example path : "/data/data/com.example.test/file"
RandomAccessFile file = new RandomAccessFile(path, "rw");
long i=file.length()-seek,j;
Log.i("File length",""+i);
file.seek(i);
file.writeBytes(text);
j=file.getFilePointer();
file.close();
return j;
}catch (Exception e) {
// TODO Auto-generated catch block
Log.d("RandomFileWrite.java","Exception: "+e.getMessage());
return 0;
}
 
}
public void seekWrite(String text,String path,long seek) {
try {
RandomAccessFile file = new RandomAccessFile(path, "rw");
file.seek(seek);
file.writeBytes(text);
file.close();
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("RandomFileWrite.java seekwrite","Exception: "+e.getMessage());
}
}
String getExternalPath(){
return Environment.getExternalStorageDirectory().toString();
}

boolean isMediaReadOnly(){
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
    // We can only read the media
   
  return true;
}
return false;
}
boolean isMediaMounted(){
String state = Environment.getExternalStorageState();

if (Environment.MEDIA_MOUNTED.equals(state)) {
    // We can read and write the media
    Log.i("Exter", "media found: "+Environment.getExternalStorageDirectory());
  return true;
return false;
}
public void createDir(String path,String dir){
new File(path+dir).mkdir();
}
public void createDir(File dirPath){
dirPath.mkdir();
}
public boolean deleteDir(File dir) {
    if (dir.isDirectory()) {
        String[] children = dir.list();
        for (int i=0; ilength; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
        }
    }

    // The directory is now empty so delete it
    return dir.delete();
}
public boolean delFile(File f){
return f.delete();
 
}

void copy(File src, File dst) throws Exception{

    // Transfer bytes from in to out
    byte[] buf = new byte[1024];
    int len;
   
    RandomAccessFile in = new RandomAccessFile(src, "r");
RandomAccessFile out = new RandomAccessFile(dst, "rw");
    while ((len = in.read(buf)) > 0) {
        out.write(buf, 0, len);
    }
    in.close();
    out.close();
   
}

}
$2.49 .COM at GoDaddy.com! Expires 5/14/13