Create SQLite database in android
Better example is here
try {
myDB = this.openOrCreateDatabase("DatabaseName", MODE_PRIVATE, null);
/* Create a Table in the Database. */
myDB.execSQL("CREATE TABLE IF NOT EXISTS "
+ TableName
+ " (Field1 VARCHAR, Field2 INT(3));");
/* Insert data to a Table*/
myDB.execSQL("INSERT INTO "
+ TableName
+ " (Field1, Field2)"
+ " VALUES ('Saranga', 22);");
/*retrieve data from database */
Cursor c = myDB.rawQuery("SELECT * FROM " + TableName , null);
int Column1 = c.getColumnIndex("Field1");
int Column2 = c.getColumnIndex("Field2");
// Check if our result was valid.
c.moveToFirst();
if (c != null) {
// Loop through all Results
do {
String Name = c.getString(Column1);
int Age = c.getInt(Column2);
Data =Data +Name+"/"+Age+"\n";
}while(c.moveToNext());
}
Fails to create database in Android sqlite
Seems like you're missing databases
folder. Try:
public static void CreateDb(String dbPath){
File f = new File(dbPath);
f.getParentFile().mkdirs();
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbPath, null);
// ...
}
how to create simple SQLite database in android with cursor adaptor?
I developed a sample project which i used in my main application. I hope that helps you too.
DataBaseHandler.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
public class DataBaseHandler extends SQLiteOpenHelper {
public String BooksTable="Books";
public String Book_Id="id";
public String BookAuther="BookAuther";
public String BookTitle="BookTitle";
private final int DB_Version=1;
public DataBaseHandler(Context context,String DBName,int DBVersion){
super(context, DBName,null,DBVersion);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("Create Table " + BooksTable + "(" + Book_Id + " INTEGER PRIMARY KEY, " + BookAuther + " Text, " + BookTitle + " Text);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void addBook(Book book){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(Book_Id,book.getId());
cv.put(BookAuther,book.getAuthor());
cv.put(BookTitle,book.getTitle());
db.insert(BooksTable, null, cv);
db.close();
}
public ArrayList<Book> fetchAllBooks(){
ArrayList<Book> booksList = new ArrayList<Book>();
SQLiteDatabase db=this.getReadableDatabase();
Cursor c= db.query(BooksTable, null, null, null, null, null, null);
c.moveToFirst();
while (!c.isAfterLast()){
Book book = new Book();
book.setId(c.getInt(0));
book.setAuthor(c.getString(1));
book.setTitle(c.getString(2));
booksList.add(book);
c.moveToNext();
}
db.close();
return booksList;
}
}
Book.java
public class Book {
private int id;
private String author;
private String title;
public void setId(int id) {
this.id = id;
}
public void setAuthor(String author) {
this.author = author;
}
public void setTitle(String title) {
this.title = title;
}
public int getId() {
return id;
}
public String getAuthor() {
return author;
}
public String getTitle() {
return title;
}
}
MainActivity.java
DataBaseHandler db=new DataBaseHandler(getApplicationContext(),"DB_Name",1);
Book book=new Book();
book.setId(1);
book.setTitle("My Title");
book.setAuthor("Name of Author");
db.addBook(book);
How to create a new Table in SQLite database from android app
In the second instance you are using db.rawQuery
instead of db.execSQL
. That's why the table is not created.
Regarding the second question: Android creates the android_metadata
table to keep track of the current database version and past updates. The sqlite_sequence
table is for managing PRIMARY KEY AUTOINCREMENT
fields (it stores the highest available number). This is normal and they always have the same name (I believe..), just remove them from your list.
creating sqlite database on device using AndroidStudio
Try this and let me know if it creates the file there
public class DatabaseHelper extends SQLiteOpenHelper
{
public DatabaseHelper(Context context)
{
super(context, context.getExternalFilesDir("MyDatabase") + "/" + DATABASE_NAME, null, DATABASE_VERSION);
}
or you can try this too if want to use internal memory , as its more secure
public class DatabaseHelper extends SQLiteOpenHelper
{
public DatabaseHelper(Context context)
{
super(context, context.getFilesDir() + "/" + DATABASE_NAME, null, DATABASE_VERSION);
}
Update 1: Try Using this
public DatabaseHelper(final Context context) {
super(context, Environment.getExternalStorageDirectory()
+ File.separator + FILE_DIR
+ File.separator + DATABASE_NAME, null, DATABASE_VERSION);
}
How to create SQLite database in android
There are some syntax problems in your code that I will point out but fixing them doesn't guarantee your app works, you still need to read Logcat for further information:
1- db.execSQL("create table " + TABLE_NAME+" ("+ COL_1 +" INTEGER PRIMARY KEY AUTOINCREMENT, "+COL_2+" VARCHAR);");
(note the added spaces after "table" and before "(" and also using your columns constants instead of hard coded strings)
2- db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
(note for the added spaces after EXISTS)
Related Topics
(Deprecated) Fragment Onoptionsitemselected Not Being Called
App Always Starts Fresh from Root Activity Instead of Resuming Background State (Known Bug)
How to Capture Image from Custom Cameraview in Android
Difference Between Build.Gradle (Project) and Build.Gradle (Module)
How to Perform a Fade Animation on Activity Transition
How to Encrypt/Decrypt String in Android
Caused By: Java.Lang.Outofmemoryerror: Bitmap Size Exceeds Vm Budget
Rawquery(Query, Selectionargs)
How to Request Root Access in Android
How to Fix "Failed to Sync Vcpu Reg" Error
Interstitial Admob Ads: "Illegalstateexception: Only Fullscreen Activities Can Request Orientation"
How to Notify Users About an Android App Update
Android Mapview -Setting Zoom Automatically Until All Itemizedoverlay's Are Visible
Android How to Programmatically Hide Launcher Icon
How to Avoid Delay in Android Gcm Messages/Change Heartbeat
Android: How to Change the Actionbar "Home" Icon to Be Something Other Than the App Icon
How to Draw a Circle with Animation in Android with Circle Size Based on a Value