I am trying to create a table using SQLite however the Create Table query does not seem to be working. When i open the .db file in an online viewer there is no data/table in the file (attached). I am not getting any errors when debugging; the issue. I have been deleting old .db files and making sure the onCreate code is running.
https://wsi.li/OzOSD2tTsB1qua/
Database Helper Code below:
package com.example.lewis.food;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Food.db";
public static final String TABLE_NAME = "food_table";
public static final String ID = "ID";
public static final String DESCRIPTION = "DESCRIPTION";
public static final String INGREDIENTS = "INGREDIENTS";
public static final String METHOD = "METHOD";
public static final String NOTES = "NOTES";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
try {
SQLiteDatabase db = this.getWritableDatabase();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(" CREATE TABLE " + TABLE_NAME + " (" +
ID + " TEXT PRIMARY KEY, " +
DESCRIPTION + " TEXT, " +
INGREDIENTS + " TEXT, " +
METHOD + " TEXT, " +
NOTES + " TEXT NOT NULL);"
);
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
Issue 1.
The onUpgrade method is part of the onCreate method move it to be out side the onCreate method. e.g. :-
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Food.db";
public static final String TABLE_NAME = "food_table";
public static final String ID = "ID";
public static final String DESCRIPTION = "DESCRIPTION";
public static final String INGREDIENTS = "INGREDIENTS";
public static final String METHOD = "METHOD";
public static final String NOTES = "NOTES";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
try {
SQLiteDatabase db = this.getWritableDatabase();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(" CREATE TABLE " + TABLE_NAME + " (" +
ID + " TEXT PRIMARY KEY, " +
DESCRIPTION + " TEXT, " +
INGREDIENTS + " TEXT, " +
METHOD + " TEXT, " +
NOTES + " TEXT NOT NULL);"
);
}
#Override
public void onUpgrade (SQLiteDatabase db,int oldVersion, int newVersion){
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
Note this may well just be that you dropped in the wrong code, as the code you have shown would very likely not compile.
Issue 2.
You are likely looking in the wrong place for the database/table.
The following code as the invoking activity (MainActivity used in the code) will confirm that the database is being created as well as the table, it will also print out the location of the database :-
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);
Cursor csr = mDBHlpr.getReadableDatabase().query("sqlite_master",null,null,null,null,null,null);
Log.d("DBLOCATION",this.getDatabasePath(DatabaseHelper.DATABASE_NAME).getAbsolutePath());
while (csr.moveToNext()) {
Log.d(
"DBINFO",
"Found a " + csr.getString(csr.getColumnIndex("type")) +
" named " + csr.getString(csr.getColumnIndex("name"))
);
}
csr.close();
}
}
When run (using only the above code) the result is :-
11-14 00:33:23.565 1246-1246/? D/DBLOCATION: /data/data/so53291104.so53291104/databases/Food.db
11-14 00:33:23.565 1246-1246/? D/DBINFO: Found a table named android_metadata
11-14 00:33:23.565 1246-1246/? D/DBINFO: Found a table named food_table
11-14 00:33:23.565 1246-1246/? D/DBINFO: Found a index named sqlite_autoindex_food_table_1
That is the above code creates the database, the table and the index on the food column (unless it already exists) and then logs some information about the actual database.
Note the DBLOCATION will depend upon your package and will not be the same as above.
You may wish to delete the App's data or uninstall the App before running any amended code.
Related
Hello I am making a simple note application, using an SQLite database, using a custom arraylist adapter, where the user can save a note having a title, a descriptive text, and the date. Everything works, but I want users to be able to save a new note only if the title is not in the database. How can I do this ?
Here is the edit note
public class Edit_notes extends AppCompatActivity {
private DBOpenHelper dbop;
private SQLiteDatabase sdb;
private EditText title_text;
private EditText note_text;
public boolean SaveNote(){
String note_title_string = title_text.getText().toString();
String note_text_string = note_text.getText().toString();
if (!note_title_string.isEmpty()){
if(!note_text_string.isEmpty()) {
// Need to check if title is not in the database then insert else don't
String date = new Date().getDate() + "/" + (new Date().getMonth() + 1) + "/" + (new Date().getYear() + 1900);
AddData(note_title_string, note_text_string, date); // Add title to the database
Toast.makeText(this, "Note saved", Toast.LENGTH_SHORT).show();
finish();
}
else {
Toast.makeText(this, "Note text cannot be empty", Toast.LENGTH_SHORT).show();
}
}
else{
Toast.makeText(this, "Title cannot be empty", Toast.LENGTH_SHORT).show();
}
return true;
}
public void AddData(String title_entry, String text_entry, String date){
dbop = new DBOpenHelper(this);
sdb = dbop.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("TITLE", title_entry);
cv.put("TEXT", text_entry);
cv.put("DATE", date);
sdb.insert("note_table", null, cv);
}
}
SQLite database.java:
public class DBOpenHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "notes.db";
public static final String TABLE_NAME = "note_table";
public static final String ID_COLUMN = "ID";
public static final String TITLE_COLUMN = "TITLE";
public static final String TEXT_COLUMN = "TEXT";
public static final String DATE_COLUMN = "DATE";
SQLiteDatabase db = this.getWritableDatabase();
public DBOpenHelper(Context context) {
super(context, DATABASE_NAME, null, 5);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME
+ " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " + " TITLE TEXT, " + " TEXT TEXT, " + " DATE STRING)";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table note_table");
onCreate(db);
}
}
I guess there is no need to provide the mainactivity.java
Change the table Create to :-
String createTable = "CREATE TABLE " + TABLE_NAME
+ " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " + " TITLE TEXT UNIQUE, " + " TEXT TEXT, " + " DATE STRING)";
Uninstall the App, or delete the App's Data, or increase the database version number and rerun the App. Row will not be added UNIQUE constraint conflict (same title) (insert method effectively uses INSERT OR IGNORE).
I'm having trouble finding what's missing in my code. I'm trying to insert data but "long result == db.insert" in my DatabaseHelper class always returns -1". I cannot pin point what I'm doing wrong. Please help. Any Idea would be very appreciated.
My DatabaseHelper class:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "drivefinal.db";
public static final String TABLE_NAME = "drive_table";
public static final String ID = "ID";
public static final String NUMBER = "Number";
public static final String FNAME = "First Name";
public static final String LNAME = "Last Name";
public static final String COORDINATE = "Coordinate";
public static final String ADDRESS = "Address";
public static final String NOTES = "Notes";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table if not exists " + TABLE_NAME +"(ID INTEGER PRIMARY KEY AUTOINCREMENT ,NUMBER TEXT,FNAME TEXT,LNAME TEXT,COORDINATE TEXT,ADDRESS TEXT,NOTES TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " +TABLE_NAME);
onCreate(db);
}
public boolean insertData(String number, String fName, String lName, String coordinate, String address, String notes){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(NUMBER, number);
contentValues.put(FNAME, fName);
contentValues.put(LNAME, lName);
contentValues.put(COORDINATE, coordinate);
contentValues.put(ADDRESS, address);
contentValues.put(NOTES, notes);
long result = db.insert(TABLE_NAME,null ,contentValues);
if(result == -1 )
return false;
else
return true;
}
My main activity file:
public void addData(){
btnSave.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v){
boolean isInserted = myDb.insertData(editTextnumber.getText().toString(),
editTextfname.getText().toString(),
editTextlname.getText().toString(),
editTextcoordinate.getText().toString(),
editTextaddress.getText().toString(),
editTextnotes.getText().toString());
if(isInserted)
Toast.makeText(MainActivity.this, "Data Inserted", Toast.LENGTH_SHORT).show();
else
Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
}
);
}
}
Your table definition creates column names that are not the same as the column names you are trying to use when inserting.
e.g. your table will have the column name FNAME not First Name (etc).
Secondly you would have issues trying to use a column named First Name as it includes a space and would have to be enclosed e.g. [First Name].
I'd suggest using :-
public static final String NUMBER = "Number";
public static final String FNAME = "FirstName"; //<<<<<<<<<< space removed
public static final String LNAME = "LastName"; //<<<<<<<<<< space removed
public static final String COORDINATE = "Coordinate";
public static final String ADDRESS = "Address";
public static final String NOTES = "Notes";
Along with :-
db.execSQL("create table if not exists " + TABLE_NAME +"(" + ID + " INTEGER PRIMARY KEY AUTOINCREMENT ," + NUMBER + " TEXT," + FNAME + " TEXT," + LNAME + " TEXT," + COORDINATE + " TEXT," + ADDRESS + " TEXT," + NOTES + " TEXT)");
To introduce the changes (i.e. for the onCreate method to run, as it only runs automatically when creating the database) you would have to do one of the following :-
Delete the App's data.
Uninstall the App.
Change the database version number e.g. change super(context, DATABASE_NAME, null, 1); to super(context, DATABASE_NAME, null, 2);
and then rerun the App.
I am currently working on an android quiz application with the questions linking to the database, however, I was be able to create the database created but somehow the values such as list of questions won't be inserted manually. As I have opened the database, it has organized the columns I have wanted but no values will be display such as the 'example question' Have I been missing some line of code?
Many Thanks
public class DatabaseHelper extends SQLiteOpenHelper
{
public static final String DATABASE_NAME = "Questions.db";
public static final String TABLE_NAME = "Questions";
public static final String QUESTION_NUMBER = "Question_Number";
public static final String QUESTION = "Question";
public static final String ANSWER_ONE = "Answer_ONE";
public static final String ANSWER_TWO = "Answer_THREE";
public static final String ANSWER_THREE = "Answer_FOUR";
private SQLiteDatabase db;
public DatabaseHelper(Context context)
{
super(context,DATABASE_NAME, null, 1);
SQLiteDatabase db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db)
{
this.db = db;
final String SQL_CREATE_QUESTIONS_TABLE = "CREATE TABLE " +
TABLE_NAME + " ( " +
QUESTION_NUMBER + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
QUESTION + " TEXT, " +
ANSWER_ONE + " TEXT, " +
ANSWER_TWO + " TEXT, " +
ANSWER_THREE + " TEXT " +
")";
db.execSQL(SQL_CREATE_QUESTIONS_TABLE);
fillQuestionTable();
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1)
{
db.execSQL("DROP TABLE IF EXISTS " +TABLE_NAME);
onCreate(db);
}
private void fillQuestionTable()
{
Question q1 = new Question(1,"Example Question?","Yes","Sometimes","No");
addQuestion(q1);
}
private void addQuestion (Question question)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(QUESTION_NUMBER, question.getQuestionNum());
cv.put(QUESTION, question.getQuestion());
cv.put(ANSWER_ONE, question.getOption1());
cv.put(ANSWER_TWO, question.getOption2());
cv.put(ANSWER_THREE, question.getOption3());
db.insert(TABLE_NAME,null,cv);
}
}
This is the activity Class
public class MainActivity extends Activity implements View.OnClickListener
{
Button screenOneButton;
Button screenTwoButton;
Button screenThreeButton;
Button quitButton;
DatabaseHelper mydb;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DatabaseHelper mydb = new DatabaseHelper(this);
}
This is programmed under Intellij software and was able to open the database under DB SQL software FYI!
Many thanks
Hi i am trying to make give connection with SQLlite database. Code is looking fine but database table is not created.App is running well but database is not created. Any suggestions?? My codes:
DatabaseManager.java
package com.step2rock.www.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;
import com.step2rock.www.model.User;
/**
* Created by Sushimz on 5/15/2016.
*/
public class DatabaseManager extends SQLiteOpenHelper {
Context context;
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "photography";
// Users table name
private static final String TABLE_USERS = "users";
//blog table name
private static final String TABLE_BLOG = "blog";
// Users Table Columns names
private static final String KEY_USER_ID = "id";
private static final String KEY_USER_first_NAME = "f_name";
private static final String KEY_USER_last_NAME = "l_name";
private static final String KEY_USER_PASS = "password";
private static final String KEY_USER_PIC = "profilepic";
private static final String KEY_USER_Address = "address";
private static final String KEY_USER_Exp = "exp_level";
private static final String KEY_USER_link = "link";
private static final String KEY_USER_TYPE = "type";
// Blog Table Columns names
private static final String KEY_Blog_ID = "id";
private static final String KEY_Blog_Title = "blog_tilte";
private static final String KEY_Blog_Desc = "blog_desc";
private static final String KEY_Blog_Image = "blog_image";
private static final String KEY_Blog_Link = "blog_link";
public DatabaseManager(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.d("users",TABLE_USERS);
Log.d("blog",TABLE_BLOG);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_USERS_TABLE = "CREATE TABLE " + TABLE_USERS
+ "("
+ KEY_USER_ID + " INTEGER PRIMARY KEY,"
+ KEY_USER_first_NAME + " TEXT,"
+ KEY_USER_last_NAME + " TEXT,"
+ KEY_USER_PASS + " TEXT,"
+ KEY_USER_PIC + " TEXT,"
+ KEY_USER_Address + " TEXT,"
+ KEY_USER_Exp + " TEXT,"
+ KEY_USER_link + " TEXT,"
+ KEY_USER_TYPE + " TEXT,"
+ ")";
db.execSQL(CREATE_USERS_TABLE);
String CREATE_BLOG_TABLE = "CREATE TABLE " + TABLE_BLOG
+ "("
+ KEY_Blog_ID + " INTEGER PRIMARY KEY,"
+ KEY_Blog_Title + " TEXT,"
+ KEY_Blog_Desc + " TEXT,"
+ KEY_Blog_Image + " TEXT,"
+ KEY_Blog_Link + " TEXT ,"
+ " FOREIGN KEY(" + KEY_USER_ID + ") REFERENCES Users(id) ON DELETE CASCADE "
+ ")";
db.execSQL(CREATE_BLOG_TABLE);
Toast.makeText(this.context, "AAA", Toast.LENGTH_SHORT).show();
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_BLOG);
// Create tables again
onCreate(db);
}
public void resetDB() {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_BLOG);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new USER
public int addUser(User user) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_USER_ID, user.get_user_id());
values.put(KEY_USER_first_NAME, user.get_first_name());
values.put(KEY_USER_last_NAME, user.get_last_name());
values.put(KEY_USER_PASS, user.get_user_pass());
values.put(KEY_USER_PIC, user.get_user_pic());
values.put(KEY_USER_Address, user.get_user_address());
values.put(KEY_USER_Exp, user.get_user_exp());
values.put(KEY_USER_link, user.get_user_link());
values.put(KEY_USER_TYPE, user.get_user_type());
// Inserting Row
int last_id = (int) db.insert(TABLE_USERS, null, values);
db.close(); // Closing database connection
return last_id;
}
// Updating single User
public int updateUser(User user) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_USER_ID, user.get_user_id());
values.put(KEY_USER_first_NAME, user.get_first_name());
values.put(KEY_USER_last_NAME, user.get_last_name());
values.put(KEY_USER_PASS, user.get_user_pass());
values.put(KEY_USER_PIC, user.get_user_pic());
values.put(KEY_USER_Address, user.get_user_address());
values.put(KEY_USER_Exp, user.get_user_exp());
values.put(KEY_USER_link, user.get_user_link());
values.put(KEY_USER_TYPE, user.get_user_type());
// updating row
return db.update(TABLE_USERS, values, KEY_USER_ID + " = ?",
new String[]{String.valueOf(user.get_user_id())});
}
}
RegistrationActivity.java
package com.step2rock.www.crudproject;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.step2rock.www.database.DatabaseManager;
/**
* Created by Sushimz on 5/15/2016.
*/
public class RegistrationActivity extends AppCompatActivity {
Button btnSaveRecord;
DatabaseManager databaseManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.registration_activity);
btnSaveRecord = (Button) findViewById(R.id.btnSaveRecord);
databaseManager = new DatabaseManager(RegistrationActivity.this);
btnSaveRecord.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Toast toast = Toast.makeText(RegistrationActivity.this,"welcome",Toast.LENGTH_SHORT);
toast.show();
}
});
}
}
The SQLiteOpenHelper you have there looks quite good.
Confusingly onCreate(...) is never called because it does not have the same behavior as an Activity.onCreate(...).
From the documentation:
Called when the database is created for the first time. This is where the creation of tables and the initial population of the tables should happen.
As far as I understand your code, the database is never created (unless you did it elsewhere). To create it you need to try to execute something on the database. For example, try to add a User on your button click. This will call getWriteableDdatabase() and should invoke onCreate(...):
btnSaveRecord.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
int id = databaseManager.addUser(new User(...));
Toast toast = Toast.makeText(RegistrationActivity.this,"Welcome User #" + id,Toast.LENGTH_SHORT);
toast.show();
}
});
Check if this calls your onCreate(...) method.
I'd also suggest you to add IF NOT EXISTS to your createTable Strings like so:"CREATE TABLE IF NOT EXISTS " + TABLE_USERS. This way, if you ever add a table, the others will not throw an error or be overwritten when the new table is created.
This question already has answers here:
What is a stack trace, and how can I use it to debug my application errors?
(7 answers)
Closed 7 years ago.
I have two tables: user and balance.
User DAO:
public class NewUserDAO {
public static final String TAG = "NewUserDAO";
public static final String TABLE_NEWUSER = "newUser";
//database fields
private SQLiteDatabase mDataBase;
private DatabaseHandler mDbHelper;
private Context mContext;
private String [] mAllColumns = {
DatabaseHandler.COLUMN_NEWUSER_ID,
DatabaseHandler.COLUMN_NEWUSER_NAME, DatabaseHandler.COLUMN_NEW_USER_PASSWORD,
DatabaseHandler.COLUMN_NEW_USER_AGE };
public NewUserDAO(Context context){
this.mContext = context;
mDbHelper = new DatabaseHandler(context);
try{
open();
} catch (SQLException e){
Log.e(TAG,"SQLexception on opening database" + e.getMessage());
e.printStackTrace();
}
}
public void open() throws SQLException{
mDataBase = mDbHelper.getWritableDatabase();
}
public void close(){
mDbHelper.close();
}
public void createNewUser(NewUserTable newUserTable){
ContentValues values = new ContentValues();
values.put(DatabaseHandler.COLUMN_NEWUSER_NAME,newUserTable.getName());
values.put(DatabaseHandler.COLUMN_NEW_USER_PASSWORD, newUserTable.getPassword());
values.put(DatabaseHandler.COLUMN_NEW_USER_AGE, newUserTable.getAge());
mDataBase.insert(TABLE_NEWUSER, null, values);
mDataBase.close();
}
}
balance DAO:
public class BalanceDAO {
public static final String TAG = "BalanceDAO";
public static final String TABLE_BALANCE = "balanceOfUser";
private Context mContext;
//Database fields
private SQLiteDatabase mDatabase;
private DatabaseHandler mDhelper;
private String[] mAllColumns = {
DatabaseHandler.COLUMN_BALANCE_ID,
DatabaseHandler.COLUMN_BALANCE_DOLLARBALANCE,
DatabaseHandler.COLUMN_BALANCE_RUBBALANCE,
DatabaseHandler.COLUMN_BALANCE_NEW_USER_ID
};
public BalanceDAO (Context context){
mDhelper = new DatabaseHandler(context);
this.mContext = context;
try{
open();
}
catch (SQLException e){
Log.e(TAG, "SQLException on openning database" + e.getMessage());
e.printStackTrace();
}
}
public void open() throws SQLException {
mDatabase = mDhelper.getWritableDatabase();
}
public void close(){
mDhelper.close();
}
public void createBalance (BalanceTable balanceTable){
ContentValues values = new ContentValues();
values.put(DatabaseHandler.COLUMN_BALANCE_DOLLARBALANCE,balanceTable.getDollarBalance());
values.put(DatabaseHandler.COLUMN_BALANCE_RUBBALANCE,balanceTable.getRubBalance());
mDatabase.insert(TABLE_BALANCE, null, values);
mDatabase.close();
}
}
And SQLiteOpenHelper class:
public class DatabaseHandler extends SQLiteOpenHelper {
//COLUMNS OF THE NEW USER TABLE
public static final String TABLE_NEWUSER = "newUser";
public static final String COLUMN_NEWUSER_ID = "id";
public static final String COLUMN_NEWUSER_NAME = "name";
public static final String COLUMN_NEW_USER_PASSWORD = "password";
public static final String COLUMN_NEW_USER_AGE = "age";
//COLUMNS OF THE BALANCE TABLE
public static final String COLUMN_BALANCE_ID = "id";
public static final String TABLE_BALANCE = "balanceOfUser";
public static final String COLUMN_BALANCE_DOLLARBALANCE = "dollarBalance";
public static final String COLUMN_BALANCE_RUBBALANCE = "rubBalance";
public static final String COLUMN_BALANCE_NEW_USER_ID = "newUserId";
private static final String DATABASE_NAME = "webStore";
private static final int DATABASE_VERSION = 1;
public DatabaseHandler(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
if (!db.isReadOnly()) {
// Enable foreign key constraints
db.execSQL("PRAGMA foreign_keys=ON;");
}
}
#Override
public void onCreate(SQLiteDatabase db) {
String SQL_CREATE_NEWUSER = "CREATE TABLE " + TABLE_NEWUSER + "("
+ COLUMN_NEWUSER_ID + " INTEGER PRIMARY KEY autoincrement,"
+ COLUMN_NEWUSER_NAME + " TEXT not null,"
+ COLUMN_NEW_USER_PASSWORD + " TEXT not null,"
+ COLUMN_NEW_USER_AGE + " INTEGER"
+ ")";
db.execSQL(SQL_CREATE_NEWUSER);
String SQL_CREATE_BALANCE = "CREATE TABLE " + TABLE_BALANCE + "("
+ COLUMN_BALANCE_ID + " INTEGER PRIMARY KEY autoincrement,"
+ COLUMN_BALANCE_DOLLARBALANCE + " INTEGER,"
+ COLUMN_BALANCE_RUBBALANCE + " INTEGER,"
+ COLUMN_BALANCE_NEW_USER_ID + " INTEGER," + "FOREIGN KEY("+COLUMN_BALANCE_NEW_USER_ID+") REFERENCES "
+ TABLE_NEWUSER + "(id) "+ ")" ;
db.execSQL(SQL_CREATE_BALANCE);
onCreate(db);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NEWUSER);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_BALANCE);
}
}
I want to join user and balance tables. How can i do? When i call Create Method, i have exception.
public void CreateUser(View view) {
etName = (EditText)findViewById(R.id.etName);
etPassword = (EditText)findViewById(R.id.etPassword);
etAge = (EditText)findViewById(R.id.etAge);
String name = String.valueOf(etName.getText());
String password = String.valueOf(etPassword.getText());
int age = Integer.parseInt(String.valueOf(etAge.getText()));
BalanceTable balanceTable = new BalanceTable(0,0);
NewUserTable newUserTable = new NewUserTable(name,password,age);
//write to database of user from our edit texts
DatabaseHandler databaseHandler = new DatabaseHandler(this);
Log.d("Insert: ", "Inserting ..");
NewUserDAO dbForUser = new NewUserDAO(this);
dbForUser.createNewUser(newUserTable);
BalanceDAO balanceDAO = new BalanceDAO(this);
balanceDAO.createBalance(balanceTable);
}
From edit text i take data. Help please
There are a few types if join, inner (which I think is what you want) which shows the data that matches, left showing all data from the first table and any additional data from the second table that meets the on condition or right which is shows all from the second table and any form the right that matches.
to Join two table you must use a statement such as
"SELECT <all the values you want> "+
" FROM users" +
" left join balance" +
" ON users.id=balance.userid " +
" where <some condition> "+
" order by gmttimestamp ;"; "
this will give you result set of mixed tables