2013-12-17 58 views
-3

您好我是android新手,可以請大家幫我介紹如何創建一個用於處理數據庫的類。如何在android中創建自己的databse助手類

+3

http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/ –

+0

如果你願意,你可以使用這個庫https://github.com/ jgilfelt/android-sqlite-asset-helper –

回答

1

你需要做的就是創建一個普通的類,並將其擴展到 的SQLLiteOpenHelper類,並實現相應的方法是什麼,你可以參考這個

public class dbHandler extends SQLiteOpenHelper{ 
static String DB_NAME="mapsDb"; 
static int DB_VERSION=1; 
String TAB_NAME="usertable"; 
String FILED_ID="id"; 
String FILED_DRIVERNAME="driver_name"; 
String FILED_CARNUMBER="cno"; 
String FILED_CARMODEL="cmodel"; 
String MARKER_TAB="markerTable"; 
String FILED_DRIVERID="id"; 
String FILED_LAT="latitude"; 
String FILED_LON="longtitude"; 
public static Context con; 
    public dbHandler(Context context) { 
     super(context, DB_NAME, null, DB_VERSION); 
     // TODO Auto-generated constructor stub 
     this.con=context; 
    } 
    @Override 
    public void onCreate(SQLiteDatabase db) { 
     // TODO Auto-generated method stub 
     String CREATE_TABLE="CREATE TABLE "+TAB_NAME+" ("+FILED_ID+" TEXT PRIMARY KEY,"+FILED_DRIVERNAME+" TEXT,"+FILED_CARNUMBER+" TEXT,"+FILED_CARMODEL+" TEXT);"; 
     String CREATE_MARKE_TABLE="CREATE TABLE "+MARKER_TAB+" ("+FILED_DRIVERID+" TEXT,"+FILED_LAT+" TEXT,"+FILED_LON+" TEXT);"; 
     db.execSQL(CREATE_TABLE); 
     db.execSQL(CREATE_MARKE_TABLE); 

    } 
    @Override 
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
     // TODO Auto-generated method stub 
     db.execSQL("DROP TABLE IF EXISTS "+TAB_NAME); 
     db.execSQL("DROP TABLE IF EXISTS "+MARKER_TAB); 
     onCreate(db); 

    } 
    public void insertDriverDetails(String id, String name, 
      String cno, String mno) { 
     // TODO Auto-generated method stub 
     SQLiteDatabase db=this.getWritableDatabase(); 
     ContentValues cv=new ContentValues(); 
     cv.put(FILED_ID, id); 
     cv.put(FILED_DRIVERNAME, name); 
     cv.put(FILED_CARNUMBER, cno); 
     cv.put(FILED_CARMODEL, mno); 
     try{ 
     db.insert(TAB_NAME, null, cv); 
     } 
     catch(Exception e) 
     { 
      e.printStackTrace(); 
     } 
     db.close(); 



    } 
    public void updateMarkerForId(String id, String longt, String lat) { 
     // TODO Auto-generated method stub 
     SQLiteDatabase db=this.getWritableDatabase(); 
     String UPDATE_QUERY="UPADATE "+MARKER_TAB+" SET "+FILED_LON+"=\""+longt+"\","+FILED_LAT+"\""+lat+"\" WHERE "+FILED_DRIVERID+"=\""+id+"\";"; 
     db.execSQL(UPDATE_QUERY); 

    } 

} 
0

我的例子中你可以找到一個快速簡便的教程在這裏..

herehere also

+0

這應該是一個評論 – insomniac

2

你有一個瞭解創建JAV文件在你的src包和擴展SQLiteOpenHelper類。

然後用樣品教程來獲得更多這方面的想法......

下面是示例代碼和鏈接

public class DatabaseHandler extends SQLiteOpenHelper 
{ 
    private static final int DATBASE_VERSION = 1; // database version 
    private static final String DATABASE_NAME = "MyManager"; // database name 

    private static final String TABLE_NAME = "ImageTable"; // 1st table name 
    private static final String KEY_ID = "id"; // 1st column name 
    private static final String KEY_IMAGE = "image"; // 2nd Column name 

    // Constructor 
    public DatabaseHandler(Context context) 
    { 
     super(context, DATABASE_NAME, null, DATBASE_VERSION); 
    } 

    @Override 
    public void onCreate(SQLiteDatabase db) 
    { 
     String CREATE_IMAGE_TABLE = "CREATE TABLE " + TABLE_NAME + "(" + KEY_ID 
       + " INTEGER PRIMARY KEY , " + KEY_IMAGE + " BLOB "+ ")"; 
     db.execSQL(CREATE_IMAGE_TABLE); 
    } 

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

你可以找到更多在這裏

SQLite Integartion

在你主要活動你想調用這個類的方法創建對象的類和訪問或調用方法。

1
public class DatabaseHelper extends SQLiteOpenHelper 
{ 
public final static String DB_NAME = "sample.sqlite"; 
private final static String DB_KEY = "db_key"; 

public static String DATABASE_PATH; 
private static SQLiteDatabase sqliteDatabase; 
private static int DB_VERSION = 1; 

private static Context myContext; 
private SharedPreferences sharedPreference; 
private SharedPreferences.Editor editor; 


public DatabaseHelper(Context context) 
{  
    super(context, DB_NAME, null, DB_VERSION = getVersionCode(myContext = context)); 
    DATABASE_PATH = myContext.getFilesDir().toString() + "/" + DB_NAME; 
    sharedPreference = PreferenceManager.getDefaultSharedPreferences(myContext); 
    initDB(); 
} 

private void initDB() 
{ 
    if(isDbExists()) 
    { 
     if(getVersion() != DB_VERSION) 
     { 
      myContext.deleteDatabase(DATABASE_PATH); 
      copyDataBase(); 
     } 
     else 
     { 
      openDataBase(); 
     } 
    } 
    else 
    { 
     copyDataBase(); 
    } 

} 


/** Get the database version from a shared preference*/ 
private int getVersion() 
{ 
    return sharedPreference.getInt(DB_KEY, 1); 
} 


/** Save the database version in a shared preference*/ 
private void saveVersion() 
{ 
    editor= sharedPreference.edit(); 
    editor.putInt(DB_KEY, DB_VERSION); 
    editor.commit(); 
} 


private boolean isDbExists() 
{ 
    return new File(DATABASE_PATH).exists(); 
} 



public static SQLiteDatabase openDataBase() throws SQLException 
{  

    if(sqliteDatabase == null || !sqliteDatabase.isOpen())  
    { 
     if(DATABASE_PATH==null || DATABASE_PATH.equalsIgnoreCase("")) 
      DATABASE_PATH = LiveSdkSampleApplication.context.getFilesDir().toString() + "/" + DB_NAME; 
     sqliteDatabase = SQLiteDatabase.openDatabase(DATABASE_PATH, null, SQLiteDatabase.OPEN_READWRITE | SQLiteDatabase.CREATE_IF_NECESSARY); 
    } 

    return sqliteDatabase; 
} 


public synchronized static void closedatabase() 
{ 
    if(sqliteDatabase != null) 
     sqliteDatabase.close(); 
} 

@Override 
public void onCreate(SQLiteDatabase db) 
{ 

} 

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

} 

public static int getVersionCode(Context context) 
{ 
    int version = -1; 
    try 
    { 
     PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_META_DATA); 
     version = pInfo.versionCode; 
    } 
    catch (NameNotFoundException e1) 
    { 
    } 
    return version; 
} 

public synchronized static DictionaryEntry[][] get(String query_str) 
{ 

    DictionaryEntry dir = null; 
    String[] columns; 
    int index; 
    int rowIndex = 0; 
    DictionaryEntry[] row_obj = null; //An array of columns and their values 
    DictionaryEntry[][] data_arr = null; 
    Cursor c; 

    if(sqliteDatabase != null) 
    { 
     try 
     { 
      openDataBase(); 
      c = sqliteDatabase.rawQuery(query_str, null); 
      if(c.moveToFirst()) 
      { 
       rowIndex = 0; 
       data_arr = new DictionaryEntry[c.getCount()][]; 
       do 
       { 
        columns = c.getColumnNames(); 
        row_obj = new DictionaryEntry[columns.length]; 
        for(int i=0; i<columns.length; i++) 
        { 
         dir = new DictionaryEntry();        
         dir.key = columns[i]; 
         index = c.getColumnIndex(dir.key); 
         dir.value = c.getString(index); 
         row_obj[i] = dir; 
        } 
        data_arr[rowIndex] = row_obj; 
        rowIndex++; 
       } 
       while(c.moveToNext()); 
      } 
      c.close(); 
     } 
     catch(Exception e) 
     { 
      e.printStackTrace(); 
     } 
    } 
    return data_arr; 
} 

public void copyDataBase() 
{ 
    //If database not copied from assets 
    try 
    { 
     boolean isFound = false; 
     int i=0; 
     String str = ""; 
     ZipFile zip = null; 
     ZipEntry zipen = null; 
     while(!isFound) 
     { 
      try 
      { 
       if(i == 0) 
       { 
        str = ""; 
       } 
       else 
       { 
        str = "-"+i; 
       } 
       zip = new ZipFile("/data/app/"+myContext.getPackageName()+str+".apk"); 
       zipen = zip.getEntry("assets/" + DB_NAME); 
       isFound = true; 
      } 
      catch(Exception e) 
      { 
       isFound = false; 
      } 
      ++i; 
     } 

     InputStream is = zip.getInputStream(zipen); 
     OutputStream os = null; 

     os = myContext.openFileOutput(DB_NAME, Context.MODE_WORLD_READABLE); 

     int len; 
     byte[] buffer = new byte[4096]; 
     while ((len = is.read(buffer)) >= 0) 
     { 
      os.write(buffer, 0, len); 
     } 
     is.close(); 
     os.close(); 

     openDataBase(); 
    } 
    catch (Exception e) 
    { 
     e.printStackTrace(); 
    } 
    finally 
    { 
     saveVersion(); 
    } 
} 

}

+0

通過這個你可以選擇刪除舊版本數據庫並用於所有數據庫操作。 – user3109745

相關問題