Skip to content
Advertisement

How do I use SQLite in android?

I’ve founde already a few answers to this topic (for example this), but it is not working. I only get the warning, that it cannot resolve the method ‘openOrCreateDatabase(java.lang.String, int, null)’.

Here is my sourcecode:

public class DBHandler
{
    SQLiteDatabase database;
    DBHandler()
    {
        database = openOrCreateDatabase("DatabaseName", Context.MODE_PRIVATE, null);
    }
}

Advertisement

Answer

SQLite is a opensource SQL database that stores data to a text file on a device. Android comes in with built in SQLite database implementation.

Please check below links

  1. Android SQLite Database Tutorial

  2. SQLite Database Tutorial

  3. SQLite and Android

Structure

 public class MySQLiteHelper extends SQLiteOpenHelper {

  public static final String TABLE_COMMENTS = "comments";
  public static final String COLUMN_ID = "_id";
  public static final String COLUMN_COMMENT = "comment";

  private static final String DATABASE_NAME = "commments.db";
  private static final int DATABASE_VERSION = 1;

  // Database creation sql statement
  private static final String DATABASE_CREATE = "create table "
      + TABLE_COMMENTS + "(" + COLUMN_ID
      + " integer primary key autoincrement, " + COLUMN_COMMENT
      + " text not null);";

  public MySQLiteHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
  }

  @Override
  public void onCreate(SQLiteDatabase database) {
    database.execSQL(DATABASE_CREATE);
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    Log.w(MySQLiteHelper.class.getName(),
        "Upgrading database from version " + oldVersion + " to "
            + newVersion + ", which will destroy all old data");
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_COMMENTS);
    onCreate(db);
  }

} 

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement