I would like to ask anyone to please help me to modify my database connection code. What I have now is it's a part of one of my method class and it will make a connection every time I call it ( which I know its very inefficient). But when I try to move the connection part out from the method it breaks the code. I just wonder if I could make a static class somewhere so I can reuse it in other method as well.
Thanks so much for any help in advance, it is really appreciated.
Here is the method code:
public void getListDetail(){
//listDetailData.clear();
ShoppingListDatabase databaseConnection = new ShoppingListDatabase(this);
final SQLiteDatabase db = databaseConnection.open();
final ArrayList<ShoppingItem> lists = ShoppingListItemTable.selectAllItems(db, selectedID);
databaseConnection.close();
//create a list adapter and set adapter
ShoppingListItemAdapter adapter = new ShoppingListItemAdapter(this, R.layout.activity_item_detail_list, lists);
ListView_ListDetail = findViewById(R.id.ListView_ListDetail);
ListView_ListDetail.setAdapter(adapter);
adapter.notifyDataSetChanged();
// ((ArrayAdapter<String>)ListView_ListDetail.getAdapter()).notifyDataSetChanged();
}
Database class:
package com.puyakul.prin.psychic_shopping;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.ContactsContract;
import android.util.Log;
public class ShoppingListDatabase {
private static final String TAG = "ShoppingListDatabase";
private static final String DATABASE_NAME = "ShoppingListDatabase";
private static final int DATABASE_VERSION = 3;
private SQLiteDatabase mDb;
private DatabaseHelper mDbHealper;
private final Context mCtx;
public ShoppingListDatabase(Context ctx){
this.mCtx = ctx;
}
/**
* DatabaseHelper class.
*
* Database helper class to manage connections with the database.
*/
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.d(TAG, "DatabaseHelper onCreate");
db.execSQL(ShoppingListItemTable.CREATE_STATEMENT);
db.execSQL(ShoppingListTable.CREATE_STATEMENT);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d(TAG, "DatabaseHelper onUpgrade");
db.execSQL("DROP TABLE IF EXISTS " + ShoppingListItemTable.TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + ShoppingListTable.TABLE_NAME);
onCreate(db); //this will recreate the database as if it were new
}
}
public SQLiteDatabase open(){
mDbHealper = new DatabaseHelper(mCtx);
mDb = mDbHealper.getReadableDatabase();
return mDb;
}
public void close(){
mDb = null;
}
}
I have tried to declare variables within onCreate so I can use with other methods in the class like this
//================DATABASE CONNECTION=====================//
private ShoppingListDatabase databaseConnection;
private SQLiteDatabase db = databaseConnection.open();
private String selectedList;
private int selectedID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
setContentView(R.layout.activity_main_lists_detail);
ShoppingListDatabase databaseConnection = new ShoppingListDatabase(this);
SQLiteDatabase db = databaseConnection.open();
lists = ShoppingListItemTable.selectAllItems(db, selectedID);
and this is the error
Process: com.puyakul.prin.psychic_shopping, PID: 5635
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.puyakul.prin.psychic_shopping/com.puyakul.prin.psychic_shopping.MainListsDetail}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase com.puyakul.prin.psychic_shopping.ShoppingListDatabase.open()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2548)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase com.puyakul.prin.psychic_shopping.ShoppingListDatabase.open()' on a null object reference
at com.puyakul.prin.psychic_shopping.MainListsDetail.<init>(MainListsDetail.java:46)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2538)
Opening and closing the connection can be inefficient/costly so perhaps introduce/use the following :-
public SQLiteDatabase open(){
if (mDb == null) {
mDbHealper = new DatabaseHelper(mCtx);
mDb = mDbHealper.getReadableDatabase();
}
return mDb;
}
or alternately :-
public synchronized SQLiteDatabase open(){
if (mDb == null) {
mDbHealper = new DatabaseHelper(mCtx);
mDb = mDbHealper.getReadableDatabase();
}
return mDb;
}
and never call the close, except when the main activity is being destroyed. Then you will retrieve the one connection.
Here's some example uses based upon your ShoppingListDatabase class.
First a modified class with a few extra methods inside (addShoppingList, getAllShoppingListsAsCursor and logDBTables) and just a very simple shoppinglist table :-
public class ShoppingListDatabase {
private static final String TAG = "ShoppingListDatabase";
private static final String DATABASE_NAME = "ShoppingListDatabase";
private static final int DATABASE_VERSION = 3;
private static final String TBNAME = "shoppinglist";
public static final String COL_SHOPPINGLIST_NAME = "shoppinglist_name";
private SQLiteDatabase mDb;
private DatabaseHelper mDbHealper;
private final Context mCtx;
public ShoppingListDatabase(Context ctx){
this.mCtx = ctx;
}
/**
* DatabaseHelper class.
*
* Database helper class to manage connections with the database.
*/
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.d(TAG, "DatabaseHelper onCreate");
//db.execSQL(ShoppingListItemTable.CREATE_STATEMENT);
//db.execSQL(ShoppingListTable.CREATE_STATEMENT);
String crtsql = "CREATE TABLE If NOT EXISTS " + TBNAME + "(" +
COL_SHOPPINGLIST_NAME + " TEXT " +
")";
db.execSQL(crtsql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d(TAG, "DatabaseHelper onUpgrade");
//db.execSQL("DROP TABLE IF EXISTS " + ShoppingListItemTable.TABLE_NAME);
//db.execSQL("DROP TABLE IF EXISTS " + ShoppingListTable.TABLE_NAME);
onCreate(db); //this will recreate the database as if it were new
}
}
public synchronized SQLiteDatabase open(){
if (mDb == null) {
mDbHealper = new DatabaseHelper(mCtx);
mDb = mDbHealper.getReadableDatabase();
}
return mDb;
}
public void close(){
mDb = null;
}
public long addShoppingList(String name) {
ContentValues cv = new ContentValues();
cv.put(COL_SHOPPINGLIST_NAME,name);
return mDb.insert(TBNAME,null,cv);
}
public Cursor getAllShoppingListAsCursor() {
return mDb.query(TBNAME,
null,
null,
null,
null,null,
null
);
}
public void logDBTables() {
Cursor csr = mDb.query("sqlite_master",null,null,null,null,null,null);
while (csr.moveToNext()) {
Log.d(TAG,"Item " +
csr.getString(csr.getColumnIndex("name")) +
" was created using " +
csr.getString(csr.getColumnIndex("sql"))
);
}
}
}
Here's code from an Activity (that uses the Database connection in various ways) :-
public class MainActivity extends AppCompatActivity {
ShoppingListDatabase mSL;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSL = new ShoppingListDatabase(this);
mSL.open();
SO50312618();
SO50312618_other();
Cursor csr = mSL.getAllShoppingListAsCursor();
while(csr.moveToNext()) {
Log.d("SL INFO","Shopping List " + String.valueOf(csr.getPosition() + 1) +
" is " +
csr.getString(csr.getColumnIndex(ShoppingListDatabase.COL_SHOPPINGLIST_NAME))
);
}
}
private void SO50312618() {
ShoppingListDatabase databaseConnection = new ShoppingListDatabase(this);
SQLiteDatabase db = databaseConnection.open();
databaseConnection.logDBTables();
}
private void SO50312618_other() {
mSL.addShoppingList("List001");
mSL.addShoppingList("List002");
}
}
The results being :-
05-13 05:36:24.290 4245-4245/soanswers.soanswers D/ShoppingListDatabase: Item android_metadata was created using CREATE TABLE android_metadata (locale TEXT)
Item shoppinglist was created using CREATE TABLE shoppinglist(shoppinglist_name TEXT )
05-13 05:36:24.302 4245-4245/soanswers.soanswers D/SL INFO: Shopping List 1 is List001
Shopping List 2 is List002
All the various uses will use the same single connection.
Related
Hello as the title says I cannot get the app to construct a small local sqlite database. I would appreciate some help as I m an amateur. Thanks in advance.
Below there are some pictures of my source code.
I tested this code on level 24 API device, but the database does not appear in the data/data/the_package/databases/ folder
Edited to include code
MainActivity.java
public class MainActivity extends AppCompatActivity {
private CrdDBHelper mydb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mydb = new CrdDBHelper(this);
boolean p1 = true;
int p11sc = 0;
int p12sc = 0;
Button btnMenu = (Button) findViewById(R.id.btnMenu);
Button btntrue = (Button) findViewById(R.id.btnTrue);
Button btnFalse = (Button) findViewById(R.id.btnFalse);
// All other available code commented out
}
#Override
protected void onDestroy() {
mydb.close();
super.onDestroy();
}
}
CrdDBContract.java
public final class CrdDBContract {
private CrdDBContract(){}
public static final class GameEntry implements BaseColumns {
public static final String TABLE_NAME = "Game";
public static final String COLUMN_KNOWN = "Known";
public static final String COLUMN_TBF = "TBF";
public static final String SQL_CREATE_TABLE =
"CREATE TABLE " + TABLE_NAME + "("
+ _ID + " INTEGER PRIMARY KEY, "
+ COLUMN_KNOWN + " TEXT NOT NULL, "
+ COLUMN_TBF + " TEXT NOT NULL)";
}
}
CrdDBHelper.java
public class CrdDBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "CardGame.db";
public static final int DATABASE_VERSION = 1;
public CrdDBHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CrdDBContract.GameEntry.SQL_CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
CrdDBDataInsertion.java
public class CrdDBDataInsertion {
//??????????? Code not available from images
SQLiteDatabase mDB;
private void contentvalues(String Known, String TBF) {
ContentValues values = new ContentValues();
values.put(CrdDBContract.GameEntry.COLUMN_KNOWN,Known);
values.put(CrdDBContract.GameEntry.COLUMN_TBF,TBF);
long newid = mDB.insert(CrdDBContract.GameEntry.TABLE_NAME,null,values);
}
}
Main Activity part1Main Activity part2
Main Activity part3(final)
DB Contract class
DB Helper class
DB insert class part1
DB insert class part2 (final)
You aren't, according to the code, acessing(opening) the database. You are just instantiating the DatabseHelper in MainActivity i.e. mydb = new CrdDBHelper(this);
It is not until an attempt is made to open the database (which is frequently implicit) that the database is actually created.
A simple way would be to force an open when instantiating the database. e.g. call the getWritableDatabase() method in the constructor, like :-
public CrdDBHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
getWritableDatabase();
}
Perhaps at that time set an SQLiteDatabase object with the returned SQLiteDatabase, so your Database Helper (CrdDBHelper.java) could be :-
public class CrdDBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "CardGame.db";
public static final int DATABASE_VERSION = 1;
SQLiteDatabase mDB;
public CrdDBHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
mDB = this.getWriteableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CrdDBContract.GameEntry.SQL_CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
as the onCreate method is called when (and ONLY when) the database is created the Game table will then be created.
I want to acess the database and insert data into the SQLite database.To acess the database i try to instatiate the DBHelper class i created extending the SQLiteOpenHelper class. The constructor of the the DBHelperclass is :
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
So I try to intatiate the class using this code
DBHelper myDb = new DBHelper(getContext());
It gives error saying "cannot resolve method getContext();"when getContext() function used as the argument for constructor of the DBHelper class.
The DBHelper class is as follows:
package com.violator.it17250_test1.Database;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.violator.it17250_test1.UserProfile;
public class DBHelper extends SQLiteOpenHelper {
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + UserProfile.Users.TABLE_NAME + " (" +
UserProfile.Users.COLUMN_NAME_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
UserProfile.Users.COLUMN_NAME_USERNAME + " TEXT," +
UserProfile.Users.COLUMN_NAME_DOB + " TEXT, " +
UserProfile.Users.COLUMN_NAME_GENDER + "TEXT )";
private static final String SQL_DELETE_ENTRIES =
"DROP TABLE IF EXISTS " + UserProfile.Users.TABLE_NAME;
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "users1.db";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
DBHelper myDb = new DBHelper(getContext());
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_ENTRIES);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(SQL_DELETE_ENTRIES);
onCreate(db);
}
public void addInfo(){
// Gets the data repository in write mode
SQLiteDatabase db = myDb.getWritableDatabase();
}
}
getContext() is a method of the View class so you can use it like:
DBHelper myDb = new DBHelper(view.getContext());
where view is some View.
If you want to instantiate the class inside an activity class you could use:
DBHelper myDb = new DBHelper(this);
or
DBHelper myDb = new DBHelper(getApplicationContext());
I am creating an android application that will be using a SQLite database. I have created a separate class called DBAdapter that holds all the methods relating to the database.
My issue comes when I try to access these methods from the main activity. I am still learning but I would normally instantiate the DBAdapter class and then I would be able to reference the methods. However the approach I am taking isnt working. Below is the single line of how I am trying to instantiate the class and under that is the rest of the class.
The error I am getting is cannot resolve method 'open()'
Instantiate Line and method
DBAdapter db = new DBAdapter(this);
db.open();
Main Class
import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.ContentFrameLayout;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
final Context context = this;
private FloatingActionButton fab;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DBAdapter db = new DBAdapter(this);
db.open();
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.dialog_box);
dialog.setTitle("Add new Location!");
dialog.show();
final EditText NameEdit = (EditText) findViewById(R.id.NameInput);
final EditText LatEdit = (EditText) findViewById(R.id.LatInput);
final EditText LongEdit = (EditText) findViewById(R.id.LongInput);
final EditText PhoneEdit = (EditText) findViewById(R.id.PhoneInput);
final Button OkButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
final Button CancelButton = (Button) dialog.findViewById(R.id.dialogButtonCancel);
OkButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String RealName = NameEdit.getText().toString();
String Lat = LatEdit.getText().toString();
Float realLat = Float.parseFloat(Lat);
String Long = LongEdit.getText().toString();
Float realLong = Float.parseFloat(Long);
String Phone = PhoneEdit.getText().toString();
Double realPhone = Double.parseDouble(Phone);
//Use above to create a new Geofence
}
});
CancelButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
}
});
}
}
DBAdpater Class
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* Created by Rory on 09/09/2016.
*/
public class DBAdapter {
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
//Database Version & name
private static final String DATABASE_NAME = "OpenSesame";
private static final int DATABASE_VERSION = 1;
private static final String TAG = "DBMain";
private static final String GEOTABLE = "geoTable";
private static final String KEY_ID = "_id";
private static final String KEY_NAME = "name";
private static final String KEY_LAT = "lat";
private static final String KEY_LONG = "long";
private static final String KEY_RADIUS = "radius";
private static final String KEY_PHONE = "phone";
private static final String CREATE_GEO_TABLE = "CREATE TABLE "
+ GEOTABLE + "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTO INCREMENT,"
+ KEY_NAME + " TEXT,"
+ KEY_LAT + " FLOAT,"
+ KEY_LONG + " FLOAT,"
+ KEY_RADIUS + " INTEGER,"
+ KEY_PHONE + " INTEGER" + ")";
public DBAdapter(Context ctx) {
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
/**
* Method to create each of the tables defined above
* #param db
*/
#Override
public void onCreate(SQLiteDatabase db)
{
try {
db.execSQL(CREATE_GEO_TABLE);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Method for updating the database
* #param db
* #param newVersion
* #param oldVersion
*/
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
public DatabaseHelper open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
public void close() {
DBHelper.close();
}
public Cursor DeleteGeo(String name) {
return db.rawQuery("delete from geoTable where name = " + name, null);
}
public long AddGeo(String name, float lat, float lon, double phone, int radius) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_LAT, lat);
initialValues.put(KEY_LONG, lon);
initialValues.put(KEY_PHONE, phone);
initialValues.put(KEY_RADIUS, radius);
return db.insert(GEOTABLE, null, initialValues);
}
public Cursor GetAllGeos() {
return db.rawQuery("select * from geoTable order by name ASC", null);
}
}
}
Your DBAdapter class does not have the open() method. It is the private inner class DatabaseHelper that has that method. You have two options to expose open() to be able to call it the way you are expecting.
Option 1: add an open() method to DBAdapter that calls DatabaseHelper's open() method
public void open() {
DBHelper.open();
}
Option 2: remove DatabaseHelper entirely, and have DBAdapter extends SQLiteOpenHelper instead
public class DBAdapter extends SQLiteOpenHelper {
...
public DBAdapter(Context ctx) {
this.context = ctx;
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// add all the code from inside DatabaseHelper below
/**
* Method to create each of the tables defined above
* #param db
*/
#Override
public void onCreate(SQLiteDatabase db)
{
try {
db.execSQL(CREATE_GEO_TABLE);
} catch (SQLException e) {
e.printStackTrace();
}
}
// you will have to change this method to work
public DBAdapter open() throws SQLException
{
db = getWritableDatabase();
return this;
}
...
}
I'm getting this error of being unable to find the table.
I tried the solutions found through surfing like erasing the database in the emulator, but it didn't work.
I think it is related to reading a database from a different class, but I don't know how to manage this.
p.s. I'm currently using the sample provided by Android Studio 'SlidingTabsBasic'
SlidingTabsBasicFragment.java
public class SlidingTabsBasicFragment extends Fragment {
static final String LOG_TAG = "SlidingTabsBasicFragment";
final String[] genre = {"고전문학", "b", "c", "d", "e","f","g","h","i","j" };
String[] genre1;
final String[] genre2 = {"...","3","4","5"};
SQLiteDatabase db;
MySQLiteOpenHelper helper;
...
class SamplePagerAdapter extends PagerAdapter {
...
public Object instantiateItem(ViewGroup container, int position) {
helper = new MySQLiteOpenHelper(getActivity(), MainActivity.DATABASE_NAME, null, MainActivity.DATABASE_VERSION);
db = helper.getWritableDatabase();
String sql_genre1 = "select name from " + MySQLiteOpenHelper.DATABASE_TABLE_NAME +
"";
Cursor cursor_genre1 = db.rawQuery(sql_genre1,null); // where problem occurs
if (cursor_genre1!=null){
int count_genre1 = cursor_genre1.getCount();
String[] temparray_genre1 = new String[count_genre1+1];
temparray_genre1[0]="...";
for (int i=1; i<=count_genre1 ; i++){
temparray_genre1[i] = cursor_genre1.getString(0);
cursor_genre1.moveToNext();
}
genre1 = temparray_genre1;
}
...
MySQLiteOpenHelper.java
package com.example.android.slidingtabsbasic;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class MySQLiteOpenHelper extends SQLiteOpenHelper {
final static public String DATABASE_TABLE_NAME = "LDB";
public MySQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
createTable(db);
insertData(db);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String sql = "drop table if exists database";
db.execSQL(sql);
onCreate(db);
}
public void createTable(SQLiteDatabase db) {
String sql ="create table " + DATABASE_TABLE_NAME
+ "(name text,"
+ "author text,"
+ "genre text,"
+ "isBookmarked integer)";
db.execSQL(sql);
}
public void insertData(SQLiteDatabase db) {
db.beginTransaction();
insertintoLDB(db,"공무도하가", "작자미상", "고대가요");
insertintoLDB(db,"구지가","작자미상","고대가요");
insertintoLDB(db,"해가","작자미상","고대가요");
insertintoLDB(db,"정읍사","작자미상","고대가요");
insertintoLDB(db,"황조가","유리왕","고대가요");
db.endTransaction();
}
public void insertintoLDB(SQLiteDatabase db, String name, String author, String genre){
String sql = "insert into " + DATABASE_TABLE_NAME + "(name, author, genre, isBookmarked) "
+"values('"+ name + "','" + author + "','" + genre + "',0)";
db.execSQL(sql);
}
}
MainActivity.java
public class MainActivity extends SampleActivityBase {
public static final String TAG = "MainActivity";
public static final int DATABASE_VERSION = 2;
public static final String DATABASE_NAME = "LiteratureDatabase.db";
SQLiteDatabase db;
MySQLiteOpenHelper helper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createDatabase();
if (savedInstanceState == null) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
SlidingTabsBasicFragment fragment = new SlidingTabsBasicFragment();
transaction.replace(R.id.sample_content_fragment, fragment);
transaction.commit();
}
}
public void createDatabase() {
helper = new MySQLiteOpenHelper(this, DATABASE_NAME, null, DATABASE_VERSION);
db = helper.getWritableDatabase();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
}
Logcat
07-23 08:50:24.075 27205-27205/com.example.android.slidingtabsbasic E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.android.slidingtabsbasic, PID: 27205
android.database.sqlite.SQLiteException: no such table: LDB (code 1): , while compiling: select name from LDB
There is an older version of the database on your device, which does have the (empty) database in place, but not the books table. If that's an option for you, just uninstall and reinstall the app.
I read several tutorials and the sqlite section in a book and applied it which works great. Now I messed with it to try and understand it but now it will just force close every single time and i'm not sure why. I've been over my code again and again but maybe I can't find the problem because i'm new to sqlite/databases in general. Any help would be appreciated:
public class Events extends Activity {
private TextView tv;
private DataHelper dh;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tv = new TextView(this);
dh = new DataHelper(this);
dh.deleteAll();
//dh.addEvent("James");
//Cursor c = dh.getEvent();
//startManagingCursor(c);
//tv.setText(dh.showEvent(c));
setContentView(tv);
}
}
public class EventsData extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "events.db";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE = "CREATE TABLE" + TABLE_NAME + "(" + TITLE + " TEXT)";
private static final String DATABASE_UPGRADE = "DROP TABLE IF EXISTS " + TABLE_NAME;
public EventsData(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL(DATABASE_UPGRADE);
onCreate(db);
}
}
public class DataHelper {
private Context context;
private SQLiteDatabase db;
private EventsData eventsData;
public DataHelper(Context context) {
this.context = context;
eventsData = new EventsData(this.context);
}
public void addEvent(String name) {
db = eventsData.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(TITLE, name);
db.insertOrThrow(TABLE_NAME, null, cv);
}
}
Commenting out addEvent() will run the app fine but once I uncomment it, it force closes.
Fast shot: There's no space after CREATE TABLE.
You can check the logcat for the error message. It will tell you what is causing the force close. Link to debugging using logcat Debugging in Android using Eclipse