Creating a Database in Android - java

Okay so I've followed a few tutorials and created a databaseHelper class after following a tutorial. However I don't fully understand or get how to actually create the database in the first place.
In my mainActivity I've added this to my onCreate but it doesn't create any database or at least nothing shows up in my Android Device Monitor.
Basically how do I actually get the database to be created?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
sharedPreferences = getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
dbHelper = new databaseHelper(this);
}
Java
public class databaseHelper extends SQLiteOpenHelper {
static final String DATABASEHELPER = "DATABASE HELPER";
static final String dbName="chefs";
//User Table Fields
static final String userTable="user";
static final String userColID="userID";
static final String userColName="firstName";
static final String userColLast="lastName";
static final String userColDOB="DOB";
static final String userColGend="gender";
static final String userColAddr="address";
static final String userColPost="postcode";
static final String userColBio="bio";
static final String userColUser="username";
static final String userColEmail="email";
static final String userColPass="password";
static final String userColPic="picture";
static final String userColLastLog="lastlogin";
static final String userColLastLogIP="lastloginIP";
static final String userColRegisteredIP="registeredIP";
static final String userColCreatedOn="createdOn";
//Recipe Table Fields
static final String recipeTable="recipe";
static final String recipeColID="recipeID";
static final String recipeColName="name";
static final String recipeColCate="category";
static final String recipeColDesc="description";
static final String recipeColUserID="user_userID";
//Ingredient Table Fields
static final String ingredientTable="ingredient";
static final String ingredientColID="ingredientID";
static final String ingredientColRecipeID="recipe_recipeID";
static final String ingredientColName="name";
static final String ingredientColAmount="amount";
static final String ingredientColUnit="unit";
//Step Table Fields
static final String stepTable="step";
static final String stepColID="stepID";
static final String stepColRecipeID="recipe_recipeID";
static final String stepColNumber="stepNumber";
static final String stepColDesc="description";
public databaseHelper(Context context) {
super(context, dbName, null,1);
Log.d(DATABASEHELPER, "Database Created");
}
#Override
public void onCreate(SQLiteDatabase db) {
// Creating User Table
db.execSQL("CREATE TABLE "+userTable+" ("+userColID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+userColName+" TEXT, "+userColLast+" TEXT, "
+userColDOB+" NUMERIC, "+userColGend+" TEXT, "+userColAddr+" TEXT, "+userColPost+" TEXT, "+userColBio+" TEXT, "
+userColUser+" TEXT, "+userColEmail+" TEXT, "+userColPass+" TEXT, "+userColPic+" TEXT, "+userColLastLog+" NUMERIC, "
+userColLastLogIP+" TEXT, "+userColRegisteredIP+" TEXT, "+userColCreatedOn+" NUMERIC)");
// Creating Recipe Table
db.execSQL("CREATE TABLE "+recipeTable+" ("+recipeColID+" INTEGER AUTOINCREMENT, "+recipeColName+" INTEGER, "+recipeColCate+" TEXT, "
+recipeColDesc+" TEXT, "+recipeColUserID+" INTEGER");
// Creating Ingredient Table
db.execSQL("CREATE TABLE "+ingredientTable+" ("+ingredientColID+" INTEGER AUTOINCREMENT, "+ingredientColRecipeID+" TEXT ,"+ingredientColName+" TEXT, "
+ingredientColAmount+" INTEGER, "+ingredientColUnit+" TEXT");
db.execSQL("CREATE TABLE "+stepTable+" ("+stepColID+" INTEGER AUTOINCREMENT, "+stepColRecipeID+" INTEGER, "+stepColNumber+" INTEGER, "
+stepColDesc+" TEXT");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d(DATABASEHELPER, "Upgrading Database");
}
}
Any help is appreciated.

As given in the android documentation, the database is not actually created or opened until one of getWritableDatabase() or getReadableDatabase() is called.
Link: http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html

Related

Android - SQLite issue with adding more tables to database

First of all I created my prescription_table and that worked.
Then I tried to add a second table to the database called patient_table.
However I am getting this error "
Error Code : 1 (SQLITE_ERROR)
Caused By : SQL(query) error or missing database.
(no such table: patient_table (code 1): , while compiling: INSERT INTO patient_table(PPS,CARINGID,DOB,ADDRESS,SNAME,PATIENTTYPE,PATIENTMEDCON,FNAME) VALUES (?,?,?,?,?,?,?,?))
I tried changing the database version number from 1 to 2 however this made my app crash. I have also tried to uninstall the application from my android device however it is still giving me the same error.
Any help would be grateful.
package com.example.medicationmanagementsystem.DAO;
//code below is based on AndroidSQLite Tutorial Android CRUD Tutorial with SQLite (Create, Read, Update, Delete), ProgrammingKnowledge, https://www.youtube.com/watch?v=kDZES1wtKUY
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHelper extends SQLiteOpenHelper {
//Create Database
public static final String DATABASE_NAME = "ManagementSystem.db";
//Create patient table
public static final String TABLE_PATIENT = "patient_table";
public static final String COL_PATIENT_PATIENTID = "PATID";
public static final String COL_PATIENT_FNAME = "FNAME";
public static final String COL_PATIENT_SNAME = "SNAME";
public static final String COL_PATIENT_PPS = "PPS";
public static final String COL_PATIENT_DOB = "DOB";
public static final String COL_PATIENT_ADDRESS = "ADDRESS";
public static final String COL_PATIENT_TYPE = "PATIENTTYPE";
public static final String COL_PATIENT_MEDCOND = "PATIENTMEDCON";
public static final String COL_PATIENT_CARINGID = "CARINGID";
//Create prescription table
public static final String TABLE_PRESCRIPTION = "prescription_table";
public static final String COL_PRESCRIPTION_ID = "PRESCRIPTIONID";
public static final String COL_PRESCRIPTION__PATIENTID = "PATIENTID";
public static final String COL_PRESCRIPTION__DATE = "DATE";
public static final String COL_PRESCRIPTION__DRUGNAME = "DRUGNAME";
public static final String COL_PRESCRIPTION__CONCENTRATION = "CONCENTRATION";
public static final String COL_PRESCRIPTION__DOSAGE = "DOSAGE";
public static final String COL_PRESCRIPTION__PREPARATION = "PREPARATION";
public static final String COL_PRESCRIPTION__STARTDATE = "STARTDATE";
public static final String COL_PRESCRIPTION__ENDDATE = "ENDDATE";
public static final String COL_PRESCRIPTION__DOCTORID = "DOCTORID";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate (SQLiteDatabase db) {
String patienttable = "CREATE TABLE " + TABLE_PATIENT + "(PATID INTEGER PRIMARY KEY AUTOINCREMENT, FNAME TEXT, SNAME TEXT, PPS TEXT, DOB TEXT, ADDRESS TEXT, PATIENTTYPE TEXT, PATIENTMEDCON TEXT, CARINGID INTEGER)";
String prescriptiontable = "CREATE TABLE " + TABLE_PRESCRIPTION + "(PRESCRIPTIONID INTEGER PRIMARY KEY AUTOINCREMENT, PATIENTID INTEGER, DATE TEXT, DRUGNAME TEXT, CONCENTRATION TEXT, DOSAGE TEXT, PREPARATION TEXT, STARTDATE TEXT, ENDDATE TEXT, DOCTORID INTEGER)";
db.execSQL(patienttable);
db.execSQL(prescriptiontable);
this.getReadableDatabase();
this.getWritableDatabase();
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_PATIENT);
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_PRESCRIPTION);
onCreate(db);
}
//insert patient data
public boolean insertPatientData(String fname, String sname, String pps, String dob, String address, String patienttype, String patientmedcon, String caringid) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues1 = new ContentValues();
contentValues1.put(COL_PATIENT_FNAME, fname);
contentValues1.put(COL_PATIENT_SNAME, sname);
contentValues1.put(COL_PATIENT_PPS, pps);
contentValues1.put(COL_PATIENT_DOB, dob);
contentValues1.put(COL_PATIENT_ADDRESS, address);
contentValues1.put(COL_PATIENT_TYPE, patienttype);
contentValues1.put(COL_PATIENT_MEDCOND,patientmedcon);
contentValues1.put(COL_PATIENT_CARINGID, caringid);
long result= db.insert(TABLE_PATIENT,null, contentValues1);
if (result == 1)
return false;
else
return true;
}
//insert prescription data
public boolean insertData(String patientid, String date, String drugname, String concentration,String dosage, String preparation, String startdate, String enddate, String doctorid) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues2 = new ContentValues();
contentValues2.put(COL_PRESCRIPTION__PATIENTID, patientid);
contentValues2.put(COL_PRESCRIPTION__DATE, date);
contentValues2.put(COL_PRESCRIPTION__DRUGNAME, drugname);
contentValues2.put(COL_PRESCRIPTION__CONCENTRATION, concentration);
contentValues2.put(COL_PRESCRIPTION__DOSAGE, dosage);
contentValues2.put(COL_PRESCRIPTION__PREPARATION, preparation);
contentValues2.put(COL_PRESCRIPTION__STARTDATE, startdate);
contentValues2.put(COL_PRESCRIPTION__ENDDATE, enddate);
contentValues2.put(COL_PRESCRIPTION__DOCTORID, doctorid);
long result= db.insert(TABLE_PRESCRIPTION,null, contentValues2);
if (result == 1)
return false;
else
return true;
//END
}
//Coding with mitch tutorial
public Cursor getListContents() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM " + TABLE_PRESCRIPTION, null);
return data;
}
}
You should not be trying to open the database (using this.getReadableDatabase or this.getWritableDatabase) in the onCreate method as at this stage a getWritableDatabase is underway and as such you will get an java.lang.IllegalStateException: getDatabase called recursively.
That is when you get an instance of the DatabaseHelper, the database is not created or opened. It's not until you invoke getWritableDatabase (implicitly (e.g. via an insert) or explicitly) that an attempt is made to open the database and create it if it doesn't already exist. Thus calling get????ableDatabase will be a recursion since it is already getting the database.
I tried changing the database version number from 1 to 2 however this
made my app crash.
As onUpgrade is also invoked when getting the database, it calling onCreate also fails because of the recursion.
As such change the onCreate method to be :-
#Override
public void onCreate (SQLiteDatabase db) {
String patienttable = "CREATE TABLE " + TABLE_PATIENT + "(PATID INTEGER PRIMARY KEY AUTOINCREMENT, FNAME TEXT, SNAME TEXT, PPS TEXT, DOB TEXT, ADDRESS TEXT, PATIENTTYPE TEXT, PATIENTMEDCON TEXT, CARINGID INTEGER)";
String prescriptiontable = "CREATE TABLE " + TABLE_PRESCRIPTION + "(PRESCRIPTIONID INTEGER PRIMARY KEY AUTOINCREMENT, PATIENTID INTEGER, DATE TEXT, DRUGNAME TEXT, CONCENTRATION TEXT, DOSAGE TEXT, PREPARATION TEXT, STARTDATE TEXT, ENDDATE TEXT, DOCTORID INTEGER)";
db.execSQL(patienttable);
db.execSQL(prescriptiontable);
//this.getReadableDatabase(); //<<<<< MUST NOT BE USED In onCreate
//this.getWritableDatabase(); //<<<<< MUST NOT BE USED in onCreate
}
Of cousre you would likely delete the lines rather than comment them out.
Before running the App it would be best to uninstall the App (this should overcome the initial issue which is due to onCreate only being called once for the lifetime of the database).
As such, if you change the schema, when developing the App, you would typicaly delete the database (uninstalling the App or deleting the App's data will do this).
Making the amendments above to the onCreate method would also allow increasing the version number to work as it calls onCreat.
P.S. checking the return value from the insert for 1 will only return true for the very fist insert, as only at that stage is the return value (the rowid (PATID and PRESCRIPTIONID will be aliases of the rowid)), for subsquent inserts the value be will be greater than 1.
I'd suggest that instead of using :-
long result= db.insert(.........);
if (result == 1)
return false;
else
return true;
That you use :-
return (db.insert(......) > 0);
or
return (db.insert(......) != -1)
(-1 indicates that no row was inserted).
TESTING
The above has been tested using you Database helper with rows being succesfully inserted.
The following code in an activity was used for the test :-
public class MainActivity extends AppCompatActivity {
DatabaseHelper mDBHlpr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDBHlpr = new DatabaseHelper(this);
mDBHlpr.insertData("1234567890","2018-01-01","X","50","4 times daily","Shake","2018-01-01","2018-03-01","DOC001");
mDBHlpr.insertPatientData("Fred","Bloggs","pps001","1974-01-01","1 Somewhere Street","X","MECON001","001");
Cursor csr = mDBHlpr.getListContents();
while (csr.moveToNext()) {
Log.d("SCRIPTINFO","ID is " +csr.getString(csr.getColumnIndex(DatabaseHelper.COL_PRESCRIPTION_ID)));
}
csr = mDBHlpr.getWritableDatabase().query(DatabaseHelper.TABLE_PATIENT,null,null,null,null,null,null);
while (csr.moveToNext()) {
Log.d("PATIENTINFO","Patient Name is " + csr.getString(csr.getColumnIndex(DatabaseHelper.COL_PATIENT_FNAME)));
}
}
}
The result (from an initial run after uninstalling the App) was :-
2019-11-18 12:57:10.362 D/SCRIPTINFO: ID is 1
2019-11-18 12:57:10.363 D/PATIENTINFO: Patient Name isFred

Android - How to access already created database from other class?

Here is my SQLiteOpenHelper class :
public class MySQLiteHelper extends SQLiteOpenHelper {
...
//all the code
SQLiteDatabase db;
String url;
String title;
String init_price;
String cur_price;
byte[] image;
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "ProductsDB";
// Products table name
private static final String TABLE_NAME = "products";
// Products Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_URL = "url";
private static final String KEY_TITLE = "title";
private static final String KEY_INIT_PRICE = "init_price";
private static final String KEY_CUR_PRICE = "cur_price";
private static final String KEY_IMAGE = "image";
private static final String[] COLUMNS = {KEY_ID, KEY_URL, KEY_TITLE, KEY_INIT_PRICE,KEY_CUR_PRICE, KEY_IMAGE};
//An array of database
String[][] table = new String[10][5];
byte[][] images = new byte[10][1];
int len = 0; //no.of rows in the table
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
this.db = db;
// SQL statement to create a products table
String CREATE_PRODUCTS_TABLE = "CREATE TABLE " + TABLE_NAME + " ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"url TEXT, " +
"title TEXT, " +
"init_price TEXT," +
"cur_price TEXT," +
"image BLOB" +
" );";
// create products table
db.execSQL(CREATE_PRODUCTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
// Create tables again
onCreate(db);
}
void read() {
int i = 0;
// 1. build the query
String query = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
do {
table[i][0] = cursor.getString(0);
table[i][1] = cursor.getString(1);
table[i][2] = cursor.getString(2);
table[i][3] = cursor.getString(3);
table[i][4] = cursor.getString(4);
images[i] = cursor.getBlob(5);
i++;
} while (cursor.moveToNext());
}
}
String[][] getTable() {
return table;
}
}
My List class :
Here in this class, I want to create a listview from the values in the database.
How do I access those values?
List.java :
public class List extends Activity {
MySQLiteHelper obj = new MySQLiteHelper(this);
// I have all the methods to get required data from database.
// But I'm unable to call those methods directly. Why?
// I actually can access those methods from a service.
// But now, I'm getting "Cannot resolve method" error.
MySQLiteHelper obj = new MySQLiteHelper(this);
obj.getLength(); //I'm getting error here
obj.read(); // It says that it cannot resolve the method.
}
Why is that? I put the same code in a thread inside List.java class and then I'm able to access those methods.
MySQLiteHelper has no method for getLength() but that is ok. (more on this at the end)
the read() method is not public, and it really does nothing other than populate the table member/field of the MySQLiteHelper class.
You aren't leveraging the getTable() method you created (which also is not public).
lets go ahead and make getTable public (consider renaming this as it is really returning table data and not an actual database table, up to you tho), and anytime it is called, lets also call read() anytime this method is called
// renamed from getTable
public String[][] getTableData() {
read();
return table;
}
With this small modification, your usage should look something like this:
MySQLiteHelper obj = new MySQLiteHelper(this);
String[][] tabledata = obj.getTableData();
// get the Length (no getLength() method needed as we will poll the tabledata length property.
int length = tabledata.length;
I'm going to assume (and I apologize if I'm incorrect) that this your first crack at doing android databases. So it might be good to read a tutorial like this one:
http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/
HTHS :)

Android: Creating a Login/Register Screen using an SQLite database?

I want to add a Login/Register Activity at the start of my Application.
Can I do so using SQLite, I.e. with the help of a "DatabaseHelper" class?
I have already implemented a Database within my application using the DatabaseHelper class shown below that extends SQLiteOpenHelper
Can I just create another class like this, or extend the current one? If so, how would I do so?
Current class (note this is database for storing game scores etc):
public class DatabaseHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 10;
// Database Name
private final static String DATABASE_NAME = "MeditationDatabase";
// Contacts table name
private static final String TABLE_SCORE = "scores";
// Contacts Table Columns names
private static final String COL_SESSION = "sessionid";
private static final String COL_GAMETITLE = "game";
private static final String COL_NAME = "name";
private static final String COL_MED = "avgmeditation";
private static final String COL_MAX = "maxmeditation";
private static final String COL_AVGATT = "avgattention";
private static final String COL_MAXATT = "maxattention";
private static final String COL_SCORE = "score";
private static final String COL_DATE = "date";
/**
* Constructor
*
* #param context
*/
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
/**
* Method that creates the database
*/
#Override
public void onCreate(SQLiteDatabase db) {
//VERY IMPORTANT: ALWAYS CHECK THAT THERE ARE SPACES AND COMMAS IN CORRECT PLACE IN CODE BELOW:
String CREATE_TABLE_SCORE = "CREATE TABLE " + TABLE_SCORE + "(" + COL_SESSION
+ " STRING PRIMARY KEY, " + COL_GAMETITLE + " STRING, " + COL_NAME + " STRING, " + COL_MED + " INTEGER, "
+ COL_MAX + " INTEGER, " + COL_AVGATT + " INTEGER, " + COL_MAXATT + " INTEGER, " + COL_SCORE + " INTEGER, " + COL_DATE + " STRING " + ")";
db.execSQL(CREATE_TABLE_SCORE);
}
/**
* Method that upgrades the database
*/
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_SCORE);
// Create tables again
onCreate(db);
}
/**
* All CRUD operations
*/
// Adding new score details (Name, score, date)
void addScore(Score score) {
SQLiteDatabase db = this.getWritableDatabase();
// ContentValues- holds the values.
ContentValues values = new ContentValues();
values.put(COL_SESSION, score.getSessionID());
values.put(COL_GAMETITLE, score.getGameTitle());
values.put(COL_NAME, score.getName());
values.put(COL_MED, score.getMeditation());
values.put(COL_MAX, score.getMax());
values.put(COL_AVGATT, score.getAvgAttention());
values.put(COL_MAXATT, score.getMaxAttention());
values.put(COL_SCORE, score.getScore());
values.put(COL_DATE, score.getDate());
// Inserting Row (i.e. the values that were entered from above
db.insert(TABLE_SCORE, null, values);
db.close(); // Closing database connection
}
}
The better approach here is to inner class your helper. Then add method to your outer class to manipulate the data or whatever else like login or register!
public class DataAccsses {
public Boolean login(String username, String password){
}
public Boolean regester(//what ever needed here){
}
//other data manipulation method from your helper
class DatabaseHelper extends SQLiteOpenHelper {
//keep everything private. outer class can access inner class private members.
}
}
You only need one helper in your application (except rare conditions) So do not create another one. You can put as many as methods in your outer class DataAccess as needed to cover all the oprations on the database on all the tables.

Android SQLite errors while inserting records

I have tried many things and searched both SO and google, but this is an odd error. The error happens when I click a button which creates(inserts) a new level in the database.
Logcat follows:
http://pokit.org/get/?564ecab747237335f72006e8e3d5d633.jpg
There is more down but it's the same error.
And here is the code that does the insert. I'm using SQLiteAssetHelper by the way.
public void createLevel(Level lev){
ContentValues values = new ContentValues();
if(lev.getGameMode()=="SinglePlayer")
{
LevelSinglePlayer level=(LevelSinglePlayer)lev;
values.put(GAME_MODE_COLUMN, level.getGameMode());
values.put(DIFFICULTY_COLUMN, level.getDifficulty());
values.put(SINGLE_PLAYER_MODE_COLUMN, level.getSinglePlayerMode());
values.putNull(TIME_CHALLENGE_MODE_COLUMN);
values.put(POINTS_COLUMN, level.getPoints());
values.put(LIVES_COLUMN, level.getLives());
values.putNull(TIME_COLUMN);
values.put(SUFFIX_COLUMN, level.getSuffix());
values.put(SUFFIX_WORDS_COUNT_COLUMN, level.getSuffixWordsCount());
db.insert(LEVELS_TABLE, null, values);
Log.w("INSERT_NEW_LEVEL", "SUCCESSFUL INSERT");
}
else if(lev.getGameMode()=="TimeChallenge")
{
LevelTimeChallenge level= (LevelTimeChallenge)lev;
values.put(GAME_MODE_COLUMN, level.getGameMode());
values.put(DIFFICULTY_COLUMN, level.getDifficulty());
values.putNull(SINGLE_PLAYER_MODE_COLUMN);
values.put(TIME_CHALLENGE_MODE_COLUMN, level.getTimeChallengeMode());
values.put(POINTS_COLUMN, level.getPoints());
values.put(LIVES_COLUMN, level.getLives());
values.put(TIME_COLUMN, level.getTime());
values.put(SUFFIX_COLUMN, level.getSuffix());
values.put(SUFFIX_WORDS_COUNT_COLUMN, level.getSuffixWordsCount());
db.insert(LEVELS_TABLE, null, values);
Log.w("INSERT_NEW_LEVEL", "SUCCESSFUL INSERT");
}
}
I have three tables, created by the following statements:
CREATE TABLE IF NOT EXISTS words(_id INTEGER PRIMARY KEY, word TEXT, tezina INTEGER)
CREATE TABLE IF NOT EXISTS levels(_id INTEGER PRIMARY KEY, modIgre TEXT NOT NULL, tezina INTEGER NOT NULL, modSingle TEXT, modTime TEXT, targetpoints INTEGER, lives INTEGER, nastavak TEXT, brojRijeciNastavak INTEGER, locked BOOLEAN, earnedpoints INTEGER, kaladonts INTEGER, req2stars INTEGER, req3stars INTEGER)
CREATE TABLE IF NOT EXISTS highscores(_id INTEGER PRIMARY KEY, player TEXT, points INTEGER)
I can post anything needed quickly.
EDIT: Java consts
//konstante(nazivi tabela)
private static final String GAME_MODE_COLUMN = "modIgre";//mod igre - single, time
private static final String DIFFICULTY_COLUMN = "tezina";//tezina rijeci na levelu
private static final String SINGLE_PLAYER_MODE_COLUMN = "modSingle";//mod single playera
private static final String TIME_CHALLENGE_MODE_COLUMN = "modTime";//mod time challenga
private static final String POINTS_COLUMN = "points";
private static final String LIVES_COLUMN = "lives";//zivoti
private static final String TIME_COLUMN = "";//koliko vrijeme?
private static final String SUFFIX_COLUMN = "nastavak";//koji nastavak?
private static final String SUFFIX_WORDS_COUNT_COLUMN = "brojRijeciNastavak";//koliko
private static final String ID_COLUMN = "_id";
private static final String TARGET_POINTS_COLUMN = "targetpoints";
private static final String LOCKED_COLUMN = "locked";
private static final String KALADONTS_COLUMN = "kaladonts";
private static final String TWO_STARS_COLUMN = "req2stars";
private static final String THREE_STARS_COLUMN = "req3stars";
private static final String EARNED_POINTS_COLUMN = "earnedpoints";
private static final String LEVELS_TABLE = "levels";
Your TIME_COLUMN is an empty string, causing the invalid SQL to be created:
private static final String TIME_COLUMN = "";//koliko vrijeme?
You can replace it with your actual column name. Didn't see a suitable column in your CREATE TABLE so it's possible that you should remove the put(TIME_COLUMN) calls altogether.
There is extra ',' in ur query or u r forget to put first field in ur query so correct query is :
INSERT into levels(modIgre,modTime,modSingle,brojRijeciNastavak,nastavak,tezina,lives,points)Values(?,?,?,?,?,?,?,?)
Your primary Key seems to be null and values too.
INSERT into levels(,modIgre,modTime,modSingle,brojRijeciNastavak,nastavak,tezina,lives,points)Values(?,?,?,?,?,?,?,?)
it is a problem because you begin your query by ,.

How to run main in android

Hi all i am writing simple app to train my ContentProvider skills .So i wrote Contract class that specifies all the meta data for all the tale her it is
public class StoreContract {
public static String AUTHORITY = "com.ura.store.intentProvider";
public static String DATABASE_NAME = "Store.db";
public static class Customer{
public static final String TABLE_NAME ="tblCustomers";
public static final String COLUMN_AUTO_ID = "_id";
public static final String COLUMN_NAME="First Name";
public static final String COLUMN_LAST_NAME = "Last name";
public static final String COLUMN_PHONE_NUMBER = "Phone number";
public static final String CREAT_STRING = "create table "+TABLE_NAME+
" ( "+COLUMN_AUTO_ID+" INTEGER PRIMARY KEY AUTOINCREMENT , "
+COLUMN_NAME+" TEXT , "
+COLUMN_LAST_NAME+" TEXT , "
+COLUMN_PHONE_NUMBER+" TEXT);";
}
static class Seller{
public static final String TABLE_NAME = "tblEmployes";
public static final String COLUMN_AUTO_ID = "_id";
public static final String COLUMN_NAME="First Name";
public static final String COLUMN_LAST_NAME = "Last name";
public static final String COLUMN_EMPLOY_TYPE = "Type";
public static final String CREAT_STRING = "create table "+TABLE_NAME+
" ( "+COLUMN_AUTO_ID+" INTEGER PRIMARY KEY AUTOINCREMENT , "
+COLUMN_NAME+" TEXT , "
+COLUMN_LAST_NAME+" TEXT , "
+COLUMN_EMPLOY_TYPE+" TEXT);";
}
static class Buy{
public static final String TABLE_NAME = "tblBuys";
public static final String COLUMN_AUTO_ID = "_id";
public static final String COLUMN_CUSTOMER_ID = "Customer";
public static final String COLUMN_SELLER_ID = "Seller";
public static final String COLUMN_INFO = "Info";
public static final String COLUMN_PRICE = "Price";
public static final String CREAT_STRING = "create table "+TABLE_NAME+
" ( "+COLUMN_AUTO_ID+" INTEGER PRIMARY KEY AUTOINCREMENT , "
+COLUMN_CUSTOMER_ID+" TEXT, "
+COLUMN_SELLER_ID+" TEXT , "
+COLUMN_INFO+" TEXT "
+COLUMN_PRICE+" REAL"
+"FOREIGN KEY("+COLUMN_CUSTOMER_ID+") REFERENCES "+Customer.TABLE_NAME+"("+Customer.COLUMN_AUTO_ID+")"
+"FOREIGN_KEY("+COLUMN_SELLER_ID+") REFERENCES "+Seller.COLUMN_AUTO_ID+"("+Seller.COLUMN_AUTO_ID+")";
}
public static void main(String []args){
System.out.println(StoreContract.Customer.CREAT_STRING);
}
Notice the main method i wrote it to see how my Table creation String looks like of course the method didn't work probably be cause it is Android Project .So my question is simple what do you suggest to do in such cases i mean a except of copying and passing all class in to other project i am pretty sure that there is a standard solution for this stuff some unit-test or something.
Thank :)
The Android equivalent of the main method is onCreate() in Activities (and pretty much everywhere else)
Unlike pure java applications, Android apps will not call main() as their starting point, but instead the onCreate() method of their top level activity. This activity needs to be specified by name through <action android:name="android.intent.action.MAIN" /> in the manifest section defining that activity.
To go about this, you would make a class that inherits from activity, add the code from your current main method in the onCreate() method, and access the class you have currently from there.
Also, there is a lot more to how android handles the lifespan of activities, and the method calls in them. I recommend this link as a starting point to look into how android code runs.

Categories

Resources