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
Related
Im trying to figure out how I can delete one user at a time by typing in the edittext the users username and clicking deleting which I then want all the users information (username, usernum, password, birthdate, phone, address) to be deleted from the database. Below is my code and for some reason it isnt working can any one please please help me!! Im very desperate and ive been trying to figure out the problem for hours.
DatabaseHelperUser class:
public class DatabaseHelperUser extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "User.db";
public static final String TABLE_NAME = "User_table";
public static final String COL1 = "ID";
public static final String COL2 = "UserNum";
public static final String COL3 = "UserName";
public static final String COL4 = "Password";
public static final String COL5 = "BirthDate";
public static final String COL6 = "Phone";
public static final String COL7 = "Address";
public DatabaseHelperUser(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, UserNum TEXT,UserName Text,Password Text,BirthDate Text,Phone Text,Address Text)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public Cursor getData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from " + TABLE_NAME, null);
return res;
}
public boolean deleteData(String UserName) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "UserName" + "=?" + UserName, null) > 0;
}
}
RemoveUser class:
public class RemoveUser extends AppCompatActivity {
Button btdelete;
EditText txtUser;
DatabaseHelperUser myDb;
private String selectedName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_remove_user);
btdelete = (Button) findViewById(R.id.butRemove);
txtUser = (EditText) findViewById(R.id.etxtUserName);
myDb = new DatabaseHelperUser(this);
btdelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean delete = myDb.deleteData(txtUser.getText().toString());
if(delete == true)
Toast.makeText(RemoveUser.this,"User has been deleted", Toast.LENGTH_LONG).show();
else
Toast.makeText(RemoveUser.this,"User has not been deleted", Toast.LENGTH_LONG).show();
}
});
}
}
You must pass the variable UserName as the 3d argument of the method delete(), so it will replace the placeholder ? when the statement is executed:
public boolean deleteData(String UserName) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "UserName = ?", new String[] {UserName}) > 0;
}
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.
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
I am making a small app and therefore i need to use a small SQLite-database.
Please help me, i dont know how to fix this error:
At the line "SQLiteDatabase db = this.getReadableDatabase();" in the database
, (Main: int teams = db.countAllTeams())
Error: W/System.errīš Invalid int: ""
Database:
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "database";
private static final String TABLE_TEAM = "team";
private static final String KEY_TEAM_FULLNAME = "full_name";
private static final String KEY_TEAM_SHORTNAME = "short_name";
private static final String KEY_TEAM_STADIUM = "stadium";
private static final String KEY_TEAM_LOGO = "logo";
private static final String CREATE_TABLE_TEAM = "CREATE TABLE "
+ TABLE_TEAM + "(" + KEY_TEAM_FULLNAME + " TEXT PRIMARY KEY," +
KEY_TEAM_SHORTNAME + " TEXT," +
KEY_TEAM_STADIUM + " TEXT," +
KEY_TEAM_LOGO + " INTEGER" + ")";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_TEAM);
}
#Override
public void onUpgrade(SQLiteDatabase db, int old, int neW) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TEAM);
onCreate(db);
}
public void closeDB() {
SQLiteDatabase db = this.getReadableDatabase();
if (db != null && db.isOpen()) db.close();
}
public long createTeam(Team team) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TEAM_FULLNAME, team.getFullName());
values.put(KEY_TEAM_SHORTNAME, team.getShortName());
values.put(KEY_TEAM_LOGO, team.getLogo());
values.put(KEY_TEAM_STADIUM, team.getStadium());
return db.insert(TABLE_TEAM, null, values);
}
public int countAllTeams(){
SQLiteDatabase db = this.getReadableDatabase();
List<Team> teams = new ArrayList<Team>();
return Integer.getInteger(db.compileStatement("SELECT COUNT(*) FROM " + TABLE_TEAM).simpleQueryForString());
}
}
Main
DatabaseHelper db;
TextView tvText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_home);
tvText = (TextView)findViewById(R.id.tvText);
String text = "";
db = new DatabaseHelper(getApplicationContext());
int teams = db.countAllTeams();
tvText.setText(teams);
}
}
Integer.getInteger does not convert a string to an integer.
The easiest way to get a single number from a query is to use DatabaseUtils:
long count = DatabaseUtils.longForQuery(db,
"SELECT COUNT(*) FROM " + TABLE_TEAM, null);
But to get the number of rows in the table, there's an even simpler function:
long count = DatabaseUtils.queryNumEntries(db, TABLE_TEAM);
Furthermore, when you give an integer to TextView.setText, it expects a resource ID.
You have to convert your count into a string manually:
tvText.setText(Integer.toString(teams));
I'd use rawQuery() instead of simpleQueryForString():
public int countAllTeams(){
SQLiteDatabase db = this.getReadableDatabase();
List<Team> teams = new ArrayList<Team>();
Cursor c = db.rawQuery("SELECT COUNT(*) FROM " + TABLE_TEAM, new String[]{});
c.moveToFirst();
return c.getInt(0);
}
.setText doesn't take in integers directly, instead try:
tvText.setText(String.valueOf(teams));
Integer value in TextView
I am creating an instance of DBHelper Class in onCreate() of main activity.
databaseHelper = new DatabaseHelper(getBaseContext());
I am not getting when is onCreate() called. I tried giving Toast. As Soon as getWritableDatabase(); is called application force closes. Here is my code:
public class DatabaseHelper extends SQLiteOpenHelper
{
SQLiteDatabase db;
// Database Name
private static final String DATABASE_NAME = "manasi.db";
// database table name
private static final String TABLE_DATA = "data";
// Database table fields
private static final String KEY_IMEI = "imei";
private static final String KEY_LAT = "lat";
private static final String KEY_LONG = "long";
private static final String KEY_DATETIME = "datetime";
private static final String KEY_ALTITUDE = "altitude";
private static final String KEY_SPEED = "speed";
private static final String KEY_BATTERY = "battery";
Context context;
/**
* #param context Application Context
*/
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
// db = this.getWritableDatabase();
Toast.makeText(context, "db helper", Toast.LENGTH_LONG).show();
}
/* Called when the database is created for the first time.
* #see android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite.SQLiteDatabase)
*/
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE DB_TABLE(_id INTEGER PRIMARY KEY AUTOINCREMENT, content TEXT);");
Toast.makeText(context, "db helper onCreate", Toast.LENGTH_LONG).show();
String CREATE_DATA_TABLE = "CREATE TABLE " + TABLE_DATA + "("
+ KEY_IMEI + " TEXT ," + KEY_LAT + " DOUBLE," + KEY_LONG
+ "DOUBLE," + KEY_DATETIME + "DATETIME," + KEY_ALTITUDE + "DOUBLE,"
+ KEY_SPEED + "TEXT," + KEY_BATTERY + "TEXT" + ")";
db.execSQL(CREATE_DATA_TABLE);
Context context = null;
}
/* Called when the database needs to be upgraded.
* #see android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite.SQLiteDatabase, int, int)
*/
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("DatabaseHelper", "Upgrading database, which will destroy all old data");
onCreate(db);
}
public void insertRecordToDB(Data data) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_IMEI, data.getImei());
values.put(KEY_LAT, data.getLatitude());
values.put(KEY_LONG, data.getLongitude());
values.put(KEY_DATETIME, data.getDateTime());
values.put(KEY_ALTITUDE, data.getAltitude());
values.put(KEY_SPEED, data.getSpeed());
values.put(KEY_BATTERY, data.getBattery());
// Inserting Row
db.insert(TABLE_DATA, null, values);
db.close(); // Closing database connection*/
}
}
Do this in your activity
databaseHelper = new DatabaseHelper(this);
SQLiteDatabase sb = databaseHelper.getWritableDatabase();//this line responsible to call onCreate()
and read this http://mobileapplications-by-himanshu.blogspot.in/
onCreate() call once.