i am very new to databases so i was looking at some guides online and started to try making my own database. For some reason my add method isnt working and i cant figure out why
This is my database class
public class DBHandler extends SQLiteOpenHelper{
// Database Version
private static final int DATABASE_VERSION = 2;
// Database Name
private static final String DATABASE_NAME = "DictionaryInfo";
// Contacts table name
private static final String TABLE_WORDS = "Words";
// Shops Table Columns names
private static final String KEY_ID ="id";
private static final String KEY_WORD = "word";
private static final String KEY_MEANING = "meaning";
private static final String CREATE_WORDS_TABLE = "CREATE TABLE " + TABLE_WORDS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_WORD + " TEXT," + KEY_MEANING + " TEXT " + ")";
public DBHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_WORDS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORDS);
onCreate(db);
}
public void addWord(Word word){
SQLiteDatabase db = this.getReadableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID,word.getId());
values.put(KEY_WORD,word.getWord());
values.put(KEY_MEANING,word.getMeaning());
db.insert(TABLE_WORDS,null,values);
db.close();
}
public Word getWord(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_WORDS,null,KEY_ID + " = ?",new String[]{String.valueOf(id)},null,null,null);
if (cursor != null)
cursor.moveToFirst();
Word word = new Word(Integer.parseInt(cursor.getString(0)),cursor.getString(1),cursor.getString(2));
return word;
}
}
This is my "word" class
public class Word {
int _id;
String word;
String meaning;
public Word(int id,String word, String meaning)
{
this._id = id;
this.word = word;
this.meaning = meaning;
}
public int getId() {
return this._id;
}
public void setId(int id) {
this._id = id;
}
public String getMeaning() {
return this.meaning;
}
public void setMeaning(String meaning) {
this.meaning = meaning;
}
public String getWord() {
return this.word;
}
public void setWord(String word) {
this.word = word;
}
}
This is my mainActivity
public class MainActivity extends AppCompatActivity {
TextView tv1;
TextView tv2;
TextView tv3;
TextView tv4;
Button btn1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView)findViewById(R.id.tv1);
tv2 = (TextView)findViewById(R.id.tv2);
tv3 = (TextView)findViewById(R.id.tv3);
tv4 = (TextView)findViewById(R.id.tv4);
btn1 = (Button)findViewById(R.id.btn1);
DBHandler db = new DBHandler(this);
db.addWord(new Word(1,"abc","def"));
Word word = db.getWord(1);
tv1.setText(word.getWord());
tv2.setText(word.getMeaning());
}
}
I tried pulling out the values out of the database and insert them into a textview to check if its working but by the logcat i can obviously see that its caused somewhere in the insert process.
My logcat
com.example.android.psydictionary E/SQLiteLog: (1555) abort at 10 in [INSERT INTO Words(meaning,word,id) VALUES (?,?,?)]: UNIQUE constraint failed: Words.id
11-19 12:34:44.875 17853-17853/com.example.android.psydictionary E/SQLiteDatabase: Error inserting meaning=def word=abc id=1
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: Words.id (code 1555)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:784)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1471)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at com.example.android.psydictionary.DBHandler.addWord(DBHandler.java:51)
at com.example.android.psydictionary.MainActivity.onCreate(MainActivity.java:31)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2311)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2420)
at android.app.ActivityThread.access$900(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5294)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
UNIQUE constraint failed says what the problem is. You have a UNIQUE constraint on a column (meaning,words,id) and try to INSERT the same value twice in that column.
It is most likely the id that fails. Maybe you can just leave it and it gets calculated during insert. Otherwise, check your testdata.
Related
DatabaseHelperClass.java
This is the database helper class for creating the database in android. But it is not working as I see in the android logcat. It is unable to point location column in database. Please advise if I made any mistake in the below mention classes.
public class DatabaseHelperClass extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "metrolines.db";
public DatabaseHelperClass(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
/* CREATE CLASS */
db.execSQL(Station.CREATE_TABLE);
Log.d("Create Table", "Passed this step");
Insert_Station(new Station("Uttam Nagar East","West Delhi"));
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
/* DROP TABLE IF EXIST */
db.execSQL("DROP TABLE IF EXISTS " + Station.TABLE_NAME);
/* CREATE TABLES AGAIN */
onCreate(db);
}
public void Insert_Station(Station station) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Station.STATION_NAME, station.getD_Station());
contentValues.put(Station.STATION_LOCATION, station.getD_Location());
db.insert(Station.TABLE_NAME, null, contentValues);
db.close();
}
public List<Station> getStationList() {
List<Station> stationList = new ArrayList<Station>();
//StationList
String SELECT_QUERY = "SELECT * FROM " + Station.TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(SELECT_QUERY, null);
if (cursor.moveToFirst()) {
do {
Station station = new Station();
station.setD_Station(cursor.getString(1));
station.setD_Location(cursor.getString(2));
stationList.add(station);
} while (cursor.moveToNext());
}
return stationList;
}}
Station.java
public class Station {
public static final String TABLE_NAME = "STATION_TABLE";
public static final String STATION_NAME = "Station_name" ;
public static final String STATION_LOCATION = "Location_name" ;
private String D_Station;
private String D_Location;
//create table SQL Query
public static final String CREATE_TABLE =
"CREATE TABLE STATION_TABLE (ID INTEGER PRIMARY KEY AUTOINCREMENT, Station_name TEXT, Location_name TEXT)";
public Station(){
}
public Station(String d_Station, String d_Location) {
D_Station = d_Station;
D_Location = d_Location;
}
public String getD_Station() {
return D_Station;
}
public void setD_Station(String d_Station) {
D_Station = d_Station;
}
public String getD_Location() {
return D_Location;
}
public void setD_Location(String d_Location) {
D_Location = d_Location;
}
}
MainActiviy.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DatabaseHelperClass db = new DatabaseHelperClass(this);
Log.d("Insert", "Inserting");
db.Insert_Station(new Station("Uttam Nagar East", "West Delhi"));
db.Insert_Station(new Station("Dwarka Sec 9", "West Delhi"));
db.Insert_Station(new Station("Rajiv Chowk", "Central Delhi"));
db.Insert_Station(new Station("Hauz Khas", "South Delhi"));
Logcat
2020-03-20 09:51:54.330 29987-29987/com.gauravbhagat.meg D/Insert: Inserting
2020-03-20 09:51:54.389 29987-29987/com.gauravbhagat.meg E/SQLiteLog: (1) table STATION_TABLE has no column named Location_name
2020-03-20 09:51:54.436 29987-29987/com.gauravbhagat.meg E/SQLiteDatabase: Error inserting Location_name=West Delhi Station_name=Uttam Nagar East
android.database.sqlite.SQLiteException: table STATION_TABLE has no column named Location_name (code 1 SQLITE_ERROR[1]): , while compiling: INSERT INTO STATION_TABLE(Location_name,Station_name) VALUES (?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1229)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:703)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:59)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:2019)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1890)
at com.gauravbhagat.meg.SQliteDataBase.DatabaseHelperClass.Insert_Station(DatabaseHelperClass.java:48)
at com.gauravbhagat.meg.MainActivity.onCreate(MainActivity.java:64)
at android.app.Activity.performCreate(Activity.java:7340)
at android.app.Activity.performCreate(Activity.java:7331)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1275)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3106)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3269)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1960)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7094)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)
I am trying to retrieve my email from my SQLiteDbHelper and view it in a TextView in another activity after I click sign in, using the WelcomeActivity or splash activity since I only want it to be view for 4 seconds, but idk whats the problem when I sign in it crashes me out.
DataBaseHelper.java
public class DataBaseHelper extends SQLiteOpenHelper
{
private DataBaseHelper dbHelper;
public static SQLiteDatabase m_db;
public static final String DB_NAME = "users.dbHelper";
public static final int DB_VERSION = 1;
public static final String TABLE_USERS = "users";
public static final String COLUMN_EMAIL = "email";
public static final String COLUMN_PASSWORD = "password";
public static final String [] ALL_COLUMNS = {COLUMN_EMAIL, COLUMN_PASSWORD};
public static final String SQL_CREATE =
"CREATE TABLE IF NOT EXISTS " + TABLE_USERS + " (" +
COLUMN_EMAIL + " STRING PRIMARY KEY, " +
COLUMN_PASSWORD + " STRING);";
public static final String SQL_DROP = "DROP TABLE " + TABLE_USERS;
public DataBaseHelper(#Nullable Context context)
{
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(SQL_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL(SQL_DROP);
onCreate(db);
}
//---opens the database---
public DataBaseHelper open() throws SQLException
{
m_db = dbHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
if (m_db != null)
m_db.close();
if (dbHelper != null)
dbHelper.close();
}
// Inserting in database
public boolean insert(String email, String password)
{
m_db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("email", email);
contentValues.put("password", password);
long ins = m_db.insert(TABLE_USERS, null, contentValues);
if (ins == -1) return false;
else return true;
}
// Checking if email exists
public boolean checkEmail(String COLUMN_EMAIL)
{
m_db = this.getWritableDatabase();
Cursor cursor = m_db.rawQuery("select * from TABLE_USERS where COLUMN_EMAIL=?",
new String[]{COLUMN_EMAIL});
if (cursor.getCount() > 0) return false;
else return true;
}
// Checking the email and password
public boolean checkEmailPassword(String COLUMN_EMAIL, String COLUMN_PASSWORD)
{
m_db = this.getWritableDatabase();
Cursor cursor = m_db.rawQuery("select * from TABLE_USERS where COLUMN_EMAIL=?
and COLUMN_PASSWORD=?", new String[]{COLUMN_EMAIL, COLUMN_PASSWORD});
if (cursor.getCount() > 0) return true;
else return false;
}
public String getEmail(String COLUMN_EMAIL)
{
m_db = this.getReadableDatabase();
Cursor cursor = m_db.query(TABLE_USERS, new String[]{COLUMN_EMAIL}, null, null,
null, null, null);
cursor.moveToFirst();
String user = cursor.getString(cursor.getColumnIndex(COLUMN_EMAIL));
cursor.close();
return user;
}
}
WelcomeActivity.Java
public class WelcomeActivity extends AppCompatActivity
{
private static int SPLASH_TIME_OUT = 4000;
private DataBaseHelper db;
private SQLiteDatabase m_db;
private TextView tvEmail2;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
db = new DataBaseHelper(this);
TextView tvEmail = findViewById(R.id.tvEmail2);
String email = db.getEmail(DataBaseHelper.COLUMN_EMAIL);
String user = email;
tvEmail.setText(Users.class.getEm);
new Handler().postDelayed(new Runnable()
{
#Override
public void run()
{
Intent intent = new Intent(WelcomeActivity.this, EthicsActivity.class);
startActivity(intent);
finish();
}
}, SPLASH_TIME_OUT);
}
}
Users.java
public class Users
{
private String email;
private String password;
public Users() {}
public Users(String email, String password)
{
this.email = email;
this.password = password;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
#Override
public String toString()
{
return "Users{" +
"email='" + email + '\'' +
", password='" + password + '\'' +
'}';
}
}
What do you guys think about this?
I am trying to retrieve my email from my SQLiteDbHelper and view it in a TextView in another activity after I click sign in, using the WelcomeActivity or splash activity since I only want it to be view for 4 seconds, but idk whats the problem when I sign in it crashes me out.
I believe that you have a number of issues.
The line tvEmail.setText(Users.class.getEm); won't compilem I believe that instead want tvEmail.setText(user); or tvEmail.setText(email); (you don't need to have both email and user Strings having the same value).
Assuming that EthicsActivity is a valid working activity, and that there is an appropriate activity entry in the manifest AndroidManifest.xml then the issue is that you would get an error along the lines of :-
11-10 19:56:12.863 1170-1170/so53240174.so53240174 E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{so53240174.so53240174/so53240174.so53240174.WelcomeActivity}: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
at android.database.AbstractCursor.checkPosition(AbstractCursor.java:418)
at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
at so53240174.so53240174.DataBaseHelper.getEmail(DataBaseHelper.java:96)
at so53240174.so53240174.WelcomeActivity.onCreate(WelcomeActivity.java:25)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
This is saying that the Cursor is empty so you cannot get any data from it and it happens at the line String user = cursor.getString(cursor.getColumnIndex(COLUMN_EMAIL)); which is in the getEmail method as indicated by the line in the log :-
at so53240174.so53240174.DataBaseHelper.getEmail(DataBaseHelper.java:96)
The reason why this is happening is that a) there are no rows in the users table and b) that the Cursor moveToFirst method's result isn't checked. Instead an assumption is made that it will always move to the first row in the Cursor.
Instead of the getEmail method being :-
public String getEmail(String COLUMN_EMAIL)
{
m_db = this.getReadableDatabase();
Cursor cursor = m_db.query(TABLE_USERS, new String[]{COLUMN_EMAIL}, null, null,
null, null, null);
cursor.moveToFirst(); //<<<<<<<<<< WRONG
String user = cursor.getString(cursor.getColumnIndex(COLUMN_EMAIL));
cursor.close();
return user;
}
It could be :-
public String getEmail(String COLUMN_EMAIL) {
String user = "No Email Found."; //<<<<<<<<<< Default value in case of empty table
m_db = this.getReadableDatabase();
Cursor cursor = m_db.query(TABLE_USERS, new String[]{COLUMN_EMAIL}, null, null,
null, null, null);
if (cursor.moveToFirst()) { //<<<<<<<<<< checks result of the move
user = cursor.getString(cursor.getColumnIndex(COLUMN_EMAIL));
}
cursor.close();
return user;
}
Of course applying this fix, unless a row is added to the users table will always result in the TextView displaying No Email Found. If there are multiple rows then it will display the email from one of the rows, not necessarily a specific row.
Adding the line db.insert("fred#fredmail.com","1234567890"); before the value is retrieved using the call to the getEmail results in fred#fredmail.com being displayed in the TextView.
I'm trying to login using the database by using the id of the specific members.
But the app crashes with log error.
Following various other similar errors, I included "c1.movetoFirst();" and "c2.movetoFirst();". But still its not working.
The logcat error is:
FATAL EXCEPTION: main
Process: no.nordicsemi.android.nrftoolbox, PID: 13196
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:4785)
at android.view.View$PerformClick.run(View.java:19888)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5276)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:911)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:706)
Caused by: java.lang.reflect.InvocationTargetException
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick
Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
at android.database.AbstractCursor.checkPosition(AbstractCursor.java:432)
at android.database.AbstractWindowedCursor.checkPosition
at android.database.AbstractWindowedCursor.getInt
at no.nordicsemi.android.nrftoolbox.LoginActivity.login
The LoginActivity is :
public class LoginActivity extends AppCompatActivity {
TextView email;
TextView pass;
private no.nordicsemi.android.nrftoolbox.myDbAdapter mydb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
email = (TextView) findViewById(R.id.editText_mail);
pass = (TextView) findViewById(R.id.editText_pass);
mydb = new no.nordicsemi.android.nrftoolbox.myDbAdapter(this);
}
public void register(View v) {
Intent goToSecond = new Intent();
goToSecond.setClass(this, Register_Page.class);
startActivity(goToSecond);
}
public void login(View v) {
Cursor c1 = mydb.getEmail(email);
c1.moveToFirst();
Cursor c2 = mydb.getpass(pass);
c2.moveToFirst();
int id1=c1.getInt(0);
int id2=c2.getInt(0);
if (id1>0 & id2>0) {
Intent goToSecond = new Intent();
goToSecond.setClass(this, Profile.class);
startActivity(goToSecond);
} else
message(getApplicationContext(), "not valid user");
}
}
The myDbHelper is:
public class myDbAdapter extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 4;
public static final String DATABASE_NAME = "MyDBName.db";
public static final String CONTACTS_TABLE_NAME = "contacts";
public static final String CONTACTS_COLUMN_ID = "id";
public static final String CONTACTS_COLUMN_NAME = "name";
public static final String CONTACTS_COLUMN_EMAIL = "email";
public static final String CONTACTS_COLUMN_PASS = "password";
public static final String CONTACTS_COLUMN_DOB = "dateofbirth";
public static final String CONTACTS_COLUMN_GENDER = "gender";
public static final String CONTACTS_COLUMN_PHONE="phone";
public static final String CONTACTS_COLUMN_CITY="city";
public static final String CONTACTS_COLUMN_WALLET="wallet";
private HashMap hp;
public myDbAdapter(Context context) {
super(context, DATABASE_NAME , null, 4);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"CREATE TABLE " + CONTACTS_TABLE_NAME + "(" + CONTACTS_COLUMN_ID + " INTEGER PRIMARY KEY," + CONTACTS_COLUMN_NAME + " TEXT," + CONTACTS_COLUMN_EMAIL + " TEXT," + CONTACTS_COLUMN_PASS +" TEXT," + CONTACTS_COLUMN_DOB + " TEXT," + CONTACTS_COLUMN_GENDER + " TEXT," + CONTACTS_COLUMN_PHONE + " INTEGER," + CONTACTS_COLUMN_CITY + " TEXT,"+CONTACTS_COLUMN_WALLET + " INTEGER DEFAULT 0);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
public boolean insertContact (String name, String email, String pass, String dob, String gender, String phone, String city) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("email", email);
contentValues.put("password", pass);
contentValues.put("dateofbirth", dob);
contentValues.put("gender", gender);
contentValues.put("phone", phone);
contentValues.put("city", city);
db.insert("contacts", null, contentValues);
return true;
}
//Cursor csr = no.nordicsemi.android.nrftoolbox.CommonSQLiteUtilities.getAllRowsFromTable(db,"contacts",true,null)
//no.nordicsemi.android.nrftoolbox.CommonSQLiteUtilities.LogCursorData(csr);
public int updateWallet(String amount,Integer id)
{
SQLiteDatabase db=this.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put("wallet",amount);
return(db.update("contacts",contentValues,"id = ? ",new String[] { Integer.toString(id)}));
}
public Cursor getData(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts where id="+id+"", null );
return res;
}
public Cursor getEmail(TextView email)
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor= db.rawQuery( "select id from contacts where email='"+email.getText().toString()+"'",null);
return cursor;
}
public Cursor getpass(TextView pass)
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor= db.rawQuery( "select id from contacts where password='"+pass.getText().toString()+"'",null);
return cursor;
}
}
Where is the error? And how can it be recitified?
You better check whether cursor has next before invoking movetoFirst as in
Cursor c1 = mydb.getEmail(email);
if(c1.getcount() > 0)
c1.moveToFirst();
and make sure, email id is already in database and check for case sensitive.
This question already has answers here:
When does SQLiteOpenHelper onCreate() / onUpgrade() run?
(15 answers)
Closed 5 years ago.
Im having some troubles trying to get the info stored in my database and showing it in a ListView.
When I start the application it crashes.
My MainActivity:
private ListViewAdapter adapter;
private ArrayList<ListItem> itemList;
private ListView list;
private DatabaseAdapter receptDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
setupButton();
setupListView();
setupDatabase();
addObject();
}
private void setupDatabase() {
receptDB = new DatabaseAdapter(this);
receptDB.open();
refreshListView();
}
private void setupButton() {
Button addItemButton = (Button) findViewById(R.id.addItemButton);
addItemButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
buttonClicked();
}
});
}
private void buttonClicked() {
//get EditText
Intent newItemIntent = new Intent(List_Page.this, Add_Object.class);
startActivity(newItemIntent);
finish();
}
private void setupListView() {
itemList = new ArrayList<ListItem>();
adapter = new ListViewAdapter(List_Page.this, itemList);
list = (ListView) findViewById(R.id.listItem);
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
return true;
}
});
View header = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.activity_list_item, null);
list.addHeaderView(header);
list.setAdapter(adapter);
}
private void addObject(){
Intent intent = getIntent();
if (intent.hasExtra(Constants.KEY_RECEPT_NAME)) {
String name = intent.getExtras().getString(Constants.KEY_RECEPT_NAME);
String kategory = intent.getExtras().getString(Constants.KEY_KATEGORY);
String ingredients = intent.getExtras().getString(Constants.KEY_INGREDIENTS);
String directions = intent.getExtras().getString(Constants.KEY_DIRECTIONS);
Bitmap image = (Bitmap) intent.getParcelableExtra(Constants.KEY_IMAGE);
//byte[] imageBytes = getBytes(image);
ListItem newObject = new ListItem(name,kategory,ingredients,directions, image);
//itemList.add(newObject);
receptDB.insertReceptItem(newObject);
refreshListView();
}
}
private void refreshListView() {
Cursor cursor = receptDB.getAllRows();
String[] fromFieldNames = new String[] {DatabaseAdapter.KEY_NAME, DatabaseAdapter.KEY_KATEGORY};
int[] toViewIDs = new int[] {R.id.receptName, R.id.kategory};
SimpleCursorAdapter myCursorAdapter;
myCursorAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.activity_list_item, cursor, fromFieldNames, toViewIDs, 0);
ListView myList = (ListView) findViewById(R.id.listItem);
myList.setAdapter(myCursorAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onDestroy() {
super.onDestroy();
receptDB.close();
}
Database:
public class DatabaseAdapter {
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "receptlist.db";
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_TABLE = "receptlistitems";
public static final String KEY_ID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_KATEGORY = "kategory";
public static final String KEY_INGREDIENTS = "ingredients";
public static final String KEY_DIRECTIONS = "directions";
//bitmap?
public static final int COLUMN_NAME_INDEX = 1;
public static final int COLUMN_KATEGORY_INDEX = 2;
public static final int COLUMN_INGREDIENTS_INDEX = 3;
public static final int COLUMN_DIRECTIONS_INDEX = 4;
public static final String[] ALL_KEYS = new String[] {KEY_ID, KEY_NAME, KEY_KATEGORY, KEY_INGREDIENTS, KEY_DIRECTIONS};
private static final String DATABASE_CREATE = "create table "
+ DATABASE_TABLE + " (" + KEY_ID
+ " integer primary key autoincrement, " + KEY_NAME
+ " text not null, " + KEY_KATEGORY
+ " text, " + KEY_INGREDIENTS
+ " text not null, " + KEY_DIRECTIONS
+ " text not null);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DatabaseAdapter(Context context) {
this.context = context;
DBHelper = new DatabaseHelper(context);
}
public DatabaseAdapter open(){
db = DBHelper.getWritableDatabase();
return this;
}
public void close(){
DBHelper.close();
}
//Neue Liste von Daten in Datenbank
public long insertReceptItem(ListItem item) {
ContentValues itemValues = new ContentValues();
itemValues.put(KEY_NAME, item.getName());
itemValues.put(KEY_KATEGORY,item.getKategory());
itemValues.put(KEY_INGREDIENTS, item.getIngredients());
itemValues.put(KEY_DIRECTIONS, item.getDirection());
//Speichern in die Datenbank
return db.insert(DATABASE_TABLE, null, itemValues);
}
//Löschen eines Items durch den primary Key
public boolean deleteItem(long itemID){
String where = KEY_ID + "=" + itemID;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ID);
if (c.moveToFirst()) {
do {
deleteItem(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
//Zurückgeben aller Daten in der Datenbank
public Cursor getAllRows(){
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null,null,null,null,null);
if (c != null) c.moveToFirst();
return c;
}
//Auf bestimmte Reihe zugreifen
public Cursor getRow(long rowId){
String where = KEY_ID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null,null,null,null,null);
if (c != null) c.moveToFirst();
return c;
}
private static class DatabaseHelper extends SQLiteOpenHelper{
DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
Logcat:
08-12 16:41:11.161 20386-20386/de.ur.mi.android.excercises.starter E/SQLiteLog: (1) no such column: ingredients
08-12 16:41:11.163 20386-20386/de.ur.mi.android.excercises.starter D/AndroidRuntime: Shutting down VM
08-12 16:41:11.164 20386-20386/de.ur.mi.android.excercises.starter E/AndroidRuntime: FATAL EXCEPTION: main
Process: de.ur.mi.android.excercises.starter, PID: 20386
java.lang.RuntimeException: Unable to start activity ComponentInfo{de.ur.mi.android.excercises.starter/de.ur.mi.android.excercises.starter.List_Page}: android.database.sqlite.SQLiteException: no such column: ingredients (code 1): , while compiling: SELECT DISTINCT _id, name, kategory, ingredients, directions FROM receptlistitems
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2720)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2781)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1508)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:241)
at android.app.ActivityThread.main(ActivityThread.java:6274)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: android.database.sqlite.SQLiteException: no such column: ingredients (code 1): , while compiling: SELECT DISTINCT _id, name, kategory, ingredients, directions FROM receptlistitems
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:895)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:506)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1318)
at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1165)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1036)
at de.ur.mi.android.excercises.starter.DatabaseAdapter.getAllRows(DatabaseAdapter.java:96)
at de.ur.mi.android.excercises.starter.List_Page.refreshListView(List_Page.java:109)
at de.ur.mi.android.excercises.starter.List_Page.setupDatabase(List_Page.java:51)
at de.ur.mi.android.excercises.starter.List_Page.onCreate(List_Page.java:42)
at android.app.Activity.performCreate(Activity.java:6720)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2673)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2781)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1508)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:241)
at android.app.ActivityThread.main(ActivityThread.java:6274)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Thanks in advance!
If you change anything in the database schema (like adding a column), you have to increase the Database version in SQLiteOpenHelper. If you increase the value of the version you will get a callback to onUpgrade and you have to handle that database change there.
private static class DatabaseHelper extends SQLiteOpenHelper{
DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION); // increased version
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Either add the column, or drop and create the table again.
}
}
Or the simple solution is to uninstall and reinstall the app.
This question already has answers here:
When does SQLiteOpenHelper onCreate() / onUpgrade() run?
(15 answers)
Closed 7 years ago.
DatabaseHandler.Java
private static final int DATABASE_Version=4;
private static final String DATABASE_Name="UserManager";
private static final String TABLE_USERS="Users";
private SQLiteDatabase db;
private static final String USER_NAME ="Name";
private static final String USER_PASSWRD ="Passwrod";
private static final String USER_REPASSWRD ="ReEnterPassword";
private static final String USER_EMAIL ="Email";
private static final String USER_AGE ="Age";
private static final String USER_PHONENO ="PhoneNumber";
private static final String USER_COLLEGE ="College";
private static final String USER_COURSE ="Course";
public DatabaseHandler(Context context){
super(context, DATABASE_Name, null, DATABASE_Version);
}
public void onCreate(SQLiteDatabase db) {
String CREATE_USERS_TABLE = "CREATE TABLE " + TABLE_USERS + "("
+ USER_NAME + " TEXT," + USER_PASSWRD + " TEXT,"
+ USER_REPASSWRD + " TEXT," + USER_EMAIL + " TEXT PRIMARY KEY," + USER_PHONENO +" INTEGER," + USER_COLLEGE + " TEXT,"
+ USER_COURSE + " TEXT);" ;
db.execSQL(CREATE_USERS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);
// Create tables again
onCreate(db);
}
public void addUser(signup users) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(USER_NAME, users.getName()); // Contact Name
values.put(USER_PASSWRD, users.getPasswrd());
values.put(USER_REPASSWRD, users.getRepaswrd());
values.put(USER_EMAIL, users.getEmail());
values.put(USER_AGE, users.getAge());
values.put(USER_PHONENO, users.getPhoneno());
values.put(USER_COLLEGE, users.getCollege());
values.put(USER_COURSE, users.getCourse()); // Contact Phone Number
// Inserting Row
db.insert(TABLE_USERS, null, values);
db.close(); // Closing database connection
}
public void open()
{
db = this.getWritableDatabase();
}
public void close()
{
this.close();
}
public boolean Login(String username, String password) throws SQLException
{
db = null;
Cursor mCursor = db.rawQuery("SELECT * FROM " + TABLE_USERS + " WHERE ``username=? AND password=?", new String[]{username,password});
if (mCursor != null) {
if(mCursor.getCount() > 0)
{
return true;
}
}
return false;
}
RegisterActivity.Java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
final DatabaseHandler db=new DatabaseHandler(this);
final TextView name1 = (TextView) findViewById(R.id.name);
final TextView pwd1 = (TextView) findViewById(R.id.paswrd);
final TextView cnfrm1 = (TextView) findViewById(R.id.repaswrd);
final TextView email1 = (TextView) findViewById(R.id.email);
final TextView age1 = (TextView) findViewById(R.id.age);
final TextView phone1 = (TextView) findViewById(R.id.phone);
final TextView college1 = (TextView) findViewById(R.id.college);
final TextView course1 = (TextView) findViewById(R.id.course);
Button signup = (Button) findViewById(R.id.button);
View.OnClickListener sp = new View.OnClickListener()
{
#Override
public void onClick(View v) {
String name = name1.getText().toString();
String pwd = pwd1.getText().toString();
String cnfrm = cnfrm1.getText().toString();
String email = email1.getText().toString();
String age = age1.getText().toString();
String phone = phone1.getText().toString();
String college = college1.getText().toString();
String course = course1.getText().toString();
if (name.isEmpty()) {
name1.setError("Enter Name");
} else if (pwd.isEmpty()) {
pwd1.setError("Enter Password");
} else if (cnfrm.isEmpty()) {
cnfrm1.setError("Enter Confirm Password ");
} else if (email.isEmpty()) {
email1.setError("Enter Email");
} else if (age.isEmpty()) {
age1.setError("Enter Age");
} else if (phone.isEmpty()) {
phone1.setError("Enter Phone Number");
} else if (college.isEmpty()) {
college1.setError("Enter College name");
} else if (course.isEmpty()) {
course1.setError("Enter Course");
} else if (!(pwd.equals(cnfrm))) {
cnfrm1.setError("Password doesn't Match");
} else {
String name_1= name1.getText().toString();
String pass_1= pwd1.getText().toString();
String repass_1= cnfrm1.getText().toString();
String email_1= email1.getText().toString();
String age_1= age1.getText().toString();
String phoneno_1= phone1.getText().toString();
String clg_1= college1.getText().toString();
String course_1= course1.getText().toString();
Log.d("Insert: ", "Inserting ..");
db.addUser(new signup(name_1, pass_1, repass_1, email_1, age_1, phoneno_1, clg_1, course_1));
Toast.makeText(getApplicationContext(), "Successfully Signed in", Toast.LENGTH_LONG).show();
Intent intent=new Intent(RegisterActivity.this,FirstActivity.class);
startActivity(intent);
}
}
};
signup.setOnClickListener(sp);
Button reset=(Button) findViewById(R.id.rest);
View.OnClickListener rs= new View.OnClickListener() {
#Override
public void onClick(View v) {
((TextView) findViewById(R.id.name)).setText(null);
((TextView) findViewById(R.id.course)).setText(null);
((TextView) findViewById(R.id.email)).setText(null);
((TextView) findViewById(R.id.age)).setText(null);
((TextView) findViewById(R.id.college)).setText(null);
((TextView) findViewById(R.id.paswrd)).setText(null);
((TextView) findViewById(R.id.repaswrd)).setText(null);
((TextView) findViewById(R.id.phone)).setText(null);
}
};
reset.setOnClickListener(rs);
}
signup.Java
public class signup {
String name;
String passwrd;
String repaswrd;
String email;
String age;
String phoneno;
String college;
String course;
public signup(String name,String passwrd,String repaswrd,String email,String age,String phoneno,String college,String course){
this.name=name;
this.passwrd=passwrd;
this.repaswrd=repaswrd;
this.email=email;
this.age=age;
this.phoneno=phoneno;
this.college=college;
this.course=course;
}
public signup(String name,String passwrd,String repaswrd,String email,String college,String course){
this.name=name;
this.passwrd=passwrd;
this.repaswrd=repaswrd;
this.email=email;
this.college=college;
this.course=course;
}
public String getName(){
return this.name;
}
public String getPasswrd(){
return this.passwrd;
}
public String getRepaswrd(){
return this.repaswrd;
}
public String getEmail(){
return this.email;
}
public String getAge(){
return this.age;
}
public String getPhoneno(){
return this.phoneno;
}
public String getCollege(){
return this.college;
}
public String getCourse(){
return this.course;
}
}
Error:
E/SQLiteLog: (1) table Users has no column named Course
01-25 22:45:31.414 12064-12064/com.pixel.sri.justdoit E/SQLiteDatabase: Error inserting Course=B.E ReEnterPassword=sri
Passwrod=sri Email=sriram.mdu31#gmail.com College=APEC
PhoneNumber=7402043073 Age=21 Name=sriram
android.database.sqlite.SQLiteException: table Users has no column
named Course (code 1): , while compiling: INSERT INTO
Users(Course,ReEnterPassword,Passwrod,Email,College,PhoneNumber,Age,Name)
VALUES (?,?,?,?,?,?,?,?)
at
android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native
Method)
at
android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
at
android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
at
android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:58)
at
android.database.sqlite.SQLiteStatement.(SQLiteStatement.java:31)
at
android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1469)
at
android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at
com.pixel.sri.justdoit.DatabaseHandler.addUser(DatabaseHandler.java:66)
at
com.pixel.sri.justdoit.RegisterActivity$1.onClick(RegisterActivity.java:81)
at android.view.View.performClick(View.java:5201)
at android.view.View$PerformClick.run(View.java:21163)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
01-25 22:45:31.572 12064-12089/com.pixel.sri.justdoit V/RenderScript: 0xb8b446f0 Launching thread(s), CPUs 8
This is common occurrence if the Course column is a recent addition to your database, but you forgot to increment the database version.
With the code you have, bumping your database version will wipe the database and recreate the database with the correct columns.
Alternatively, uninstalling and reinstalling your app should fix it.
You probably added that column after a previous run, when the database was already created.
Solution: Uninstall and reinstall your app.
Alternate solution: Increase the DATABASE_VERSION constant value.