Samiur Rahman Samiur Rahman - 6 months ago 33
Java Question

SQLite database connection issue

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


}

Answer

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.