如何在android中创建自己的数据库助手类

时间:2013-12-17 05:09:51

标签: android database sqlite

您好我是Android的新手,请各位帮我们如何创建一个处理数据库的类。

5 个答案:

答案 0 :(得分:2)

你必须在你的src包中创建一个jav文件并扩展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 :(得分: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);

    }

}

答案 2 :(得分: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();
    }
}

}

答案 3 :(得分:0)

你可以在这里找到一个快速简单的教程..

herehere also

答案 4 :(得分:0)

如果您可以按照Android文档本身进行操作,那将会非常棒,因为它会以标准的代码编写方式为您提供支持...

查看http://developer.android.com/training/basics/data-storage/databases.html