Table Users has no column named Course [duplicate] - java

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.

Related

Adding Date (TextView) into SQLite Database

I'm creating an SQLiteDatabase, I was able to add all the EditText values into the Database however when trying to add a Date which I have used a DatePicker to find and input into TextView, the app crashes.
Is there a different way to insert TextView values into SQLiteDatabase.
Main Activity:
public class MainActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener {
DatabaseHelper peopleDB;
TextView etDate;
Button btnAddData, btnViewData;
EditText etName, etEmail, etAddress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
peopleDB = new DatabaseHelper(this);
etName = (EditText) findViewById(R.id.editName);
etEmail = (EditText) findViewById(R.id.editEmail);
etAddress = (EditText) findViewById(R.id.editAddress);
etDate = (TextView) findViewById(R.id.textView4);
btnAddData = (Button) findViewById(R.id.btnAddData);
btnViewData = (Button) findViewById(R.id.btnViewData);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment datePicker = new DatePickerFragment();
datePicker.show(getSupportFragmentManager(), "date picker");
}
});
AddData();
ViewData();
}
public void AddData() {
btnAddData.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String name = etName.getText().toString();
String email = etEmail.getText().toString();
String tvShow = etAddress.getText().toString();
String date = etDate.getText().toString();
boolean insertData = peopleDB.addData(name, email, tvShow, date);
if (insertData == true) {
Toast.makeText(MainActivity.this, "Data Successfully Inserted!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Something went wrong :(.", Toast.LENGTH_LONG).show();
}
}
});
}
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
String currentDateString = DateFormat.getDateInstance(DateFormat.FULL).format(c.getTime());
TextView textView = (TextView) findViewById(R.id.textView4);
textView.setText(currentDateString);
}
public void ViewData() {
btnViewData.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Cursor data = peopleDB.showData();
if(data.getCount() == 0) {
display("Error", "No Data Found.");
return;
}
//display message
String datestring = etDate.getText().toString();
StringBuffer buffer = new StringBuffer();
while (data.moveToNext()){
buffer.append("ID: " + data.getString(0) + "\n");
buffer.append("Name: " + data.getString(1) + "\n");
buffer.append("Email: " + data.getString(2) + "\n");
buffer.append("Address: " + data.getString(3) + "\n");
buffer.append("Date: " + data.getString(4) + "\n");
}
display("All Stored Data:", buffer.toString());
}
});
}
DatabaseHelper Activity:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "people.db";
public static final String TABLE_NAME = "people_table";
public static final String COL1 = "ID";
public static final String COL2 = "NAME";
public static final String COL3 = "EMAIL";
public static final String COL4 = "ADDRESS";
public static final String COL5 = "DATE";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
" NAME TEXT, EMAIL TEXT, ADDRESS TEXT)";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean addData(String name, String email, String address, String date){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, name);
contentValues.put(COL3, email);
contentValues.put(COL4, address);
contentValues.put(COL5, date);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1) {
return false;
}
else {
return true;
}
}
public Cursor showData(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
return data;
}
}
I think that you did not add date column in create database statement so change this at DatabaseHelper class
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
" NAME TEXT, EMAIL TEXT, ADDRESS TEXT)";
db.execSQL(createTable);
}
to
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
" NAME TEXT, EMAIL TEXT, ADDRESS TEXT , DATE DATETIME)";
db.execSQL(createTable);
}
For best code refactor variables names by click shift+F6 then rename
public static final String COL1 = "ID";
public static final String COL2 = "NAME";
public static final String COL3 = "EMAIL";
public static final String COL4 = "ADDRESS";
public static final String COL5 = "DATE";
to
public static final String COL_ID = "ID";
public static final String COL_NAME = "NAME";
public static final String COL_EMAIL = "EMAIL";
public static final String COL_ADDRESS = "ADDRESS";
public static final String COL_DATE = "DATE";
and change create statement to
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (" +
COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL_NAME +" TEXT," +
COL_EMAIL +" TEXT,"+
COL_ADDRESS + " TEXT ,"+
COL_DATE + " DATETIME)";
db.execSQL(createTable);
}

How to update sqlite record?

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);
}
}

How to move data to SQLite?

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));

Difficult to store Shared preferences value to SQLIte in Android and having null value stored

I think i ran out from ideas about how to do this. I am building and TODO app with register and login feature. Once a user is logged, can create new todos task in SQLite(for now), later i want to delete and rename todos as well.
This is my DB class with SQliteHelper.
public class DatabaseHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "UserManager.db";
// User table name
private static final String TABLE_USER = "user";
// User Table Columns names
private static final String COLUMN_USER_ID = "user_id";
private static final String COLUMN_USER_NAME = "user_name";
private static final String COLUMN_USER_EMAIL = "user_email";
private static final String COLUMN_USER_PASSWORD = "user_password";
//Table mToDo task name
private final static String mTODO = "Todos";
//Todos table columns names
private final static String TASK_ID = "task_Id"; //autoincrement
private final static String user_Id = "userId";
private final static String TITLE = "title";
private final static String CONTENT = "content";
// create table sql query
private String CREATE_USER_TABLE = "CREATE TABLE " + TABLE_USER + "("
+ COLUMN_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COLUMN_USER_NAME + " TEXT,"
+ COLUMN_USER_EMAIL + " TEXT," + COLUMN_USER_PASSWORD + " TEXT" +
")";
private String CREATE_mTODO_TABLE = "CREATE TABLE " + mTODO + "("
+ TASK_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + user_Id + " TEXT NOT NULL,"
+ TITLE + " TEXT," + CONTENT + " TEXT" + ")";
// drop table sql query
private String DROP_USER_TABLE = "DROP TABLE IF EXISTS " + TABLE_USER;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// this.ctx = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_USER_TABLE);
db.execSQL(CREATE_mTODO_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//Drop User Table if exist
db.execSQL(DROP_USER_TABLE);
// Create tables again
onCreate(db);
}
Adding new Task to second table
public void add(ToDo todoTask) {
SQLiteDatabase db = this.getWritableDatabase();
// SharedPreferences sp = PreferenceManager
// .getDefaultSharedPreferences(ctx);
// String d = sp.toString();
ContentValues values = new ContentValues();
values.put(TITLE, todoTask.getTitle());
values.put(CONTENT, todoTask.getContent());
// values.put(user_Id,todoTask.getUserID(d));
// Inserting Row
db.insert(mTODO, null, values);
db.close();
}
ToDo.java
public class ToDo {
private int id;
private String userID;
private String title;
private String content;
public ToDo(String content, int id, String title, String userID) {
this.content = content;
this.id = id;
this.title = title;
this.userID = userID;
}
public ToDo(String content, String title, String userID) {
this.content = content;
this.title = title;
this.userID = userID;
}
public ToDo() {
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getId(String name) {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUserID(String userID) {
return userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
}
Add activity class with inputs and add method
public class addTask extends AppCompatActivity {
private EditText titleUser;
private EditText contentDesc;
private DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_task);
Button btnAdd = (Button) findViewById(R.id.addToDo);
titleUser = (EditText) findViewById(R.id.titleID);
contentDesc = (EditText) findViewById(R.id.contentDescId);
db = new DatabaseHelper(this);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddItem();
}
});
}
private void AddItem() {
ToDo todo = new ToDo();
todo.setTitle(titleUser.getText().toString().trim());
todo.setContent(contentDesc.getText().toString().trim());
db.add(todo);
finish();
}
The current user that is logged, i am putting that user id to Shared preferences
In my second Table i have something like this
task_Id user_id title content
1 null Eat go to Mc
user_id is null here, and i don't know why
i want something like this
task_Id user_id title content
1 2 Eat go to Mc
user_id- should be which user id make the todo
Supposing that you already know how to store and get the userid from the shared preferences.
In your addTask activity, add:
private String userId;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
userId = sharedPreference.getString("USER_ID",null);
...
}
in the addItem() add:
private void AddItem() {
...
todo.setUserId(userId);
...
}
in the DB add() use this:
public void add(ToDo todoTask) {
...
values.put(USERID, todoTask.getUserId());
...
}
OR:
Another approach is to get the value directly from the DB class if you are sure that you will never insert task for other users.
public void add(ToDo todoTask) {
SQLiteDatabase db = this.getWritableDatabase();
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(ctx);
String d = sp.toString();
ContentValues values = new ContentValues();
values.put(TITLE, todoTask.getTitle());
values.put(CONTENT, todoTask.getContent());
values.put(user_Id,todoTask.getUserID(d));
db.insert(mTODO, null, values);
db.close();
}
and in the constructor save the context for further use.
private Context ctx;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.ctx = context;
}
You are creating ToDo Table using user_id. while static String refrenced is userid: hence in database when entered it goes null by default
//Table mToDo task name
private final static String mTODO = "Todos";
//Todos table columns names
private final static String TASK_ID = "task_Id";
private final static String user_Id = "userId"; //<----Wrong Here
private final static String TITLE = "title";
private final static String CONTENT = "content";
private String CREATE_mTODO_TABLE = "CREATE TABLE " + mTODO + "("
+ TASK_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + user_Id + " TEXT NOT NULL,"
+ TITLE + " TEXT," + CONTENT + " TEXT" + ")";
Also here is something more for you, Simply you must supply the User Id value to the Field. Below are Some Examples How to do So
private static final String TAG = "DB_HANDLER";
private static final int DATABASE_VERSION = 15;
private static final String DATABASE_NAME = "ElmexContactsManager.db";
/*-------------------------------------------BIZ_SEGMENT----------------------------------------*/
private static final String TABLE_BIZ_SEGMENT = "BizSegment";
/*01*/private static final String KEY_LOCAL_BIZ_SEGMENT_ID = "LocalBizSegmentId";
/*02*/private static final String KEY_BIZ_SEGMENT_ID = "BizSegmentId";
/*03*/private static final String KEY_BIZ_SEGMENT = "BizSegment";
/*04*/private static final String KEY_ADDED_ON = "AddedOn";
/*05*/private static final String KEY_UPDATED_ON = "UpdatedOn";
/*-------------------------------------------BIZ_SEGMENT----------------------------------------*/
String CREATE_TABLE_BIZ_SEGMENT = "CREATE TABLE " + TABLE_BIZ_SEGMENT + "("
/*01*/ + KEY_LOCAL_BIZ_SEGMENT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
/*02*/ + KEY_BIZ_SEGMENT_ID + " INTEGER,"
/*03*/ + KEY_BIZ_SEGMENT + " TEXT,"
/*04*/ + KEY_ADDED_ON + " TEXT,"
/*05*/ + KEY_UPDATED_ON + " TEXT"
+ ")";
public ContactDatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
//3rd argument to be passed is CursorFactory instance
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) { try {
sqLiteDatabase.execSQL(CREATE_TABLE_BIZ_SEGMENT);
sqLiteDatabase.execSQL(CREATE_TABLE_CONTACT_TYPE);
sqLiteDatabase.execSQL(CREATE_TABLE_CONTACT_SOURCE);
sqLiteDatabase.execSQL(CREATE_TABLE_CONT_INDUSTRY);
sqLiteDatabase.execSQL(CREATE_TABLE_MARKETING_REGION);
sqLiteDatabase.execSQL(CREATE_TABLE_MARKETING_REGION_BLOCK);
sqLiteDatabase.execSQL(CREATE_TABLE_CONTACT_MASTER);
sqLiteDatabase.execSQL(CREATE_TABLE_CONTACT_DET);
} catch (SQLException e) {
e.printStackTrace();
}
Log.d(TAG, "Table Craeted ");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
// Drop older table if existed
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_BIZ_SEGMENT);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACT_TYPE);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACT_SOURCE);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_CONT_INDUSTRY);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_MARKETING_REGION);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_MARKETING_REGION_BLOCK);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACT_MASTER);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACT_DET);
// Create tables again
onCreate(sqLiteDatabase);
Log.d(TAG, "Table Udgraded to Version :" + i1);
}
/*-------------------------------------------BIZ_SEGMENT----------------------------------------*/
public void addBizSegment(BizSegment bizSegment) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
ContentValues values = new ContentValues();
values.put(KEY_BIZ_SEGMENT_ID, bizSegment.getBizSegmentId());
values.put(KEY_BIZ_SEGMENT, bizSegment.getBizSegment());
values.put(KEY_ADDED_ON, df.format(bizSegment.getAddedOn()));
values.put(KEY_UPDATED_ON, df.format(bizSegment.getUpdatedOn()));
// Inserting Row
sqLiteDatabase.insert(TABLE_BIZ_SEGMENT, null, values);
//2nd argument is String containing nullColumnHack
sqLiteDatabase.close(); // Closing database connection
}
public void updateBizSegment(BizSegment bizSegment) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
ContentValues values = new ContentValues();
//values.put(KEY_BIZ_SEGMENT_ID, bizSegment.getBizSegmentId());
values.put(KEY_BIZ_SEGMENT, bizSegment.getBizSegment());
values.put(KEY_ADDED_ON, df.format(bizSegment.getAddedOn()));
values.put(KEY_UPDATED_ON, df.format(bizSegment.getUpdatedOn()));
// Inserting Row
sqLiteDatabase.update(TABLE_BIZ_SEGMENT, values, KEY_BIZ_SEGMENT_ID + " = ?", new String[]{String.valueOf(bizSegment.getBizSegmentId())});
//2nd argument is String containing nullColumnHack
sqLiteDatabase.close(); // Closing database connection
}
public List<BizSegment> getBizSegmentAll() {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
List<BizSegment> bizSegmentList = new ArrayList<BizSegment>();
DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_BIZ_SEGMENT;
Cursor cursor = sqLiteDatabase.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
try {
BizSegment bizSegment = new BizSegment(cursor.getInt(0),
cursor.getInt(1),
cursor.getString(2),
df.parse(cursor.getString(3)),
df.parse(cursor.getString(4)));
bizSegmentList.add(bizSegment);
} catch (ParseException e) {
e.printStackTrace();
}
} while (cursor.moveToNext());
}
cursor.close();
sqLiteDatabase.close();
//2nd argument is String containing nullColumnHack
return bizSegmentList;
}
public void deleteBizSegment(BizSegment bizSegment) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_BIZ_SEGMENT, KEY_BIZ_SEGMENT_ID + " = ?",
new String[]{String.valueOf(bizSegment.getBizSegmentId())});
db.close();
}
Other method is Using Shared Preference suitable for limited Data. It does not provide any relationships. I use this to store basic User related Data. Not for complicated/Relational Large Data. For That Sqlite is preferred.
public class AppPreference {
SharedPreferences pref;
SharedPreferences.Editor edit;
/**
* #param clientMaster object to set preference
* #param context Context of call
*/
public void putPreference(ClientMaster clientMaster, Context context) {
pref = context.getSharedPreferences("AppPreference", Context.MODE_PRIVATE);
edit = pref.edit();
edit.putInt("ClientId", clientMaster.getClientId());
edit.putString("FirstName", clientMaster.getFirstName());
edit.putString("LastName", clientMaster.getLastName());
edit.putString("Mobile", clientMaster.getMobile());
edit.putInt("PincodeId", clientMaster.getPincodeId());
edit.putString("Email", clientMaster.getEmail());
edit.putString("Password", clientMaster.getPassword());
edit.putString("MembershipCode", clientMaster.getMembershipCode());
edit.putString("MembershipIssueDate", clientMaster.getMembershipIssueDate().toString());
edit.putString("MembershipExpiryDate", clientMaster.getMembershipExpiryDate().toString());
edit.putString("MemberShipUpdatedOn", clientMaster.getMemberShipUpdatedOn().toString());
edit.putString("MemberShipQRCode", clientMaster.getMemberShipQRCode());
edit.putInt("ReferredByTypeID", clientMaster.getReferredByTypeID());
edit.putInt("ReferredByID", clientMaster.getReferredByID());
//edit.putString("LastPasswordUpdatedOn", clientMaster.getLastPasswordUpdatedOn().toString());
edit.putString("TempMembershipCode", clientMaster.getTempMembershipCode());
edit.putString("AddedOn", clientMaster.getAddedOn().toString());
//edit.putString("UpdatedOn", clientMaster.getUpdatedOn().toString());
edit.putBoolean("Login", true);
edit.putBoolean("Skip", false);
edit.commit();
}
/**
*
* #param appLanguage
* #param context
*/
public void putLanguagePreference(String appLanguage, Context context) {
pref = context.getSharedPreferences("AppPreference", Context.MODE_PRIVATE);
edit = pref.edit();
edit.putString("AppLanguage", appLanguage);
edit.commit();
}
/**
* To clear All Object preference & Login False
*
* #param context Context call
*/
public void clearPreference(Context context) {
pref = context.getSharedPreferences("AppPreference", Context.MODE_PRIVATE);
edit = pref.edit();
edit.clear();
edit.putBoolean("Login", false);
edit.commit();
}
/**
* #param InstanceId Instance Id
* #param context
*/
public void putPreferenceInstance(String InstanceId, Context context) {
pref = context.getSharedPreferences("AppPreference", Context.MODE_PRIVATE);
edit = pref.edit();
edit.putString("InstanceId", InstanceId);
edit.commit();
}
}

Cant insert values in my sqlite database

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.

Categories

Resources