I coded this for my school project. It crashes when I call update method. error is given below :
E/SQLiteLog: (1) table userInfo has no column named userInfo E/SqDb:
Err ins ...
android.database.sqlite.SQLiteException: table userInfo has no column named userInfo (code 1): , while compiling: INSERT INTO
userInfo(password,userInfo) VALUES (?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native
Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:921)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:532)
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:1570)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1427)
at com.example.prabuddhaabisheka.mock.DBHelper.addInfo(DBHelper.java:46)
at com.example.prabuddhaabisheka.mock.Home$2.onClick(Home.java:59)
at android.view.View.performClick(View.java:5232)
at android.view.View$PerformClick.run(View.java:21289)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:168)
at android.app.ActivityThread.main(ActivityThread.java:5885)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
public class EditProfile extends AppCompatActivity {
Button search, edit, delete;
EditText name, password, dob;
RadioButton male,female;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
search = findViewById(R.id.buttonSerach);
edit = findViewById(R.id.buttonEdit);
delete = findViewById(R.id.Delete);
name = findViewById(R.id.editTextName);
password = findViewById(R.id.editTextPassword);
dob = findViewById(R.id.editTextDOB);
male = (RadioButton) findViewById(R.id.radioButtonMale);
female = findViewById(R.id.radioButtonFemale);
}
public void search(View view){
DBHelper dbHelper = new DBHelper(this);
String givenName = name.getText().toString();
ArrayList<userInfo> user ;
user = dbHelper.readAllInfo();
if(!user.isEmpty()) {
for (userInfo u : user) {
if (givenName.equals(u.name)) {
password.setText(u.password);
dob.setText(u.dob);
if ("Male".equals(u.gender)) {
male.setChecked(true);
female.setChecked(false);
} else {
male.setChecked(false);
female.setChecked(true);
}
}
}
}
}
public void update(View view){
DBHelper dbHelper = new DBHelper(this);
String givenName = name.getText().toString();
int id = 0;
ArrayList<userInfo> user;
user = dbHelper.readAllInfo();
if(!user.isEmpty()) {
for (userInfo u : user) {
if (givenName.equals(u.name)) {
id = u.id;
}
}
}
String givenDob = dob.getText().toString();
String givenPassword = name.getText().toString();
String gender;
if (male.isChecked()){
gender = "Male";
}
else{
gender = "Female";
}
boolean updated = dbHelper.updateInfo(id,givenName,givenPassword,givenDob,gender);
if (updated) {
Toast toast = Toast.makeText(this, "Updated", Toast.LENGTH_SHORT);
toast.show();
}
else{
Toast toast = Toast.makeText(this, "Update failed !", Toast.LENGTH_SHORT);
toast.show();
}
}
}
DBHelper class is also given below
public class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context) {
super(context, UserProfile.Users.DB_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE "+ UserProfile.Users.TABLE_NAME +" ("+
UserProfile.Users._ID + "INTEGER PRIMARY KEY," +
UserProfile.Users.TABLE_COLUMN_USERNAME + "TEXT,"+
UserProfile.Users.TABLE_COLUMN_PASSWORD + "TEXT," +
UserProfile.Users.TABLE_COLUMN_DOB + "TEXT,"+
UserProfile.Users.TABLE_COLUMN_GENDER + "TEXT)";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public boolean addInfo( ContentValues values ){
SQLiteDatabase db = getWritableDatabase();
long added = db.insert(UserProfile.Users.TABLE_NAME,null,value);
return (added != 0);
}
public boolean updateInfo(int id, String name, String password, String dob, String gender ){
SQLiteDatabase db = getReadableDatabase();
ContentValues values = new ContentValues();
values.put(UserProfile.Users.TABLE_COLUMN_USERNAME,name);
values.put(UserProfile.Users.TABLE_COLUMN_PASSWORD,password);
values.put(UserProfile.Users.TABLE_COLUMN_DOB,dob);
values.put(UserProfile.Users.TABLE_COLUMN_GENDER,gender);
String where = UserProfile.Users._ID + " =";
String[] arg = {Integer.toString(id)};
int row = db.update(UserProfile.Users.TABLE_NAME, values, where, arg);
return (row !=0 );
}
public ArrayList readAllInfo(){
SQLiteDatabase db = getReadableDatabase();
String[] columns = {
UserProfile.Users._ID,
UserProfile.Users.TABLE_COLUMN_USERNAME,
UserProfile.Users.TABLE_COLUMN_PASSWORD,
UserProfile.Users.TABLE_COLUMN_GENDER,
UserProfile.Users.TABLE_COLUMN_DOB
};
Cursor cursor = db.query(UserProfile.Users.TABLE_NAME,columns,null,null,null
,null,null);
ArrayList<userInfo> users = new ArrayList<>();
while (cursor.moveToNext()){
int id = cursor.getInt(cursor.getColumnIndexOrThrow(UserProfile.Users._ID));
String name = cursor.getString(cursor.getColumnIndexOrThrow(UserProfile.Users.TABLE_COLUMN_USERNAME));
String dob = cursor.getString(cursor.getColumnIndexOrThrow(UserProfile.Users.TABLE_COLUMN_DOB));
String gender = cursor.getString(cursor.getColumnIndexOrThrow(UserProfile.Users.TABLE_COLUMN_GENDER));
String password = cursor.getString(cursor.getColumnIndexOrThrow(UserProfile.Users.TABLE_COLUMN_PASSWORD));
userInfo user = new userInfo(id,name,password,dob,gender);
users.add(user);
}
cursor.close();
return users;
}
public ArrayList readAllInfo(int id){
SQLiteDatabase db = getReadableDatabase();
String[] columns = {
UserProfile.Users._ID,
UserProfile.Users.TABLE_COLUMN_USERNAME,
UserProfile.Users.TABLE_COLUMN_PASSWORD,
UserProfile.Users.TABLE_COLUMN_GENDER,
UserProfile.Users.TABLE_COLUMN_DOB
};
String where = UserProfile.Users._ID + " =?";
String[] arg = {Integer.toString(id)};
Cursor cursor = db.query(UserProfile.Users.TABLE_NAME,columns,where,arg,null
,null,null);
ArrayList<userInfo> users = new ArrayList<>();
while (cursor.moveToNext()){
//int ID = cursor.getInt(cursor.getColumnIndexOrThrow(UserProfile.Users._ID));
String name = cursor.getString(cursor.getColumnIndexOrThrow(UserProfile.Users.TABLE_COLUMN_USERNAME));
String dob = cursor.getString(cursor.getColumnIndexOrThrow(UserProfile.Users.TABLE_COLUMN_DOB));
String gender = cursor.getString(cursor.getColumnIndexOrThrow(UserProfile.Users.TABLE_COLUMN_GENDER));
String password = cursor.getString(cursor.getColumnIndexOrThrow(UserProfile.Users.TABLE_COLUMN_PASSWORD));
userInfo user = new userInfo(id,name,password,dob,gender);
users.add(user);
}
cursor.close();
return users;
}
public void deleteUser(int ID){
SQLiteDatabase db = getReadableDatabase();
String where = UserProfile.Users._ID + " =?";
String[] arg = {Integer.toString(ID)};
int count = db.delete(UserProfile.Users.TABLE_NAME,where,arg);
}
}
The error is clear:
...
.sqlite.SQLiteException: table userInfo has no column named userInfo (code 1):
, while compiling: INSERT INTO userInfo(password,userInfo) VALUES (?,?) at
...
When you are invoking the method
public boolean addInfo( ContentValues values )
You are passing as a content value, a value named with the same name as the table. You have to check two things:
Where you are using UserProfile.Users.TABLE_NAME (that I suppose it has the value userInfo
Check what you are passing to content values used by addInfo method.
Hope it helps.
If you are trying to add new row to the table after it has been created, try to remove the table and create it again.
to remove
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
after this, you can recreate the table again
You have to increase your version of database after then do changes in On-upgrade method of sqlite.
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if(newVersion > oldVersion){
db.execSQL("DROP TABLE IF EXISTS " +......);
db.execSQL("CREATE TABLE IF NOT EXISTS " +......);
insertColumnIfNotAvailableinTable(SQLiteDatabase db, String tableName, String columnName, String columnType);
}
}
Related
Code
public class SettingsContacts extends AppCompatActivity {
private RecyclerView contactsList;
private List<ContactsHelper> contacts = new ArrayList<>();
private LinearLayoutManager linearLayoutManager;
private ContactsAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings_contacts);
contactsList = (RecyclerView) findViewById(R.id.usersList);
//Add the data first
addDataToList();
linearLayoutManager = new LinearLayoutManager(getApplicationContext());
//and then create a object and pass the lis
mAdapter = new ContactsAdapter(contacts);
contactsList.setHasFixedSize(true);
contactsList.setLayoutManager(linearLayoutManager);
contactsList.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
}
public void addDataToList() {
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
if (cursor != null) {
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Cursor phoneCursor = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id},
null);
if (phoneCursor != null) {
if (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contacts.add(new ContactsHelper(name, phoneNumber));
phoneCursor.close();
}
}
}
}
}
cursor.close();
}
}
}
This displays all the contacts in the users phone in an activity... How do i move the data into a table in SQLite?
Progress so far:
public class DatabaseHelper extends SQLiteOpenHelper {
// Table Name
public static final String TABLE_NAME = "Contacts";
// Table columns
public static final String ID = "ID";
public static final String Contact_Name = "Contact_Name";
public static final String Phone_Number = "Phone_Number";
// Database Information
static final String DB_NAME = "MessagePlus_Contacts";
// database version
static final int DB_VERSION = 1;
// Creating table query
private static final String CREATE_TABLE = "Create Table " + TABLE_NAME + "(" + ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + Contact_Name + " TEXT NOT NULL, " + Phone_Number + " INT NOT NULL);";
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
Helper
public class ContactsHelper {
private String Name;
private String PhoneNumber;
public ContactsHelper() {
}
public ContactsHelper(String Name, String PhoneNumber) {
this.Name = Name;
this.PhoneNumber = PhoneNumber;
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public String getPhoneNumber() {
return PhoneNumber;
}
public void setPhoneNumber(String PhoneNumber) {
this.PhoneNumber = PhoneNumber;
}
}
I've got to this point but I don't know how to proceed because I have so far only worked with adding/modifying data by clicking a button or similar to that.
How do I move the complete data to SQLite and when new contact is added obviously it wont get added to table automatically so when I add a feature like swipe to refresh I want the new contact to be added to the data as well?
Solution:
Add this method in your DatabaseHelper class:
public void insertData(String contactName, String phoneNumber) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DatabaseHelper.Contact_Name, contactName);
values.put(DatabaseHelper.Phone_Number, phoneNumber);
db.insert(DatabaseHelper.TABLE_NAME, null, values);
// close db connection
db.close();
}
then, Firstly, make DatabaseHelper global object in your SettingsContacts class:
public DatabaseHelper database;
Add this in youronCreate()
database = new DatabaseHelper(SettingsContacts.this);
then after this, add the below line in addDataToList() method as shown:
Add this line:
database.insertData(name, phoneNumber)
as shown in below code (Write Here):
if (phoneCursor != null) {
if (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contacts.add(new ContactsHelper(name, phoneNumber));
phoneCursor.close();
....... (Write Here)
}
}
That's it.
Hope it works.
To see if the data is already inserted, you can check the count of your table:
public int getCount() {
String countQuery = "SELECT * FROM " + DatabaseHandler.TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
// return count
return count;
}
Write the above method in you Database Handler class.
Then, in your activity after calling insertData(..), you can write like:
int count = database.getCount();
Log.e("Count From DB: ", String.valueOf(count));
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 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.
This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 7 years ago.
the database class
public class DBHelper extends SQLiteOpenHelper {
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_STREET = "street";
public static final String CONTACTS_COLUMN_CITY = "place";
public static final String CONTACTS_COLUMN_PHONE = "phone";
private HashMap hp;
public DBHelper(Context context)
{
super(context, DATABASE_NAME , null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table contacts " +
"(id integer primary key, name text,phone text,email text, street text,place text)"
);
}
#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 phone, String email, String street,String place)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("phone", phone);
contentValues.put("email", email);
contentValues.put("street", street);
contentValues.put("place", place);
db.insert("contacts", null, contentValues);
return true;
}
public Cursor getData(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts where id="+id+"", null );
return res;
}
public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, CONTACTS_TABLE_NAME);
return numRows;
}
public boolean updateContact (Integer id, String name, String phone, String email, String street,String place)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("phone", phone);
contentValues.put("email", email);
contentValues.put("street", street);
contentValues.put("place", place);
db.update("contacts", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
public Integer deleteContact (Integer id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("contacts",
"id = ? ",
new String[] { Integer.toString(id) });
}
public ArrayList<String> getAllCotacts()
{
ArrayList<String> array_list = new ArrayList<String>();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts", null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME)));
res.moveToNext();
}
return array_list;
}
the activity class
public class MainActivity extends AppCompatActivity {
Button login;
EditText student_id;
EditText password;
TextView message;
DBHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DBHelper(this);
login = (Button) findViewById(R.id.button);
student_id = (EditText) findViewById(R.id.student_id);
password = (EditText) findViewById(R.id.password);
message=(TextView)findViewById(R.id.logResult);
message.setText("");
db.insertContact("jon","9595749944","r#hotmail.com","a","usa");
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String pass = password.getText().toString();
int id = Integer.parseInt(student_id.getText().toString());
int result= db.numberOfRows();
if (result == 1) {
message.setText("Invalid User");
} else {
message.setText("valid User" );
}
}
});
}
But,When the button is pressed the insertion in not occur and app close
where is the problem?? help?????????????? I want to insert data in database when the app is created how?
your call is outside of the onclick , first try:
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
db.insertContact("jon","9595749944","r#hotmail.com","a","usa");
}
});
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Im trying to store data from some editTexts on a local android database and then eventually show it on a listview, but right now Im getting an error that says a column doesnt exist, I was following a tutorial on android hive so some of the variable names might look weird, but everything should be accurate.
StackTrace
2038-12038/com.example.adrian.legioncheck_in E/SQLiteLog﹕ (1) table contacts has no column named Longitude
08-25 12:12:19.121 12038-12038/com.example.adrian.legioncheck_in E/SQLiteDatabase﹕ Error inserting Latitude=-85 Longitude=50 POnumber=255902
android.database.sqlite.SQLiteException: table contacts has no column named Longitude (code 1): , while compiling: INSERT INTO contacts(Latitude,Longitude,POnumber) VALUES (?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:923)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:534)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1523)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1395)
at com.example.adrian.legioncheck_in.DatabaseHandler.addContact(DatabaseHandler.java:67)
at com.example.adrian.legioncheck_in.MapsActivity.SaveAction(MapsActivity.java:67)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3850)
at android.view.View.performClick(View.java:4470)
at android.view.View$PerformClick.run(View.java:18593)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5867)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674)
at dalvik.system.NativeStart.main(Native Method)
Database Handle.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
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 = "contactsManager";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "POnumber";
private static final String KEY_PH_NO = "Latitude";
private static final String KEY_LONG = "Longitude";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
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" + KEY_LONG + " TEXT" +")";
db.execSQL(CREATE_CONTACTS_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_CONTACTS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new contact
/* line 67 */ void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getPO());
values.put(KEY_PH_NO, contact.getLat());
values.put(KEY_LONG, contact.getLong());
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO, KEY_LONG }, 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), cursor.getString(3));
// return contact
return contact;
}
// Getting All Contacts
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.setPO(cursor.getString(1));
contact.setLat(cursor.getString(2));
contact.setLong(cursor.getString(3));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// Updating single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getPO());
values.put(KEY_PH_NO, contact.getLat());
values.put(KEY_LONG, contact.getLong());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
}
// Getting contacts Count
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();
}
}
contact.java
public class Contact {
//private variables
int _id;
String _PO;
String _lat;
String _longi;
// Empty constructor
public Contact(){
}
// constructor
public Contact(int id, String PO, String _lat, String _longi){
this._id = id;
this._PO = PO;
this._lat = _lat;
this._longi = _longi;
}
// constructor
public Contact(String PO, String _lat, String _longi){
this._PO = PO;
this._lat = _lat;
this._longi = _longi;
}
// getting ID
public int getID(){
return this._id;
}
// setting id
public void setID(int id){
this._id = id;
}
// getting name
public String getPO(){
return this._PO;
}
// setting name
public void setPO(String PO){
this._PO = PO;
}
// getting phone number
public String getLat(){
return this._lat;
}
// setting phone number
public void setLat(String lat){
this._lat = lat;
}
public String getLong()
{
return this._longi;
}
public void setLong(String longi)
{
this._longi = longi;
}
}
Button that saves data to database:
public void SaveAction(View view)
{
EditText po = (EditText)findViewById(R.id.POnumber);
String PO = po.getText().toString();
EditText textlat = (EditText)findViewById(R.id.textLat);
String LAT = textlat.getText().toString();
EditText textlong = (EditText)findViewById(R.id.textLong);
String LONG = textlong.getText().toString();
DatabaseHandler db = new DatabaseHandler(MapsActivity.this);
db.addContact(new Contact(PO,LAT,LONG));
// Reading all Data
Log.d("Reading: ", "Reading all inputs..");
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
String log = "Id: "+cn.getID()+" ,PO number: " + cn.getPO() + " ,Latitude: " + cn.getLat() + " ,Longitude: " + cn.getLong();
// Writing Data to log
Log.d("Name: ", log);
}
}
KEY_PH_NO + " TEXT" + KEY_LONG + " TEXT" +")"
Add the missing , before KEY_LONG:
KEY_PH_NO + " TEXT," + KEY_LONG + " TEXT" +")"
Uninstall your app so the onCreate() is run again. See
When is SQLiteOpenHelper onCreate() / onUpgrade() run?
for more about that.