Ive made a user register activity and it succesfully adds the user details to the database but now I am trying to get the user to be able to login with the same details but I have ran into a problem where I have a error in the code below saying comma or semi column needed but I dont think thats the correct answer to my problem. Can anyone see why my error would be happening? The error is where it says "SELECT * FROM" the from is the error and "WHERE" is the other error.
MainActivity class:
public class MainActivity extends AppCompatActivity {
SQLiteDatabase db;
SQLiteOpenHelper openHelper;
Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
openHelper = new DatabaseHelperUser(this);
db = openHelper.getReadableDatabase();
final EditText userEdit = findViewById(R.id.editTextUsername);
final EditText passwordEdit = findViewById(R.id.editTextTextPassword);
final Button loginBt = findViewById(R.id.buttonLogin);
loginBt.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String userEt = userEdit.getText().toString();
String userP = passwordEdit.getText().toString();
cursor = db.rawQuery("SELECT * FROM" + DatabaseHelperUser.TABLE_NAME + "WHERE" + DatabaseHelperUser.COL2 + "=? AND" + DatabaseHelperUser.COL3 + "=?", new String[]{userEt, userP});
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 = "UserNum";
public static final String COL2 = "UserName";
public static final String COL3 = "Password";
public static final String COL4 = "BirthDate";
public static final String COL5 = "Phone";
public static final String COL6 = "Address";
public DatabaseHelperUser(Context context){
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (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);
}
}
Please include the full text of the error in your question, but it looks to me like:
cursor = db.rawQuery("SELECT * FROM" + DatabaseHelperUser.TABLE_NAME
+ "WHERE" + DatabaseHelperUser.COL2 +
"=? AND" + DatabaseHelperUser.COL3 + "=?",
new String[]{userEt, userP});
I see that there is no trailing space after FROM, WHERE and AND, and since your TABLE_NAME etc does not have a leading space, FROMUser_tableWHEREUserName is going to be a syntax error.
You must add space to command FROM , WHERE, AND :
cursor = db.rawQuery("SELECT * FROM " + DatabaseHelperUser.TABLE_NAME + " WHERE " + DatabaseHelperUser.COL2 + "=? AND " + DatabaseHelperUser.COL3 + "=?", new String[]{userEt, userP});
Related
please suggest me solution for this code. It does not work. The application goes back after I pressed submit button. It can not store data
public class UserContract {
//if you need multi tabless user inner classes to represent each table inn class
public static abstract class NewUserinfo implements BaseColumns
{
public static final String USER_NAME="user_name"; //right side represent column name
public static final String USER_MOB="user_mob";
public static final String USER_EMAIL="user_email";
public static final String TABLE_NAME="user_info";
}
}
public class UserDbHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME="USERINFO.DB";
private static final int database_version=1;
private static final String create_query=
"CREATE TABLE "+ UserContract.NewUserinfo.TABLE_NAME + " ("+ UserContract.NewUserinfo.USER_NAME+" TEXT, "+
UserContract.NewUserinfo.USER_MOB+" TEXT,"+ UserContract.NewUserinfo.USER_EMAIL+" TEXT);";
public UserDbHelper(Context context)
{
super(context,DATABASE_NAME,null,database_version);
Log.e("database operation ","database created /opend");
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(create_query);
Log.e("database operation","table created");
}
public void addinformation(String name, String mob, String email, SQLiteDatabase db)
{
ContentValues contentValues=new ContentValues();
contentValues.put(UserContract.NewUserinfo.USER_NAME,name);
contentValues.put(UserContract.NewUserinfo.USER_MOB,mob);
contentValues.put(UserContract.NewUserinfo.USER_EMAIL,email);
db.insert(UserContract.NewUserinfo.TABLE_NAME,null,contentValues);
Log.e("database operation","one row insert");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}
public class NewContactActivity extends AppCompatActivity {
UserDbHelper userDbHelper;
SQLiteDatabase sqLiteDatabase;
EditText editText,editText1,editText2;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_contact);
editText=findViewById(R.id.contect_name);
editText1=findViewById(R.id.mob_number);
editText2=findViewById(R.id.email);
}
public void addcontact(View view)
{
String name= editText.getText().toString();
String number=editText1.getText().toString();
String email=editText2.getText().toString();
userDbHelper=new UserDbHelper(context);
sqLiteDatabase=userDbHelper.getWritableDatabase();
userDbHelper.addinformation(name,number,email,sqLiteDatabase);
Toast.makeText(getBaseContext(), "data saved", Toast.LENGTH_SHORT).show();
}
}
you require a primary key in one of the variables. say it like this.
String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + TITLE + " TEXT," + PRINT_NAME + " TEXT," + MRP + " TEXT," + QTY + " TEXT, " + IMAGE + " BLOB, " + WEIGHT + " TEXT " + ")";
db.execSQL(CREATE_TABLE);
}
The Overall Code Should Look Like...
public class SQLiteHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "Club100database";
private static final String TABLE_NAME = "myclub100cart";
private static final String KEY_ID = "cart_id";
private static final String TITLE = "title";
private static final String PRINT_NAME = "print_name";
private static final String MRP = "mrp";
private static final String QTY = "qty";
private static final String IMAGE = "image";
private static final String WEIGHT = "weight";
public SQLiteHandler(Context context) {
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + TITLE + " TEXT," + PRINT_NAME + " TEXT," + MRP + " TEXT," + QTY + " TEXT, " + IMAGE + " BLOB, " + WEIGHT + " TEXT " + ")";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL(" DROP TABLE " + TABLE_NAME);
onCreate(db);
}
}
As you mentioned error:
02-08 16:22:06.453 1994-1994/com.example.abbas.sqlitedatabase
E/dalvikvm: Could not find class
'android.graphics.drawable.RippleDrawable', referenced from method
android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering
Its not the issue of DataBase , its issue of Drawable Resource
Look into this
Could not find RippleDrawable
Could not find class 'android.graphics.drawable.RippleDrawable', Could not execute method for android:onClick, Android Studio
This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 5 years ago.
When I click Submit Button in Change password class or layout the app crashes. What's wrong with my code, please teach me! Thanks in Advance. I am working with Sqlite database for user login system and user can change their password from app bar layout. On clicking >>change password in App Bar new activity pops up i.e changePassword Activity. Upto here everything works fine but after typing password and clicking on submit button the app crashes and sets back to MainActivity.
Here is my change password class
public class changePasswordActivity extends AppCompatActivity {
EditText oldpasswordEditText;
EditText newpasswordEditText;
EditText confirmpasswordEditText;
Button btnsubmit;
String realusername, realpassword;
String checkoldpass, checknewpass, checkconfirmpass;
SQLiteHelper sqLiteHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_change_password);
oldpasswordEditText = findViewById(R.id.oldpasswordEditText);
newpasswordEditText = findViewById(R.id.newPasswordEditText);
confirmpasswordEditText = findViewById(R.id.confirmPasswordEditText);
btnsubmit= findViewById(R.id.btnsubmit);
checkoldpass = oldpasswordEditText.getText().toString();
checknewpass = newpasswordEditText.getText().toString();
checkconfirmpass = confirmpasswordEditText.getText().toString();
realusername = getIntent().getStringExtra("USERNAME");
realpassword= getIntent().getStringExtra("PASSWORD");
btnsubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!(checkconfirmpass.equals(checknewpass))) {
Toast.makeText(changePasswordActivity.this,"New Password didn't matched",Toast.LENGTH_SHORT).show();
}else if (!(realpassword.equals(checkoldpass))){
Toast.makeText(changePasswordActivity.this,"Old password didn't matched",Toast.LENGTH_SHORT).show();
}
else if (checkconfirmpass.equals(checkoldpass)){
Toast.makeText(changePasswordActivity.this,"New password cannot be same as old password",Toast.LENGTH_SHORT).show();
}else if(checkconfirmpass.equals(checknewpass.equals(checkoldpass))) {
Toast.makeText(changePasswordActivity.this, "New password cannot be same as old password", Toast.LENGTH_SHORT).show();
}
else{
sqLiteHelper = new SQLiteHelper(changePasswordActivity.this);
sqLiteHelper.changepassword(checknewpass,realusername);
}
}
});
}
}
Here is my SQLiteHelper class
public class SQLiteHelper extends SQLiteOpenHelper {
SQLiteDatabase db;
private static final String DATABASE_NAME = "info.db";
private static final int DATABASE_VERSION = 1;
public static final String TABLE_NAME = "profile";
public static final String COLUMN_ID = "userid";
public static final String COLUMN_FULLNAME = "fullname";
public static final String COLUMN_EMAIL = "email";
public static final String COLUMN_PASSWORD = "password";
public static final String COLUMN_MOBILE = "mobile";
private static final String CREATE_TABLE_QUERY =
"CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_FULLNAME + " TEXT, " +
COLUMN_EMAIL + " TEXT, " +
COLUMN_PASSWORD + " TEXT, " +
COLUMN_MOBILE + " TEXT " + ")";
//modified constructor
public SQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_QUERY);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public Cursor getData() {
String query = "SELECT * FROM" + TABLE_NAME;
Cursor data = db.rawQuery(query, null);
return data;
}
public void changepassword(String mpassword, String mname) {
Cursor cur= db.rawQuery("UPDATE "+SQLiteHelper.TABLE_NAME+" SET "
+SQLiteHelper.COLUMN_PASSWORD
+" = '"+mpassword+"' WHERE "+ SQLiteHelper.COLUMN_EMAIL+" = ?",new String[]{mname});
}
}
db will be null, there is also no need for a Cursor, so change
public void changepassword(String mpassword, String mname) {
Cursor cur= db.rawQuery("UPDATE "+SQLiteHelper.TABLE_NAME+" SET "
+SQLiteHelper.COLUMN_PASSWORD
+" = '"+mpassword+"' WHERE "+ SQLiteHelper.COLUMN_EMAIL+" = ?",new String[]{mname});
}
To :-
public void changepassword(String mpassword, String mname) {
SQLiteDatabase db = this.getWriteableDatabae();
db.rawQuery("UPDATE "+SQLiteHelper.TABLE_NAME+" SET "
+SQLiteHelper.COLUMN_PASSWORD
+" = '"+mpassword+"' WHERE "+ SQLiteHelper.COLUMN_EMAIL+" = ?",new String[]{mname});
}
You will also have the same issue with the getData method so you should add SQLiteDatabase db = this.getWriteableDatabae(); to the getData method as well.
Alternately you could change :-
public SQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
to :-
public SQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
db = this.getWriteableDatabase();
}
In which case db will be a valid SQLiteDatabase.
teH
I am trying to get started with SQLite databases. Unfortunately, on my onCreate method, my database is never getting created and crashing can anyone help me out.
Error I get is: No such table: firstdatabase.
This is my MySQLiteHelper class:
public class MySQLiteHelper extends SQLiteOpenHelper {
//Database instance
//private static MySQLiteHelper sInstance;
//Database name
private static final String DATABASE_NAME = "TestDB";
//Table name
private static final String TABLE_NAME = "firstdatabase";
//column names of the table
private static final String KEY_ID = "id";
private static final String KEY_ISBN = "isbn";
private static final String KEY_INGREDIENTS = "ingredients";
//Database Version
private static final int DATABASE_VERSION = 2;
// Log TAG for debugging purpose
private static final String TAG = "SQLiteAppLog";
//Method that will ensure only one instance of the database is created.
/* public static synchronized MySQLiteHelper getsInstance(Context context){
if(sInstance == null){
sInstance = new MySQLiteHelper(context.getApplicationContext());
}
return sInstance;
}
*/
// Constructor
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.d(TAG, "Inside SQLITEHELPER METHOD()");
}
#Override
public void onCreate(SQLiteDatabase db) {
//SQLite statement to create a table called 'TestDB'.
String CREATE_PROTOTYPE_TABLE = "CREATE TABLE " + TABLE_NAME + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_ISBN + " TEXT,"
+ KEY_INGREDIENTS + " TEXT" + ")";
Log.d(TAG, "DB created");
db.execSQL(CREATE_PROTOTYPE_TABLE);
//Log.d(TAG, "DB created");
}
// onUpdate() is invoked when you upgrade the database scheme.
// Don’t consider it seriously for the sample app.
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older prototype table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
this.onCreate(db);
}
public void addIngredientsToTable(Product product){
Log.d(TAG, "adding ingredients to table");
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ISBN, product.getIsbn());
values.put(KEY_ISBN, product.getIngredients());
db.insert(TABLE_NAME,null, values);
db.close();
}
//Method to get the ingredients list based on the isbn passed in.
public ArrayList<String> getIngredients(String isbn){
ArrayList<String> ingredientList = new ArrayList<String>();
String isbnPassedIn = isbn;
String query = "SELECT isbn, ingredients FROM " + TABLE_NAME + " WHERE isbn = " + isbnPassedIn;
//Getting instance to a readable database
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
if(cursor.moveToFirst()){
do{
ingredientList.add(cursor.getString(1));
ingredientList.add(cursor.getString(2));
}while (cursor.moveToFirst());
}
Log.d(TAG, "Inside getIngredients()");
return ingredientList;
}
//Method to get all the list of products in the datbase.
public ArrayList<Product> getAllProducts(){
ArrayList<Product> productList = new ArrayList<Product>();
String selectQuery = "SELECT * FROM firstdatabase";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery,null);
if(cursor.moveToFirst()){
do{
Product product = new Product();
product.setId(Integer.parseInt(cursor.getString(0)));
product.setIsbn(cursor.getString(1));
product.setIngredients(cursor.getString(2));
productList.add(product);
}while (cursor.moveToNext());
}
return productList;
}
Java file:
public class BarCodeActivity extends AppCompatActivity {
MySQLiteHelper db1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bar_code);
db1 = new MySQLiteHelper(this);
Log.d("Insert", "Inserting data...");
db1.addIngredientsToTable(new Product(1, "89470001033", "Lowfat yogurt, mango, milk, water"));
Log.d("Reading: ", "Reading all products");
ArrayList<Product> products = db1.getAllProducts();
for(Product product : products){
String log = "Id: " + product.getId() + ", ISBN: " + product.getIsbn() + ", Ingredients: " + product.getIngredients();
Log.d("Product:", log);
}
Your CREATE_PROTOTYPE_TABLE String is not correct, the semicolon is missing(;) :
Use the following:
String CREATE_PROTOTYPE_TABLE = "CREATE TABLE " + TABLE_NAME + "("
+ KEY_ID + " INTEGER PRIMARY KEY autoincrement," + KEY_ISBN + " TEXT,"
+ KEY_INGREDIENTS + " TEXT" + ");";
I have SQLite database file (which I did not create in this program, and it has its tables and datas), I open it in my android program, but when I write SELECT statement program can not find tables and I get error:
Error: no such table: Person
This is code:
public class SQLiteAdapter {
private DbDatabaseHelper databaseHelper;
private static String dbfile = "/data/data/com.example.searchpersons/databases/";
private static String DB_NAME = "Person.db";
static String myPath = dbfile + DB_NAME;
private static SQLiteDatabase database;
private static final int DATABASE_VERSION = 3;
private static String table = "Person";
private static Context myContext;
public SQLiteAdapter(Context ctx) {
SQLiteAdapter.myContext = ctx;
databaseHelper = new DbDatabaseHelper(SQLiteAdapter.myContext);
}
public static class DbDatabaseHelper extends SQLiteOpenHelper {
public DbDatabaseHelper(Context context) {
super(context, DB_NAME, null, DATABASE_VERSION);
dbfile = "/data/data/" + context.getPackageName() + "/databases/";
myPath = dbfile + DB_NAME;
//this.myContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
public SQLiteDatabase open() {
try {
database = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
Log.v("db log", "database exist open");
} catch (SQLiteException e) {
Log.v("db log", "database does't exist");
}
if (database != null && database.isOpen())
return database;
else {
database = databaseHelper.getReadableDatabase();
Log.v("db log", "database exist helper");
}
return database;
}
public Cursor onSelect(String firstname, String lastname) {
Log.v("db log", "database exist select");
Cursor c = database.rawQuery("SELECT * FROM " + table + " where Firstname='" + firstname + "' And Lastname='" + lastname + "'", null);
c.moveToFirst();
return c;
}
public void close() {
if (database != null && database.isOpen()) {
database.close();
}
}
}
And this is button click function:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button btn1 = (Button) rootView.findViewById(R.id.button1);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText t = (EditText) rootView.findViewById(R.id.editText1);
String name = t.getText().toString();
EditText tt = (EditText) rootView.findViewById(R.id.editText2);
String lastname = tt.getText().toString();
if (name.length() == 0 || lastname.length() == 0) {
Toast.makeText(rootView.getContext(), "Please fill both box", Toast.LENGTH_LONG).show();
} else {
GridView gridview = (GridView) rootView.findViewById(R.id.gridView1);
List < String > li = new ArrayList < String > ();
ArrayAdapter < String > adapter = new ArrayAdapter < String > (rootView.getContext(), android.R.layout.simple_gallery_item, li);
try {
SQLiteAdapter s = new SQLiteAdapter(rootView.getContext());
s.open();
Cursor c = s.onSelect(name, lastname);
if (c != null) {
if (c.moveToFirst()) {
do {
String id = c.getString(c.getColumnIndex("ID"));
String name1 = c.getString(c.getColumnIndex("Firstname"));
String lastname1 = c.getString(c.getColumnIndex("Lastname"));
String personal = c.getString(c.getColumnIndex("PersonalID"));
li.add(id);
li.add(name1);
li.add(lastname1);
li.add(personal);
gridview.setAdapter(adapter);
} while (c.moveToNext());
}
} else {
Toast.makeText(rootView.getContext(), "There is no data", Toast.LENGTH_LONG).show();
}
c.close();
s.close();
} catch (Exception e) {
Toast.makeText(rootView.getContext(), "Error : " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
});
return rootView;
}
I check database in SQLite Database Browser, everything is normal (There are tables and data), but program still can not find them.
I added sqlitemanager to eclipse and it can not see tables too:
There is only one table android_metadata and there are no my tables.
Can anyone help me?
I thought about it for about a week, the answer is very simple. I resolved the problem so:
from sqlitemanager
I added database from that button.
And now everything works fine ;)
In oncreate you have to create your db. I am sending you my db class.
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DbAdapter extends SQLiteOpenHelper {
private static DbAdapter mDbHelper;
public static final String DATABASE_NAME = "demoDb";
public static final String TABLE_Coin= "coin_table";
public static final String TABLE_Inbox= "inbox";
public static final String TABLE_Feature= "feature";
public static final String TABLE_Time= "time";
public static final String TABLE_Deduct_money= "deduct_time";
public static final String TABLE_Unread_message= "unread_message";
public static final String COLUMN_Email= "email";
public static final String COLUMN_Appearence= "appearence";
public static final String COLUMN_Drivability= "drivability";
public static final String COLUMN_Fuel= "fuel";
public static final String COLUMN_Insurance= "insurance";
public static final String COLUMN_Wow= "wow";
public static final String COLUMN_CurrentValue= "current_value";
public static final String COLUMN_coin = "name";
public static final String COLUMN_seenTime = "seen";
public static final String COLUMN_number_of_times = "number_of_times";
public static final String COLUMN_name = "name";
public static final String COLUMN_type = "type";
public static final String COLUMN_text = "text";
public static final String COLUMN_image = "image";
public static final String COLUMN_created_time = "created_time";
public static final String COLUMN_unread = "unread";
// ****************************************
private static final int DATABASE_VERSION = 1;
private final String DATABASE_CREATE_BOOKMARK = "CREATE TABLE "
+ TABLE_Coin + "(" + COLUMN_coin
+ " Varchar,"+COLUMN_Email +" Varchar, UNIQUE("
+ COLUMN_Email + ") ON CONFLICT REPLACE)";
private final String DATABASE_CREATE_BOOKMARK1 = "CREATE TABLE "
+ TABLE_Feature + "(" + COLUMN_Appearence
+ " Integer,"+COLUMN_Email +" Varchar ,"+COLUMN_name +" Varchar ,"+COLUMN_Drivability +" Integer ,"+COLUMN_Wow +" Integer,"+COLUMN_CurrentValue +" Integer,"+COLUMN_Fuel +" Integer,"+COLUMN_Insurance +" Integer, UNIQUE("
+ COLUMN_Email + ") ON CONFLICT REPLACE)";
private final String DATABASE_CREATE_BOOKMARK2 = "CREATE TABLE "
+ TABLE_Time + "(" + COLUMN_Email +" Varchar ,"+COLUMN_seenTime +" Integer,"+COLUMN_number_of_times +" Integer, UNIQUE("
+ COLUMN_Email + ") ON CONFLICT REPLACE)";
private final String DATABASE_CREATE_BOOKMARK3 = "CREATE TABLE "
+ TABLE_Deduct_money + "(" + COLUMN_seenTime
+ " Varchar,"+ COLUMN_number_of_times
+ " Integer,"+COLUMN_Email +" Varchar, UNIQUE("
+ COLUMN_Email + ") ON CONFLICT REPLACE)";
private final String DATABASE_CREATE_BOOKMARK4 = "CREATE TABLE "
+ TABLE_Inbox + "(" + COLUMN_created_time
+ " DATETIME,"+ COLUMN_image
+ " Varchar,"
+ COLUMN_type
+ " Varchar,"+ COLUMN_name
+ " Varchar,"+ COLUMN_text
+ " Varchar,"+COLUMN_Email +" Varchar)";
private final String DATABASE_CREATE_BOOKMARK5 = "CREATE TABLE "
+ TABLE_Unread_message + "(" + COLUMN_unread
+ " Varchar,"+COLUMN_Email +" Varchar, UNIQUE("
+ COLUMN_Email + ") ON CONFLICT REPLACE)";
private DbAdapter(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static synchronized DbAdapter getInstance(Context context) {
if (mDbHelper == null) {
mDbHelper = new DbAdapter(context);
}
return mDbHelper;
}
/**
* Tries to insert data into table
*
* #param contentValues
* #param tablename
* #throws SQLException
* on insert error
*/
public void insertQuery(ContentValues contentValues, String tablename)
throws SQLException {
try {
final SQLiteDatabase writableDatabase = getWritableDatabase();
writableDatabase.insert(tablename, null, contentValues);
// writableDatabase.insertWithOnConflict(tablename, null,
// contentValues,SQLiteDatabase.CONFLICT_REPLACE);
} catch (Exception e) {
e.printStackTrace();
}
}
// public void insertReplaceQuery(ContentValues contentValues, String tablename)
// throws SQLException {
//
// try {
// final SQLiteDatabase writableDatabase = getWritableDatabase();
// writableDatabase.insertOrThrow(tablename, null, contentValues);
//
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
//
// /**
// * Update record by ID with contentValues
// *
// * #param id
// * #param contentValues
// * #param tableName
// * #param whereclause
// * #param whereargs
// */
public void updateQuery(ContentValues contentValues, String tableName,
String whereclause, String[] whereargs) {
try {
final SQLiteDatabase writableDatabase = getWritableDatabase();
writableDatabase.update(tableName, contentValues, whereclause,
whereargs);
} catch (Exception e) {
e.printStackTrace();
}
}
public Cursor fetchQuery(String query) {
final SQLiteDatabase readableDatabase = getReadableDatabase();
final Cursor cursor = readableDatabase.rawQuery(query, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
public Cursor fetchQuery(String query, String[] selectionArgs) {
final SQLiteDatabase readableDatabase = getReadableDatabase();
final Cursor cursor = readableDatabase.rawQuery(query, selectionArgs);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
public void delete(String table) {
final SQLiteDatabase writableDatabase = getWritableDatabase();
writableDatabase.delete(table, null, null);
}
public void delete(String table, String whereClause, String[] selectionArgs) {
final SQLiteDatabase writableDatabase = getWritableDatabase();
writableDatabase.delete(table, whereClause, selectionArgs);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE_BOOKMARK);
db.execSQL(DATABASE_CREATE_BOOKMARK1);
db.execSQL(DATABASE_CREATE_BOOKMARK2);
db.execSQL(DATABASE_CREATE_BOOKMARK3);
db.execSQL(DATABASE_CREATE_BOOKMARK4);
db.execSQL(DATABASE_CREATE_BOOKMARK5);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Coin);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Feature);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Time);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Deduct_money);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Inbox);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Unread_message);
onCreate(db);
}
}
You are messing up the paths.
Please clean up every definition or reference to dbfile and myPath.You are initializing them in the definition with some values (probably copy-pasted), then giving them new different values in the DbDatabaseHelper constructor. And the helper will not use these paths, it will just create the database in the default directory.
Then after this, in the open method you are calling SQLiteDatabase.openDatabase with your intended paths. Use instead getReadableDatabase and getWritableDatabase from the Helper.
I built an app that so far manages to ADD text to a database (cannot verify yet but I killed the FC). However, when I try to read from the database it FCs because I'm unsure of how to use the Cursor object. I read the documentation and it confuses me more. I have a database with table "records" and a single column "texts". While my project manages to input text into the database (via an EditText), I'm trying unsuccessfully to return all the database entries from this "texts" column into a textView.
DB Helper inner-class:
private class dbHelper extends SQLiteOpenHelper {
public dbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
System.out.println("create statement"+SQL_CREATE_ENTRIES);
try
{
db.execSQL(SQL_CREATE_ENTRIES);
}catch(SQLiteException sql)
{
sql.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS records");
onCreate(db);
}
public void addRecord(String t) {
ContentValues values = new ContentValues(1);
values.put(RECORDS_COLUMN_TEXTS,t);
getWritableDatabase().insert(TABLE_NAME, RECORDS_COLUMN_TEXTS, values);
}
public Cursor getRecords() {
return getWritableDatabase().rawQuery("select * from " + TABLE_NAME, null);
}
}
Within main class:
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "CSCI598";
private static final String TABLE_NAME = "records";
public static final String RECORDS_COLUMN_TEXTS = "texts";
private dbHelper openHelper;
private static final String SQL_CREATE_ENTRIES = "CREATE TABLE " + TABLE_NAME + "(" + RECORDS_COLUMN_TEXTS + " TEXT PRIMARY KEY AUTOINCREMENT" + ");";
public void onClick(View v) {
TextView tv=(TextView)findViewById(R.id.textView1);
EditText et=(EditText)findViewById(R.id.editText1);
openHelper = new dbHelper(this);
switch(v.getId()) {
case R.id.fetch1:
Cursor cursor = openHelper.getRecords();
StringBuffer sb = new StringBuffer();
cursor.moveToFirst();
while(cursor.moveToNext()) {
sb.append(cursor.getString(0) + "\n");
}
tv.setText(sb.toString());
break;
case R.id.append1:
String txt=et.getText().toString();
openHelper.addRecord(txt);
break;
}
logcat: http://pastebin.com/mqUn6g7P
As you can see, I'm probably trying something very stupid with the action for clicking the fetch button, ie. "openHelper.getRecords().toString()" attempting to convert all that Cursor returns to string. How can I go about this alternately in the simplest fashion?
Ok First you have get the strings from the Cursor by doing this
Cursor cursor = openHelper.getRecords();
StringBuffer sb = new StringBuffer();
while(cursor.moveToNext()) {
sb.append(cursor.getString(0) + "\n");
}
Then you can set it to the textView
tv.setText(sb.toString);
This should work actually
.Replace this part of your code
case R.id.fetch1:
tv.setText(openHelper.getRecords().toString());
break;
With this
case R.id.fetch1:
Cursor cursor = openHelper.getRecords();
StringBuffer sb = new StringBuffer();
while(cursor.moveToNext()) {
sb.append(cursor.getString(0) + "\n");
}
tv.setText(sb.toString);
break;
Also remove autoincrement for Text when you create the table
Replace this:
private static final String SQL_CREATE_ENTRIES = "CREATE TABLE " + TABLE_NAME + "(" + RECORDS_COLUMN_TEXTS + " TEXT PRIMARY KEY AUTOINCREMENT" + ");";
With this:
private static final String SQL_CREATE_ENTRIES = "CREATE TABLE " + TABLE_NAME + "(" + RECORDS_COLUMN_TEXTS + " TEXT" + ")";
Also Add table name in the constructor instead of database name. Change this:
public dbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
To this:
public dbHelper(Context context) {
super(context, TABLE_NAME, null, DATABASE_VERSION);
}