Can't get a database to be created - java

I'm trying to create a database but when I open the file explorer on the app there are no databases and there's no folder where the database should be, but that's probably because the database was never created. Below is my code. ny help is appreciated
DatabaseHelper.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Student.db";
public static final String TABLE_NAME = "student_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "NAME";
public static final String COL_3 = "I1Q1";
public static final String COL_4 = "I1Q2";
public static final String COL_5 = "I2Q1";
public static final String COL_6 = "I2Q2";
public static final String COL_7 = "I3Q1";
public static final String COL_8 = "I3Q2";
public static final String COL_9 = "I4Q1";
public static final String COL_10 = "I4Q2";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME +" (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,I1Q1 TEXT,I1Q2 TEXT,I2Q1 TEXT,I2Q2 TEXT,I3Q1 TEXT,I3Q2 TEXT,I4Q1 TEXT,I4Q2 TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
}
Main Activity.java
public class MainActivity extends AppCompatActivity {
DatabaseHelper myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb = new DatabaseHelper(this);
}
}

You have created the DatabaseHelper object in onCreate() but you have not used your SQLiteDatabase yet. That is why the database was never created.
Call myDb.getWrittableDatabase() in onCreate() and your database will be created after.

As Skemelio answered, you need to perform any task using the database for it to be actually created.
A nice advice is to use a ORM instead of writing all the code for the Database yourself.
I recommend using Room

Related

My application does not access/create my pre-populated database, instead it creates an empty database

I am making a quiz application. I've made a pre-populated database including questionNumber, subject, question, correctAnswer, wrongAnswer1, wrongAnswer2, and wrongAnswer3 as its columns (view the picture at the bottom). I was testing if querying a database will work, so I made a class called TestActivity with its corresponding XML file, "activity_test". I included one button and a textView. My objective is to query the database and show it inside the textView upon clicking the button. My problem is that in my DatabaseHelper class which extends with the SQLiteOpenHelper, creates an empty database instead of querying my pre-populated database. I don't know where I did wrong, but I highly suspect it's the CREATE_TABLE's fault. I might have made typos. I tried retyping and retyping the schema but still no records were shown in the textView.
In this test, I only tried to query the "wrongAnswers3" column because the database has too many records.
This is my "DatabaseAdapter" class
package com.example.quizalarm;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseAdapter {
static class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME="qasadb.db";
private static final String TABLE_NAME="qasaMultipleChoicequizdb";
private static final String QUESTION_NUMBER="questionNumber";
private static final String SUBJECT="subject";
private static final String QUESTION="question";
private static final String CORRECT_ANSWER="correctAnswer";
private static final String WRONG_ANSWER1="wrongAnswer1";
private static final String WRONG_ANSWER2="wrongAnswer2";
private static final String WRONG_ANSWER3="wrongAnswer3";
private static final String CREATE_TABLE="CREATE TABLE "+
TABLE_NAME+" ( "+
QUESTION_NUMBER+" INTEGER PRIMARY KEY AUTOINCREMENT, "+
SUBJECT+" TEXT, "+
QUESTION+" TEXT, "+
CORRECT_ANSWER+" TEXT, "+
WRONG_ANSWER1+" TEXT, " +
WRONG_ANSWER2+" TEXT, "+
WRONG_ANSWER3+" TEXT" +
")";
private static final String DROP_TABLE="DROP TABLE IF EXISTS "+TABLE_NAME;
private static final int DATABASE_VERSION=1;
private Context context;
//constructor
public DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
Message.message(context, "Constructor called");
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_TABLE);
Message.message(context, "onCreate was called");
} catch (SQLException e){
Message.message(context, ""+e);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
Message.message(context, "onUpgrade was called");
db.execSQL(DROP_TABLE);
onCreate(db);
} catch (SQLException e){
e.printStackTrace();
}
}
}
DatabaseHelper helper;
public DatabaseAdapter (Context context){
helper = new DatabaseHelper(context);
}
public String getData(){
SQLiteDatabase db=helper.getWritableDatabase();
//select necessary columns from table
String[] columns={DatabaseHelper.WRONG_ANSWER3};
Cursor cursor=db.query(DatabaseHelper.TABLE_NAME, columns, null, null, null, null, null);
StringBuffer sb=new StringBuffer();
while (cursor.moveToNext()){
String cWA3 = cursor.getString(6);
sb.append(cWA3);
}
return sb.toString();
}
}
This is my "TestActivity" class
package com.example.quizalarm;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class TestActivity extends AppCompatActivity {
DatabaseAdapter helper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
helper = new DatabaseAdapter(this);
}
public void viewDetails(View view){
TextView textShowData = findViewById(R.id.textShowData);
String data = helper.getData();
textShowData.setText(data);
}
}
Here's my pre-populated database:
the schema of its "qasaMultipleChoicequizdb" table is
CREATE TABLE "qasaMultipleChoicequizdb" (
"questionNumber" INTEGER PRIMARY KEY AUTOINCREMENT,
"subject" TEXT,
"question" TEXT,
"correctAnswer" TEXT,
"wrongAnswer1" TEXT,
"wrongAnswer2" TEXT,
"wrongAnswer3" TEXT
)
My reference to this code is from this playlist. Parts/videos 160-166).
For me, It's much easier to use SQLiteAssetHelper than SQLiteOpenHelper. You don't need to use the "CREATE TABLE" schema, You just need to add a certain dependency in the build.gradle (Module: app) to use this.
Here's the link: https://www.javahelps.com/2015/04/import-and-use-external-database-in.html.
Hope it helps :)

Android SQLiteOpenHelper is not working

The onCreate void of my SQLiteOpenHelper is not called even when get a database with "database = helper.getWritableDatabase();". I read lots of posts on this page here but I didn't find any solution that worked for me.
SQLiteOpenHelper:
package eu.michael1011.currencies.sql;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class Helper extends SQLiteOpenHelper {
public static final String database_name = "currencies.db";
public static final String col1 = "id";
public static final String col2 = "value";
public Helper(Context context) {
super(context, database_name, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.d("database", "started");
db.execSQL("create table EUR ("+col1+" TEXT, "+col2+" TEXT)");
Log.d("database", "finished");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("drop table if exists EUR");
onCreate(db);
}
}
I call it in my main activity like this:
helper = new Helper(getBaseContext());
database = helper.getWritableDatabase();

Getting Error when attempting to save to database

I'm a beginner with android studio, so I'm stumbling my way through building my first app. I've come up with and error when attempting to save my data to a database. Whenever I try to save any digits, the app crashes.
Database Java file:
package com.miahollins.basketballfinal;
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;
/**
* Created by pumpkin on 6/17/16.
*/
public class DataHandler {
public static final String GAMES = "games_played";
public static final String GAMES2 = "games_started";
public static final String GAMES3 = "points";
public static final String TABLE_NAME = "statstable";
public static final String DATA_BASE_NAME = "mydatabase.sqlite";
public static final int DATABASE_VERSION = 2;
public static final String TABLE_CREATE = "create table statstable (games_played VARCHAR not null, games_started VARCHAR not null, points VARCHAR not null)";
DatabaseHelper dbhelper;
Context ctx;
SQLiteDatabase db;
public DataHandler(Context ctx){
this.ctx = ctx;
dbhelper = new DatabaseHelper(ctx);
}
private static class DatabaseHelper extends SQLiteOpenHelper{
public DatabaseHelper(Context ctx){
super(ctx, DATA_BASE_NAME,null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(TABLE_CREATE);
} catch(SQLException e){
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS statstable");
onCreate(db);
}
}
public DataHandler open(){
db = dbhelper.getWritableDatabase();
return this;
}
public void close(){
dbhelper.close();
}
public long insertData(String games_played, String games_started, String points){
ContentValues content = new ContentValues();
content.put(GAMES, games_played);
content.put(GAMES2, games_started);
content.put(GAMES3, points);
return db.insertOrThrow(TABLE_NAME, null, content);
}
public Cursor returnData(){
return db.query(TABLE_NAME, new String[]{GAMES, GAMES2, GAMES3},null, null, null, null, null);
}
}
In my logcat I get an error saying that columns cannot be found. Any help is appreciated!

SQLite database is not creating

SQLite database is not creating.
I have used a method getwritabledatabase(); in main class, but only the log appears "Constructor is called" and then the application is closed.
Here is my code
table extends SQLiteOpenHelper class
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;
import java.sql.SQLDataException;
import java.sql.SQLException;
public class Table extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "Hammas's Database";
private static final String TABLE_NAME = "Hammas's Table";
private static final int DATABASE_VERSION = 1;
private static final String ID = "_id";
private static final String COLNAME = "Names";
private static final String CREATE_TABLE = "CREATE TABLE "+TABLE_NAME+" ("+ID+" INTEGER PRIMARY KEY AUTOINCREMENT,"+COLNAME+" VARCHAR(255));";
private static final String DROP_TABLE = "DROP TABLE IF EXIST "+TABLE_NAME+"";
private static final String TAG = "Hammas";
private Context context;
public Table(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
Message.message(context,"Constructor is called");
Log.i(TAG,"CONSTRUCTOR IS CALLED");
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
Message.message(context, "onCreate is called");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DROP_TABLE);
onCreate(db);
Message.message(context,"onUpgrade is called");
}
}
Message class is just for toast.
Here is mainClass
enter code here
public class MainActivity extends ActionBarActivity {
Table table;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view);
table = new Table(this);
SQLiteDatabase sql= table.getReadableDatabase();
}
This string can't be processed as is
private static final String TABLE_NAME = "Hammas's Table";
It needs to be modified as
private static final String TABLE_NAME = "[Hammas''s Table]";
Because
The apostrophe is a string delimiter, so it has to be doubled.
The space would break the table name, so it needs to be enclosed in square brackets ([]).
This is also true for column names.
To insert apostrophes in string values, it has to be doubled, too.
Check the file system to ensure:
//data/data/<Your-Application-Package-Name>/databases/Hammas's Database.db
is created and located there. It won't create again if it already exists.

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");
}

Categories

Resources