SQLite database ..onCreate() is not being called - java

Kohli.java
package com.kohli;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.content.Context;
public class KohlifActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("KOHLIActivity", "qwert11111111");
setContentView(R.layout.main);
Log.i("KOHILActivity", "qwert22222222222");
DbHelper1 DbHelper=new DbHelper1(this) ;
Log.i("KOHLIfActivity", "qwert3333333333");
}
}
DbHelper1.java
package com.kohli;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.util.Log;
public class DbHelper1 extends SQLiteOpenHelper
{
static final String TAG = "DbHelper1";
static final String DB_NAME = "timeline.db";
static final int DB_VERSION = 1;
static final String TABLE = "timeline";
static final String C_ID = BaseColumns._ID;
static final String C_CREATED_AT = "created_at";
static final String C_SOURCE = "source";
static final String C_TEXT = "txt";
static final String C_USER = "user";
Context context;
public DbHelper1(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.context = context;
Log.d(TAG, "constructor111111");
//System.out.println("dbhelper constructor");
}
// Called only once, first time the DB is created
public void onCreate(SQLiteDatabase db) {
String sql = "create table " + TABLE + " (" + C_ID + " int primary key, "
+ C_CREATED_AT + " int, " + C_USER + " text, " + C_TEXT + " text)";
db.execSQL(sql);
Log.d(TAG, "onCreated sql:22222222 ");
//System.out.println("dbhelper oncreate");
}
// Called whenever newVersion != oldVersion
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Typically do ALTER TABLE statements, but...we're just in development,
// so:
db.execSQL("drop table if exists " + TABLE); // drops the old database
Log.d(TAG, "onUpdated 33333333");
//System.out.println("dbhelper onupgrade");
onCreate(db); // run onCreate to get new database
}
}
i wrote the following code to make a database with a table... the output at logcat is :: qwert111111 qwert22222 constructor111111 qwert3333 .. that is the oncreate function is not being called so the database is also not created...

The database isn't actually created until you call getWritableDatabase() on the
dbHelper object.

Related

Building Database and outputting data in Android

I've built a database class in Android using SQLite, so far it just creates a database and inputs data, however the only log report I see is that the data has been input, but the log never shows for the database creation.
I have also seen people have a .db file in their assets folder, mine is not created.
so:
1) How come it's not showing the log error for building the database, and also is there meant to be a .db file created through SQLite? It's my first time using it.
2) If it is creating, how can I call the List from the getData() method and output it in MainActivity? I've tried using intents but once I realised I wasn't getting the log report from the database creation so I need that sorted before anything.
MainActivity.java
public class MainActivity extends Activity {
Intent appIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DB db = new DB(this);
db.insertStudent("T", "T", 5, "T", "T", "T");
List<tableStudents> outputList = db.getData();
}
DB.java
package com.example.project;
import java.util.ArrayList;
import java.util.List;
import com.example.project.tableStudents.tableColumns;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.view.View;
public class DB extends SQLiteOpenHelper {
public static final int db_version = 1;
public static final String Table = "Students";
public static final String Student_ID = "Student_ID";
public static final String Student_Name = "Student_Name";
public static final String Student_Password = "Student_Password";
public static final String Student_Gender = "gender";
public static final String Student_Age = "age";
public static final String Student_Course = "course";
public static final String Modules = "modules";
public DB(Context context) {
super(context, tableColumns.Database, null, db_version);
}
#Override
public void onCreate(SQLiteDatabase db) {
//Create Table
db.execSQL("CREATE TABLE " + Table + "(" +
Student_ID + " INTEGER PRIMARY KEY, " +
Student_Name + " TEXT, " +
Student_Password + " TEXT, " +
Student_Gender + " TEXT, " +
Student_Age + " INTEGER, " +
Student_Course + " TEXT, " +
Modules + "TEXT");
Log.d("DB", "DB Created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + Table);
onCreate(db);
}
public List<tableStudents> getData() {
List<tableStudents> studentList = new ArrayList<tableStudents>();
// Select All Query
String selectQuery = "SELECT * FROM " + Table;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
tableStudents student = new tableStudents();
student.name = cursor.getString(0);
student.gender = cursor.getString(1);
student.age = Integer.parseInt(cursor.getString(2));
student.password = cursor.getString(3);
student.course = cursor.getString(4);
student.modules = cursor.getString(5);
studentList.add(student);
} while (cursor.moveToNext());
}
// return contact list
return studentList;
}
public boolean insertStudent(String name, String gender, int age, String password, String course, String modules) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Student_Name, name);
contentValues.put(Student_Gender, gender);
contentValues.put(Student_Age, age);
contentValues.put(Student_Password, password);
contentValues.put(Student_Course, course);
contentValues.put(Modules, modules);
//Log for admin insert
Log.d("DB", "Inserted Successfully");
return true;
}
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Matt Murphy please go through this link for each detail for your project
http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/.

_id Column is said not to exist even after I have included it into the create table statement [duplicate]

This question already has answers here:
When does SQLiteOpenHelper onCreate() / onUpgrade() run?
(15 answers)
Closed 7 years ago.
I am trying to populate a listview from a database. When I try to use a cursor to do it I get an error:
android.database.sqlite.SQLiteException: no such column: _id (code 1): , while compiling: SELECT _id FROM contacts WHERE _id ORDER BY name DESC
Here is my code:
MainActivity.java
package com.boggs.barr.barrboggscontactlist;
import android.content.ContentValues;
import android.content.Loader;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
populateListView();
}
public static final String KEY_ID = "_id";
private void populateListView() {
String[] projection = {
KEY_ID
};
FeedReaderDbHelper mDbHelper = new FeedReaderDbHelper(getApplicationContext());
SQLiteDatabase db = mDbHelper.getWritableDatabase();
String sortOrder =
FeedReaderContract.FeedEntry.COLUMN_NAME_NAME + " DESC";
Cursor cursor = db.query(
FeedReaderContract.FeedEntry.TABLE_NAME, // The table to query
projection, // The columns to return
KEY_ID, // The columns for the WHERE clause
null, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
String[] fromColumns = new String[] {FeedReaderContract.FeedEntry.COLUMN_NAME_NAME, FeedReaderContract.FeedEntry.COLUMN_NAME_PHONE};
int[] toViews = {R.id.name, R.id.phone};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.name_and_number, cursor, fromColumns, toViews, 0);
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
FeedReaderDbHelper.java
package com.boggs.barr.barrboggscontactlist;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.sql.RowId;
/**
* Created by adnroid developer site
*/
public class FeedReaderDbHelper extends SQLiteOpenHelper {
// If you change the database schema, you must increment the database version.
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "FeedReader.db";
public static final String LONG_TYPE = " Long";
public static final String STRING_TYPE = " STRING";
public static final String BYTE_TYPE = " BYTE";
private static final String COMMA_SEP = ",";
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + FeedReaderContract.FeedEntry.TABLE_NAME + " (" +
FeedReaderContract.FeedEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
FeedReaderContract.FeedEntry.COLUMN_NAME_PICTURE + STRING_TYPE + COMMA_SEP +
FeedReaderContract.FeedEntry.COLUMN_NAME_NAME + STRING_TYPE + COMMA_SEP +
FeedReaderContract.FeedEntry.COLUMN_NAME_EMAIL + STRING_TYPE + COMMA_SEP +
FeedReaderContract.FeedEntry.COLUMN_NAME_PHONE + STRING_TYPE +
")";
private static final String SQL_DELETE_ENTRIES =
"DROP TABLE IF EXISTS " + FeedReaderContract.FeedEntry.TABLE_NAME;
public FeedReaderDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_ENTRIES);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// This database is only a cache for online data, so its upgrade policy is
// to simply to discard the data and start over
db.execSQL(SQL_DELETE_ENTRIES);
onCreate(db);
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onUpgrade(db, oldVersion, newVersion);
}
}
FeedReaderContract.java
package com.boggs.barr.barrboggscontactlist;
import android.provider.BaseColumns;
import android.support.annotation.Nullable;
/**
* Created by android developer site.
* attempted to do database ran out of time
*/
public final class FeedReaderContract {
// To prevent someone from accidentally instantiating the contract class,
// give it an empty constructor.
public FeedReaderContract() {}
/* Inner class that defines the table contents */
public static abstract class FeedEntry implements BaseColumns {
public static final String TABLE_NAME = "contacts";
public static final String _ID = "_id";
public static final String COLUMN_NAME_PICTURE = "picture";
public static final String COLUMN_NAME_NAME = "name";
public static final String COLUMN_NAME_EMAIL = "email";
public static final String COLUMN_NAME_PHONE = "phone";
public static final Nullable COLUMN_NAME_NULLABLE = null;
}
}
Ive read that I need to pass the ID to the cursor? But I am not sure what that means. To me it should work since I am include the ID in the list of columns to include in the cursor. Any help is appreciated!
Edit: I asked this because people that had the same problem were proposed solutions that did not work for me. They kept suggesting to try and use RowId or .moveToFirst to include the ID. Laalto was proposed a solution that worked for me.
As user laalto pointed out, I needed to uninstall the app from the emulator because I made a schema change. Once I did that, the app started working.

Android SQLite data inserting

I am creating an android application that has two databases. One is offline SQLite database directly on the device and another one on public server that is used for update the offline one.
This is the way I'm inserting data into my SQLite database:
My activity:
package com.empekapp;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class Linie extends Activity {
DBAdapter db
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.linie);
openDB();
}
private void openDB(){
db = new DBAdapter(this);
db.open();
db.insertLineRecord("1");
db.insertLineRecord("2");
}
And in my database adapter:
public static final String KEY_LINE_ROWID = "_id";
public static final String KEY_LINE_NAME = "line_name";
public static final int COL_LINE_ROWID = 0;
public static final int COL_LINE_NAME = 1;
public static final String[] ALL_LINE_KEYS = new String[] {KEY_LINE_ROWID, KEY_LINE_NAME};
private static final String TABLE_LINE = "lines";
private static final String TABLE_LINE_CREATE =
"create table if not exists " + TABLE_LINE + "("
+ KEY_LINE_ROWID + " integer primary key autoincrement, "
+ KEY_LINE_NAME + " VARCHAR not null unique);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter (Context ctx){
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper{
DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE_LINE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LINE);
}
}
public DBAdapter open(){
db = DBHelper.getWritableDatabase();
return this;
}
public void close(){
DBHelper.close();
}
public void insertLineRecord(String line_name){
db.execSQL("INSERT OR IGNORE INTO " + TABLE_LINE + "('"
+ KEY_LINE_NAME + "') VALUES ('"
+ line_name + "');");
}
Generally this solution is enough for me.. but data is inserted to the table everytime I'm opening that activity to prevent this I set the unique constraint but how to insert data only once, when I'm creating that table to avoid situation like this?
use the data insertion in onCreate of database adapter class as this will be called only once when database created by this you can make it insert only once and no need to unique constaraint as well
Like this:
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE_LINE_CREATE);
db.insertLineRecord("1");
db.insertLineRecord("2");
}

SQLite NullPpointerException Error when trying to call a method

The aim is to retrieve the car park names from the car park tables columns 'CPNAME' and put those rows of names in another class' arraylist which a spinner will display.
The problem is apparently with my getCpNames() method, specifically on this line:
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_CPNAME, null, null, null,
null);
The errors I get on LogCat:
Caused by: java.lang.NullPointerException
at com.example.parkangel.DbHelper.getCpnames(DbHelper.java:93)
at com.example.parkangel.BookTicket.<init>(BookTicket.java:19)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)
at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2112)
My database class code:
package com.example.parkangel;
import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DbHelper extends SQLiteOpenHelper
{
private static DbHelper dbHelper;
private Context ourContext;
private static DbHelper instance;
private static SQLiteDatabase ourDatabase;
private static final String DATABASE_NAME = "CPDB.db";
private static final String DATABASE_TABLE = "CPTable";
private static final int DATABASE_VERSION = 1;
public static final String KEY_ID = "_id";
public static final String KEY_CPNAME = "cpname";
public static final String KEY_COST = "cost";
public DbHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
this.ourContext = context;
}
public static DbHelper getInstance(Context context)
{
if (instance == null)
{
instance = new DbHelper(context);
}
return instance;
}
#Override
public void onCreate(SQLiteDatabase db)
{
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_CPNAME + " TEXT NOT NULL, " + KEY_COST + " TEXT NOT NULL);");
db.execSQL("INSERT INTO " + DATABASE_TABLE + " Values ('1','Learning
Resource Center','2');");
db.execSQL("INSERT INTO " + DATABASE_TABLE + " Values ('2','Park and
Ride','1');");
db.execSQL("INSERT INTO " + DATABASE_TABLE + " Values ('3','de
Havilland Campus','2');");
db.execSQL("INSERT INTO " + DATABASE_TABLE + " Values ('4','Multi
Storey Building','2');");
db.execSQL("INSERT INTO " + DATABASE_TABLE + " Values
('5','Reception','2');");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
public synchronized DbHelper open() throws SQLException
{
System.out.println ("running open");
if(ourDatabase == null || !ourDatabase.isOpen());
this.ourDatabase = getWritableDatabase();
return this;
}
public static String[] getCpnames()
{
String[] columns = new String[] {KEY_ID, KEY_CPNAME, KEY_COST};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_CPNAME,
null, null, null, null);
ArrayList<String> list = new ArrayList<String>();
if (c != null)
{
c.moveToFirst();
do
{
list.add(c.getString(0));
}
while (c.moveToNext());
}
if (ourDatabase == null) System.out.println ("is null");
return list.toArray(new String[]{});
}
}
This is the class and arraylist I am calling getCpnames() into:
package com.example.parkangel;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
public class BookTicket extends Activity implements OnClickListener{
Spinner spinner, spinner2;
DbHelper dbhelper = DbHelper.getInstance(this);
String[] carParks = DbHelper.getCpnames();
I am beginner, so apologies for any amateur mistakes. Thank you in advance!
You never called DbHelper.open();
BTW, I also see a potential problem here
public synchronized DbHelper open() throws SQLException
{
System.out.println ("running open");
if(ourDatabase == null || !ourDatabase.isOpen());
this.ourDatabase = getWritableDatabase();
return this;
}
especially on this line
if(ourDatabase == null || !ourDatabase.isOpen());
The semicolon ";" at the end of line makes the if statement ineffective
The most likely explanation is that ourDatabase is null. You failed to call DBHelper.open() to set it.

I want to create a table but it gives me an error

This code is to create a new table.
import android.database.sqlite.SQLiteOpenHelper;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
public class MySQLHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "verlaufAufgaben.db";
public static final int DATABASE_VERSION = 1;
create the table
private static final String TABLE_CREATE_VERLAUF = ""
+"create table VERLAUF ("
+" ID integer primary key, "
+" Zahl1 int,) ";
public MySQLHelper(Context context)
{
super (context, DATABASE_NAME, null, DATABASE_VERSION);
}
create SQLiteDatabase
#Override
public void onCreate(SQLiteDatabase database)
{
database.execSQL(TABLE_CREATE_VERLAUF);
}
upgrade the database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(MySQLHelper.class.getName(),
"Upgrading database from version " + oldVersion + "to "
+ newVersion + ", which all destroy all old data");
db.execSQL("DROP TABLE IF EXISTS SCANITEM");
onCreate(db);
}
}
What's wrong in this code, it shows me an error because of the table?
you had the table create DDL ending with a comma...remove that!
private static final String TABLE_CREATE_VERLAUF = ""
+"create table VERLAUF ("
+" ID integer primary key, "
+" Zahl1 int) ";

Categories

Resources