I want to use two tables in my SQLite database but when I try to read the second table my app crashes.
I have a table for the items in a storage and another table for the employees of the storage.
Here is my database class:
public class Database extends SQLiteOpenHelper {
protected static final String DATABASE_NAME = "Storage";
protected static final String KEY_ID = "id";
protected static final String KEY_DESCRIPTION = "description";
protected static final String KEY_CATEGORY = "category";
protected static final String KEY_ORIGIN = "origin";
protected static final String KEY_DATE = "date";
protected static final String KEY_BRAND = "brand";
protected static final String TAB_NAME = "items";
protected static final String KEY_ID2 = "id2";
protected static final String KEY_SURNAME = "surname";
protected static final String KEY_NAME = "name";
protected static final String KEY_USERNAME = "username";
protected static final String KEY_PASSWORD = "password";
protected static final String TAB_NAME2 = "employees";
protected static final int VERSION = 1;
public Database(Context context) {
super(context, DATABASE_NAME, null, VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_ITEMS_TABLE = "CREATE TABLE " + TAB_NAME + " ("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_DESCRIPTION + " TEXT, "
+ KEY_CATEGORY + " TEXT, "
+ KEY_ORIGIN + " TEXT, "
+ KEY_DATE + " TEXT, "
+ KEY_BRAND + " TEXT)";
String CREATE_DIPENDENTI_TABLE = "CREATE TABLE " + TAB_NAME2 + " ("
+ KEY_ID2 + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_SURNAME + " TEXT, "
+ KEY_NAME + " TEXT, "
+ KEY_USERNAME + " TEXT, "
+ KEY_PASSWORD + " TEXT)";
db.execSQL(CREATE_ITEMS_TABLE);
db.execSQL(CREATE_DIPENDENTI_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TAB_NAME);
db.execSQL("DROP TABLE IF EXISTS " + TAB_NAME2);
this.onCreate(db);
}
public void Add(String des, String cat, String pro, String data, String brand) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_DESCRIPTION, des);
contentValues.put(KEY_CATEGORY, cat);
contentValues.put(KEY_ORIGIN, pro);
contentValues.put(KEY_DATE, data);
contentValues.put(KEY_BRAND, brand);
sqLiteDatabase.insert(TAB_NAME,null, contentValues);
sqLiteDatabase.close();
}
public void Add(String cog, String nom, String user, String pass) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_SURNAME, cog);
contentValues.put(KEY_NAME, nom);
contentValues.put(KEY_USERNAME, user);
contentValues.put(KEY_PASSWORD, pass);
sqLiteDatabase.insert(TAB_NAME2,null, contentValues);
sqLiteDatabase.close();
}
public Cursor getInfo() {
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
String query = "SELECT * FROM " + TAB_NAME + ";";
return sqLiteDatabase.rawQuery(query, null);
}
public ArrayList getInfoDip() {
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
ArrayList<String> al=new ArrayList<>();
Cursor cursor= sqLiteDatabase.rawQuery("SELECT * FROM " +TAB_NAME2, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()){
al.add(cursor.getString(cursor.getColumnIndex("surname")));
al.add(cursor.getString(cursor.getColumnIndex("name")));
al.add(cursor.getString(cursor.getColumnIndex("username")));
al.add(cursor.getString(cursor.getColumnIndex("password")));
cursor.moveToNext();
}
return al;
}
public void Modify(int cod,String des, String cat, String pro, String dat, String bran){
SQLiteDatabase db = this.getWritableDatabase();
if(!des.isEmpty())
db.execSQL("UPDATE "+TAB_NAME+" SET description = "+"'"+des+"' "+ "WHERE id = "+"'"+cod+"'");
if(!cat.isEmpty())
db.execSQL("UPDATE "+TAB_NAME+" SET categoria = "+"'"+cat+"' "+ "WHERE id = "+"'"+cod+"'");
if(!pro.isEmpty())
db.execSQL("UPDATE "+TAB_NAME+" SET origin = "+"'"+pro+"' "+ "WHERE id = "+"'"+cod+"'");
if(!dat.isEmpty())
db.execSQL("UPDATE "+TAB_NAME+" SET date = "+"'"+dat+"' "+ "WHERE id = "+"'"+cod+"'");
if(!bran.isEmpty())
db.execSQL("UPDATE "+TAB_NAME+" SET brand = "+"'"+bran+"' "+ "WHERE id = "+"'"+cod+"'");
}
public void Modify(int cod, String cog, String nom, String user, String pass){
SQLiteDatabase db = this.getWritableDatabase();
if(!cog.isEmpty())
db.execSQL("UPDATE "+TAB_NAME2+" SET surname = "+"'"+cog+"' "+ "WHERE id2 = "+"'"+cod+"'");
if(!nom.isEmpty())
db.execSQL("UPDATE "+TAB_NAME2+" SET name = "+"'"+nom+"' "+ "WHERE id2 = "+"'"+cod+"'");
if(!user.isEmpty())
db.execSQL("UPDATE "+TAB_NAME2+" SET username = "+"'"+user+"' "+ "WHERE id2 = "+"'"+cod+"'");
if(!pass.isEmpty())
db.execSQL("UPDATE "+TAB_NAME2+" SET password = "+"'"+pass+"' "+ "WHERE id2 = "+"'"+cod+"'");
}
public void Delete(int cod){
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM "+TAB_NAME+" WHERE id= "+"'"+cod+"'");
}
public void DeleteDip(int cod){
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM "+TAB_NAME2+" WHERE id2= "+"'"+cod+"'");
}
public Cursor Search(int cod){
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
String query = "SELECT * FROM " + TAB_NAME + " WHERE id = "+"'"+cod+"';";
return sqLiteDatabase.rawQuery(query, null);
}
public Cursor Search(String des){
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
String query = "SELECT * FROM " + TAB_NAME + " WHERE description = "+"'"+des+"';";
return sqLiteDatabase.rawQuery(query, null);
}
public void DeleteAll() {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from " + TAB_NAME);
}
}
and here is the activity where I try to get the ArrayList with the data:
private Database db= new Database(this);
private ArrayList<String> al=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
db.Add("admin","admin","admin","admin");
al.addAll(db.getInfoDip());
But when I try to put the data in the ArrayList the app crashes. Can anyone help me out?
Well so far, how I learned that the best practice for formating queries is to use String.format function. Here your example:
String query = "SELECT * FROM " + TAB_NAME + ";";
Best practice:
String query = String.format("SELECT * FROM %s", TAB_NAME);
So let's get to the getInfoDip method, you should try this:
public List<ContentValues> getInfoDip() {
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
String query = String.format("SELECT * FROM %s", TAB_NAME2);
Cursor res = db.rawQuery(query, null);
res.moveToFirst();
List<ContentValues> list = new ArrayList<>(res.getCount());
while (!res.isAfterLast()){
String surname = res.getString(res.getColumnIndex(KEY_SURNAME));
String name = res.getString(res.getColumnIndex(KEY_NAME));
String username = res.getString(res.getColumnIndex(KEY_USERNAME));
String password = res.getString(res.getColumnIndex(KEY_PASSWORD));
list.add(new ContentValues(surname, name, username, password));
res.moveToNext();
}
return list;
}
Here is my whole SQLite test program, check out maybe it helps you:
package com.example.vezba09;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
public class Database extends SQLiteOpenHelper {
private static final String DATABASE_FILE_NAME = "contact_database";
public Database(#Nullable Context context) {
super(context, DATABASE_FILE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = String.format(
"CREATE TABLE IF NOT EXISTS %s (%s INTEGER PRIMARY KEY AUTOINCREMENT, %s TEXT, %s TEXT, %s TEXT)",
ContactModel.TABLE_NAME,
ContactModel.COLUMN_CONTACT_ID,
ContactModel.COLUMN_CONTACT_NAME,
ContactModel.COLUMN_CONTACT_EMAIL,
ContactModel.COLUMN_CONTACT_PHONE
);
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
String query = String.format("DROP TABLE IF EXISTS %s", ContactModel.TABLE_NAME);
db.execSQL(query);
onCreate(db);
}
//Dodavanje kontakta
public void addContact(String name, String email, String phone) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(ContactModel.COLUMN_CONTACT_NAME, name);
cv.put(ContactModel.COLUMN_CONTACT_EMAIL, email);
cv.put(ContactModel.COLUMN_CONTACT_PHONE, phone);
db.insert(ContactModel.TABLE_NAME, null, cv);
}
//Izmena
public void editContact(int contactId, String name, String email, String phone) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(ContactModel.COLUMN_CONTACT_NAME, name);
cv.put(ContactModel.COLUMN_CONTACT_EMAIL, email);
cv.put(ContactModel.COLUMN_CONTACT_PHONE, phone);
db.update(ContactModel.TABLE_NAME,
cv,
ContactModel.COLUMN_CONTACT_ID + "=?",
new String[]{String.valueOf(contactId)});
}
public int deleteContact(int contactId) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(ContactModel.TABLE_NAME,
ContactModel.COLUMN_CONTACT_ID + "=?",
new String[]{String.valueOf(contactId)});
}
public ContactModel getContactById(int contactId) {
SQLiteDatabase db = this.getReadableDatabase();
String query = String.format("SELECT * FROM %s WHERE %s = ?",
ContactModel.TABLE_NAME,
ContactModel.COLUMN_CONTACT_ID);
Cursor res = db.rawQuery(query, new String[] {String.valueOf(contactId)});
if(res.moveToFirst()) {
String name = res.getString(res.getColumnIndex(ContactModel.COLUMN_CONTACT_NAME));
String email = res.getString(res.getColumnIndex(ContactModel.COLUMN_CONTACT_EMAIL));
String phone = res.getString(res.getColumnIndex(ContactModel.COLUMN_CONTACT_PHONE));
return new ContactModel(contactId, name, email, phone);
}
else {
return null;
}
}
public List<ContactModel> getAllContacts() {
SQLiteDatabase db = this.getReadableDatabase();
String query = String.format("SELECT * FROM %s", ContactModel.TABLE_NAME);
Cursor res = db.rawQuery(query, null);
res.moveToFirst();
List<ContactModel> list = new ArrayList<>(res.getCount());
while(!res.isAfterLast()) {
int contactId = res.getInt(res.getColumnIndex(ContactModel.COLUMN_CONTACT_ID));
String name = res.getString(res.getColumnIndex(ContactModel.COLUMN_CONTACT_NAME));
String email = res.getString(res.getColumnIndex(ContactModel.COLUMN_CONTACT_EMAIL));
String phone = res.getString(res.getColumnIndex(ContactModel.COLUMN_CONTACT_PHONE));
list.add(new ContactModel(contactId, name, email, phone));
res.moveToNext();
}
return list;
}
}
Try this and feel free to ask more questions :)
Best regards, Sanady
Related
I am creating a login app, where a user has an username and a password. I want to save sign up data in my database, but when I want to get access to the elements from database, no one seems to be saved ( it has no user saved in db). I suppose the error comes from db implementation. Any idea?
public class DataBaseHelper extends SQLiteOpenHelper {
public static final String TABLE_NAME = "user_table";
public static final String COL1 = "ID";
public static final String COL2 = "user_username";
public static final String COL3 = "user_password";
public DataBaseHelper(Context context) {
super(context, TABLE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + "( " + COL2 + " TEXT," +
COL3 + "TEXT)";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public void add(String name, String password) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, name);
contentValues.put(COL3, password);
db.insert(TABLE_NAME, null, contentValues);
}
public Cursor getData() {
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT *FROM " + TABLE_NAME;
Cursor data = db.rawQuery(query, null);
return data;
}
LOGIN Activity:
public void loginSeach(View view) {
EditText password_editText = (EditText) findViewById(R.id.editText_password);
EditText username_editText = (EditText) findViewById(R.id.editText_username);
String currUserName = username_editText.getText().toString();
String currPassWord = password_editText.getText().toString();
DataBaseHelper db = new DataBaseHelper(this);
Cursor data = db.getData();
int Number = 0;
while (data.moveToNext()) {
Number ++;
String userName = data.getString(1);
String passWord = data.getString(2);
}
Toast.makeText(this, Integer.toString(Number), Toast.LENGTH_SHORT).show();
}
Sign up activity:
public void createAccount(View view) {
EditText usernameEditText = (EditText) findViewById(R.id.editText_createUsername);
EditText passwordEditText = (EditText) findViewById(R.id.editText_createPassword);
String userName = usernameEditText.getText().toString();
String passWord = passwordEditText.getText().toString();
dataBaseHelper.add(userName, passWord);
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
This statement in onCreate():
String createTable = "CREATE TABLE " + TABLE_NAME + "(" + COL2 + " TEXT," + COL3 + "TEXT)";
created a table without an ID column.
Uninstall the app from the emulator/device, change your code to this:
String createTable = "CREATE TABLE " + TABLE_NAME + "(" + COL1 + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL2 + " TEXT," + COL3 + " TEXT)";
and rerun the app.
I am new to Android and I want it when the user logs in by the email and password. Bring the rest of the information like the first name and the date of birth to the user via email. Is there any way to do that?
"Is there a function I can add that can not bring all user information after logging in by email"
this is my database Code :
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "UserManager.db";
private static final String TABLE_USER = "user";
private static final String COLUMN_USER_ID = "user_id";
private static final String COLUMN_USER_FIRST_NAME = "user_first_name";
private static final String COLUMN_USER_LAST_NAME = "user_last_name";
private static final String COLUMN_USER_EMAIL = "user_email";
private static final String COLUMN_USER_PHONE_NUMBER = "user_phone_number";
private static final String COLUMN_USER_BARTH_DAY = "user_barth_day";
private static final String COLUMN_USER_PASSWORD = "user_password";
private static final String COLUMN_USER_GENDER = "user_gender";
private String CREATE_USER_TABLE = "CREATE TABLE "+TABLE_USER + "("+
COLUMN_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"+
COLUMN_USER_FIRST_NAME + " TEXT,"+ COLUMN_USER_LAST_NAME + " TEXT,"+
COLUMN_USER_EMAIL + " TEXT PRIMARY KEY,"+COLUMN_USER_PHONE_NUMBER + " TEXT,"+
COLUMN_USER_BARTH_DAY+" TEXT,"+ COLUMN_USER_PASSWORD+" TEXT," +
COLUMN_USER_GENDER+" TEXT"+ ")";
private String DROP_USER_TABLE = "DROP TABLE IF EXISTS "+ TABLE_USER ;
public DatabaseHelper(Context context) {
super(context , DATABASE_NAME, null , DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_USER_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DROP_USER_TABLE);
onCreate(db);
}
public void addUser(User user){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_USER_FIRST_NAME , user.getFirstName());
values.put(COLUMN_USER_LAST_NAME , user.getLastName());
values.put(COLUMN_USER_EMAIL , user.getEmail());
values.put(COLUMN_USER_PHONE_NUMBER , user.getPhoneNumber());
values.put(COLUMN_USER_BARTH_DAY , user.getBarthDay());
values.put(COLUMN_USER_PASSWORD , user.getPassword());
values.put(COLUMN_USER_GENDER , user.getGender());
database.insert(TABLE_USER , null, values);
database.close();
}
public boolean checkUser (String email){
String [] columns = {
COLUMN_USER_ID
};
SQLiteDatabase database = this.getWritableDatabase();
String selection = COLUMN_USER_EMAIL + " = ?";
String[] selectionArgs = {email};
Cursor cursor = database.query(TABLE_USER,
columns,selection , selectionArgs,null,null,null);
int cursorCount = cursor.getCount();
cursor.close();
database.close();
if (cursorCount > 0){
return true;
}else {
return false;
}
}
public boolean checkUser (String email , String password){
String [] columns = {
COLUMN_USER_ID
};
SQLiteDatabase database = this.getWritableDatabase();
String selection = COLUMN_USER_EMAIL + " = ?" + " AND " + COLUMN_USER_PASSWORD + " = ?";
String[] selectionArgs = {email , password};
Cursor cursor = database.query(TABLE_USER,
columns,selection , selectionArgs,null,null,null);
int cursorCount = cursor.getCount();
cursor.close();
database.close();
if (cursorCount > 0){
return true;
}else {
return false;
}
}
}
For your first question, you can add below function and use it.
public User getSingleUserInfo(String email){
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery("SELECT * FROM " + TABLE_USER + " WHERE " + COLUMN_USER_EMAIL + "=" + email);
cursor.moveToFirst();
//setting related user info in User Object
User user = new User();
user.setUserId(cursor.getInt(cursor.getColumnIndexCOLUMN_USER_ID ));
user.setFirstName(cursor.getString(cursor.getColumnIndex(COLUMN_USER_FIRST_NAME));
user.setLastName(cursor.getString(cursor.getColumnIndex(COLUMN_USER_LAST_NAME ));
user.setEmail(cursor.getString(cursor.getColumnIndex(COLUMN_USER_EMAIL ));
user.setPhoneNumber(cursor.getString(cursor.getColumnIndex(COLUMN_USER_PHONE_NUMBER ));
user.setBirthday(cursor.getString(cursor.getColumnIndex(COLUMN_USER_BARTH_DAY ));
user.setPassword(cursor.getString(cursor.getColumnIndex(COLUMN_USER_PASSWORD));
user.setGender(cursor.getString(cursor.getColumnIndex(COLUMN_USER_GENDER ));
//close cursor & database
cursor.close();
database.close();
return user;
}
Note : Becareful about your User object's setter functions which may be vary from my example and data types. Use c.getInt() if it is int and c.getString() if String.
You can use particular email address with password to query in database to get all the details.
public String getUserName(String email, String password) {
Cursor cursor = null;
String firstName = "";
try {
cursor = SQLiteDatabaseInstance_.rawQuery("SELECT * FROM " + TABLE_USER + " WHERE "+ COLUMN_USER_EMAIL +"?", new String[] {email+ ""}+ " AND "+COLUMN_USER_PASSWORD+"?", new String[] {password+ ""});
if(cursor.getCount() > 0) {
cursor.moveToFirst();
firstName= cursor.getString(cursor.getColumnIndex(COLUMN_USER_FIRST_NAME));
}
return firstName;
}finally {
cursor.close();
}
}
How to read and display "email" and "address" in HomeAcitivity TextView.
The database designed to be store only 1 row of data.
DatabaseHandler.java
package com.example.androidjhfong.library;
import java.util.HashMap;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "android_database";
// Table name
private static final String TABLE_LOGIN = "login";
// Login Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_EMAIL = "email";
private static final String KEY_UID = "uid";
private static final String KEY_ADDRESS = "address";
private static final String KEY_PHONE = "phone";
private static final String KEY_CREATED_AT = "created_at";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_LOGIN + "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_NAME + " TEXT,"
+ KEY_EMAIL + " TEXT UNIQUE,"
+ KEY_UID + " TEXT,"
+ KEY_ADDRESS + " TEXT,"
+ KEY_PHONE + " TEXT,"
+ KEY_CREATED_AT + " TEXT" + ")";
db.execSQL(CREATE_LOGIN_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOGIN);
// Create tables again
onCreate(db);
}
/**
* Storing user details in database
* */
public void addUser(String name, String email, String uid, String address, String phone, String created_at) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, name); // Name
values.put(KEY_EMAIL, email); // Email
values.put(KEY_UID, uid); // Email
values.put(KEY_ADDRESS, address); // Address
values.put(KEY_PHONE, phone); // phone
values.put(KEY_CREATED_AT, created_at); // Created At
// Inserting Row
db.insert(TABLE_LOGIN, null, values);
db.close(); // Closing database connection
}
/**
* Getting user data from database
* */
public HashMap<String, String> getUserDetails(){
HashMap<String,String> user = new HashMap<String,String>();
String selectQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if(cursor.getCount() > 0){
user.put("name", cursor.getString(1));
user.put("email", cursor.getString(2));
user.put("uid", cursor.getString(3));
user.put("address", cursor.getString(4));
user.put("phone", cursor.getString(5));
user.put("created_at", cursor.getString(6));
}
cursor.close();
db.close();
// return user
return user;
}
/**
* Getting user login status
* return true if rows are there in table
* */
public int getRowCount() {
String countQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int rowCount = cursor.getCount();
db.close();
cursor.close();
// return row count
return rowCount;
}
/**
* Re crate database
* Delete all tables and create them again
* */
public void resetTables(){
SQLiteDatabase db = this.getWritableDatabase();
// Delete All Rows
db.delete(TABLE_LOGIN, null, null);
db.close();
}
/**
* Getting product status
**/
public String getData() {
String username;
String getdata = "SELECT name FROM " + TABLE_LOGIN;
//String[] columns = new String[]{ KEY_ID, KEY_NAME, KEY_ADDRESS, KEY_PHONE};
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(getdata, null);
cursor.moveToFirst();
username=cursor.getString(cursor.getColumnIndex("name"));
cursor.close();
db.close();
return username;
}
}
how to display the retrieve the data and display in HomeActivity correctly?
HomeActivity
public class HomeActivity extends Activity implements OnItemSelectedListener{
TextView inputname
TextView inputemail;
TextView inputaddress;
Button btnPurchase;
// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ADDRESS = "address";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.Home);
inputname= (TextView) findViewById(R.id.qrpurchaseitem);
inputaddress = (TextView) findViewById(R.id.qrtextpurchaseaddress);
inputemail = (TextView) findViewById(R.id.qrtextpurchasecomment);
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
HashMap<String, String> key = db.getUserDetails();
String text= DatabaseHandler.getUserDetails();
}
in your HomeActivty add this both line
String email=db.getEmail()
String address=db.getAddress();
Now then you can use below method in you Database Handler class, just change variable name from below methods
public String getStartBal() {
Cursor cr=ourDatabase.rawQuery("SELECT "+KEY_START_BAL+" FROM "+DB_TABLE,null);
String sum="";
for(cr.moveToFirst();!cr.isAfterLast();cr.moveToNext()){
sum=cr.getString(cr.getColumnIndex(KEY_START_BAL));
}
cr.close();
return sum;
}
Please help me, I'm newbie and I have problem. I try to create multiple table in this code but always error. this error say there is no table PENGINAPAN and i can't solve it.
this is DatabaseHelper class :
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "dbwisata";
public static final String NAMA = "nama";
public static final String KEY_ID = "_id";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
// method createTable untuk membuat table WISATA
public void createTable(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS WISATA");
db.execSQL("CREATE TABLE if not exists WISATA (_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "nama TEXT);");
db.execSQL("DROP TABLE IF EXISTS PENGINAPAN");
db.execSQL("CREATE TABLE if not exists PENGINAPAN (_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "nama TEXT);");
}
// method generateData untuk mengisikan data ke table Wisata.
public void generateData(SQLiteDatabase db) {
ContentValues cv = new ContentValues();
cv.put(NAMA, "Ancol");
db.insert("WISATA", NAMA, cv);
cv.put(NAMA, "Ragunan");
db.insert("WISATA", NAMA, cv);
cv.put(NAMA, "Taman Mini");
db.insert("PENGINAPAN", NAMA, cv);
cv.put(NAMA, "Melati");
db.insert("PENGINAPAN", NAMA, cv);
cv.put(NAMA, "Villa");
db.insert("PENGINAPAN", NAMA, cv);
cv.put(NAMA, "Bintang");
db.insert("PENGINAPAN", NAMA, cv);
}
// method delAllAdata untuk menghapus data di table Wisata.
public void delAllData(SQLiteDatabase db) {
db.delete("WISATA", null, null);
db.delete("WISATA", null, null);
}
public Cursor fetchAllWisata(SQLiteDatabase db) {
return db.query("WISATA", new String[] { KEY_ID, NAMA }, null, null,
null, null, null);
}
public Cursor fetchAllPenginapan(SQLiteDatabase db) {
return db.query("PENGINAPAN", new String[] { KEY_ID, NAMA }, null, null,
null, null, null);
}
#Override
public void onCreate(SQLiteDatabase db) {
createTable(db);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
please help me.
I cleaned up your code. If it doesn't work, uninstall your app and install it again. Be sure you create the database before you try to write/read any data.
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "dbwisata";
private static final String TABLE_WISATA = "WISATA";
private static final String TABLE_PENGINAPAN = "PENGINAPAN";
public static final String NAMA = "nama";
public static final String KEY_ID = "_id";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
// method createTable untuk membuat table WISATA
public void createTable(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_WISATA);
db.execSQL("CREATE TABLE if not exists " + TABLE_WISATA + " (" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "nama TEXT);");
db.execSQL("DROP TABLE IF EXISTS PENGINAPAN");
db.execSQL("CREATE TABLE if not exists " + TABLE_PENGINAPAN + " (" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ NAMA + " TEXT);");
}
// method generateData untuk mengisikan data ke table Wisata.
public void generateData(SQLiteDatabase db) {
ContentValues cv = new ContentValues();
cv.put(NAMA, "Ancol");
db.insert(TABLE_WISATA, null, cv);
cv.put(NAMA, "Ragunan");
db.insert(TABLE_WISATA, null, cv);
cv.put(NAMA, "Taman Mini");
db.insert(TABLE_PENGINAPAN, null, cv);
cv.put(NAMA, "Melati");
db.insert(TABLE_PENGINAPAN, null, cv);
cv.put(NAMA, "Villa");
db.insert(TABLE_PENGINAPAN, null, cv);
cv.put(NAMA, "Bintang");
db.insert(TABLE_PENGINAPAN, null, cv);
}
// method delAllAdata untuk menghapus data di table Wisata.
public void delAllData(SQLiteDatabase db) {
db.delete(TABLE_WISATA, null, null);
db.delete(TABLE_WISATA, null, null);
}
public Cursor fetchAllWisata(SQLiteDatabase db) {
return db.query(TABLE_WISATA, new String[] { KEY_ID, NAMA }, null, null,
null, null, null);
}
public Cursor fetchAllPenginapan(SQLiteDatabase db) {
return db.query(TABLE_PENGINAPAN, new String[] { KEY_ID, NAMA }, null, null,
null, null, null);
}
#Override
public void onCreate(SQLiteDatabase db) {
createTable(db);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
Use this code and modify it as per your needs. i have added all comments so that you can understand where i am adding a table, where i am adding a column and where i am adding entries.
public class DatabaseHelper extends SQLiteOpenHelper {
//changing master
// Logcat tag
//add comment
private static final String LOG = "DatabaseHelper";
// Database Version
private static final int DATABASE_VERSION = 3;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
// Table Names
private static final String TABLE_VIDEO = "video";
private static final String TABLE_PICTURE = "pictures";
private static final String TABLE_MUSIC = "music";
// Common column names
private static final String KEY_ID = "id";
private static final String KEY_FAV = "fav";
// MUSIC Table - column names
private static final String KEY_MUSIC_PATH = "path";
private static final String KEY_MUSIC_CAT_ID = "cat_id";
private static final String KEY_MUSIC_NAME = "music_name";
// PICTURE Table - column names
private static final String KEY_PICTURE_PATH = "path";
private static final String KEY_PICTURE_CAT_ID = "cat_id";
private static final String KEY_PICTURE_NAME = "picture_name";
// VIDEO Table - column names
private static final String KEY_VIDEO_PATH = "path";
private static final String KEY_VIDEO_CAT_ID = "cat_id";
private static final String KEY_VIDEO_SUBCAT_ID = "subcat_id";
private static final String KEY_VIDEO_NAME = "video_name";
// Table Create Statements
// Video table create statement
private static final String CREATE_TABLE_VIDEO = "CREATE TABLE "
+ TABLE_VIDEO + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_FAV + " TEXT,"
+ KEY_VIDEO_PATH + " TEXT,"
+ KEY_VIDEO_CAT_ID+ " INTEGER,"
+ KEY_VIDEO_SUBCAT_ID + " TEXT,"
+ KEY_VIDEO_NAME + " TEXT)";
// PICTURE table create statement
private static final String CREATE_TABLE_PICTURE = "CREATE TABLE "
+ TABLE_PICTURE + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_FAV + " TEXT,"
+ KEY_PICTURE_PATH + " TEXT," + KEY_PICTURE_CAT_ID+ " INTEGER,"
+ KEY_PICTURE_NAME + " TEXT)";
// MUSIC table create statement
private static final String CREATE_TABLE_MUSIC = "CREATE TABLE "
+ TABLE_MUSIC + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_FAV + " TEXT,"
+ KEY_MUSIC_PATH + " TEXT," + KEY_MUSIC_CAT_ID+ " INTEGER,"
+ KEY_MUSIC_NAME + " TEXT)";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
// creating required tables
db.execSQL(CREATE_TABLE_PICTURE);
db.execSQL(CREATE_TABLE_MUSIC);
db.execSQL(CREATE_TABLE_VIDEO);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
// on upgrade drop older tables
db.execSQL("DROP TABLE IF EXISTS " + TABLE_VIDEO);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PICTURE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MUSIC);
// create new tables
onCreate(db);
}
/*
* create videos
* */
/* public boolean addVideos(List<Video> video, int category_id){
SQLiteDatabase db = this.getWritableDatabase();
long id = 0;
for(int i = 0; i <video.size(); ++i){
ContentValues values = new ContentValues();
values.put(KEY_VIDEO_NAME, video.get(i).getName());
values.put(KEY_VIDEO_PATH, video.get(i).getPath());
values.put(KEY_VIDEO_CAT_ID, category_id);
// insert row
id = db.insert(TABLE_VIDEO, null, values);
}
if (id < 0)
return false;
return true;
}*/
// add videos
public void addvideos(Video item, int catid, String subcat) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("insert into video (fav, path, cat_id, subcat_id , video_name) VALUES (" + "'" + item.isFavourite() + "',"+ "'" + item.getPath() + "'," + "'" + catid + "'," + "'" + subcat + "'," + "'" + item.getName() + "'" + ")");
}
// add pictures
public void addpictures(Picture item, int catid) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("insert into video (path, cat_id , video_name) VALUES (" + "'" + item.isFavourite() + "',"+ "'" + item.getPath() + "'," + "'" + catid + "'," + "'" + item.getName() + "'" + ")");
}
// add music
public void addmusic(Music item, int catid) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("insert into video (path, cat_id , video_name) VALUES (" + "'" + item.isFavourite() + "',"+ "'" + item.getPath() + "'," + "'" + catid + "'," + "'" + item.getName() + "'" + ")");
}
/*
* getting all videos
* */
public List<Video> getAllVideos() {
List<Video> lstVideo = new ArrayList<Video>();
String selectQuery = "SELECT * FROM " + TABLE_VIDEO;
Log.e(LOG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
Video video = new Video();
video.setId(c.getInt((c.getColumnIndex(KEY_ID))));
video.setName((c.getString(c.getColumnIndex(KEY_VIDEO_NAME))));
video.setPath((c.getString(c.getColumnIndex(KEY_VIDEO_PATH))));
video.setSubcategory(c.getString(c.getColumnIndex(KEY_VIDEO_SUBCAT_ID)));
// adding to video list
lstVideo.add(video);
} while (c.moveToNext());
}
return lstVideo;
}
/*
* getting all videos by categories
* */
public List<Video> getAllVideosByCategory(String category) {
List<Video> lstVideo = new ArrayList<Video>();
String selectQuery = "SELECT * FROM " + TABLE_VIDEO +
" WHERE " + TABLE_VIDEO + "." + KEY_VIDEO_SUBCAT_ID +
" = " + category;
Log.e(LOG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
Video video = new Video();
video.setId(c.getInt((c.getColumnIndex(KEY_ID))));
video.setName((c.getString(c.getColumnIndex(KEY_VIDEO_NAME))));
video.setPath((c.getString(c.getColumnIndex(KEY_VIDEO_PATH))));
video.setSubcategory(c.getString(c.getColumnIndex(KEY_VIDEO_SUBCAT_ID)));
// adding to video list
lstVideo.add(video);
} while (c.moveToNext());
}
return lstVideo;
}
// getting all pictures
public List<Picture> getAllPictures() {
List<Picture> lstVideo = new ArrayList<Picture>();
String selectQuery = "SELECT * FROM " + TABLE_PICTURE;
Log.e(LOG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
Picture video = new Picture();
video.setId(c.getInt((c.getColumnIndex(KEY_ID))));
video.setName((c.getString(c.getColumnIndex(KEY_PICTURE_NAME))));
video.setPath((c.getString(c.getColumnIndex(KEY_PICTURE_PATH))));
// adding to video list
lstVideo.add(video);
} while (c.moveToNext());
}
return lstVideo;
}
// getting all music
public List<Music> getAllMusic() {
List<Music> lstVideo = new ArrayList<Music>();
String selectQuery = "SELECT * FROM " + TABLE_MUSIC;
Log.e(LOG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
Music video = new Music();
video.setId(c.getInt((c.getColumnIndex(KEY_ID))));
video.setName((c.getString(c.getColumnIndex(KEY_VIDEO_NAME))));
video.setPath((c.getString(c.getColumnIndex(KEY_VIDEO_PATH))));
// adding to video list
lstVideo.add(video);
} while (c.moveToNext());
}
return lstVideo;
}
// closing database
public void closeDB() {
SQLiteDatabase db = this.getReadableDatabase();
if (db != null && db.isOpen())
db.close();
}
}
Updated Answer: Picture class code is added
public class Picture {
public int id;
public String name;
public String path;
public int favourite;
public int getFavourite() {
return favourite;
}
public void setFavourite(int favourite) {
this.favourite = favourite;
}
public Picture(){
}
public Picture(int id, String name, String path){
this.id = id;
this.name = name;
this.path = path;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
}
I want built a Android Application with a SQLite Database. I have two Java Classes. The First is the Contact Class ans the second the DatabaseHandle class for the operations how add, update etc...
I don't get a error but if I start my Application I become this message ...
Here is my Contact Class
package de.linde.sqlite;
public class Contact {
int _id;
String _name;
String _phone_number;
public Contact(){}
public Contact(int id,String name,String _phone_number){
this._id = id;
this._name = name;
this._phone_number = _phone_number;
}
public Contact(String name,String _phone_number){
this._name = name;
this._phone_number = _phone_number;
}
public int getID(){
return this._id;
}
public void setID(int id){
this._id = id;
}
public String getName(){
return this._name;
}
public void setName(String name){
this._name = name;
}
public String getPhoneNumber(){
return this._phone_number;
}
public void setPhoneNumber(String phone_number){
this._phone_number = phone_number;
}
}
Here is my DatabaseHandler Class
package de.linde.sqlite;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHandler extends SQLiteOpenHelper {
//Datenbank version
private static final int DATABASE_VERSION = 1;
//Datenbankname
private static final String DATABASE_NAME = "contactsManager";
//Tabellenname
private static final String TABLE_CONTACTS = "contacts";
//Tabellenspalten
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";
public DatabaseHandler(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db){
String CREATE_CONTACTS_TABLE = "CREATE TABLE" + TABLE_CONTACTS + "("
+ KEY_ID + "INTEGER PRIMARY KEY," + KEY_NAME + "TEXT,"
+ KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
db.execSQL("DROP TABLE IF EXISTS" + TABLE_CONTACTS);
onCreate(db);
}
public void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone Number
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
public Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return contact
return contact;
}
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
}
}
Here is my MainActivity
package de.linde.sqlite;
import java.util.List;
import android.os.Bundle;
import android.util.Log;
import android.app.Activity;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DatabaseHandler db = new DatabaseHandler(this);
Log.d("Insert: ", "Inserting ..");
db.addContact(new Contact("Wladimir","024324324"));
db.addContact(new Contact("Max","0324324324"));
db.addContact(new Contact("Benny","0324324"));
db.addContact(new Contact("derSchwarze","051324324"));
Log.d("Reading: ","Reading all Contacts..");
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
String log = "Id: " + cn.getID() + " ,Name: " + cn.getName() + " ,Phone: " + cn.getPhoneNumber();
Log.d("Name: ", log);
}
}
}
My activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</RelativeLayout>
What I make wrong :(
Add spaces between the values that you add to CREATE_CONTACTS_TABLE and the concatenated string, so you build a valid table creation string:
"CREATE TABLE " + TABLE_CONTACTS + " (" + KEY_ID + " INTEGER PRIMARY KEY, " + KEY_NAME + " TEXT, " + KEY_PH_NO + " TEXT)";
You'll need to uninstall the app from the phone/emulator and then run it again to make the database to be recreated again.
The same thing is valid for the String in the onUpgrade method:
"DROP TABLE IF EXISTS " + TABLE_CONTACTS