Error of inserting data into sqlite database - java

Am working on a project. I want to insert student details into sqlite database but i receive an error in the android monitor that "The TABLE AttendanceList does not have column named surname" and i do have that colunm. i have been stuck for days, please i help.
Here is my code.
DatabaseHandler.java
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 = "StudentAttendance";
// Contacts table name
private static final String TABLE_AttendanceList = "AttendanceList";
// Contacts Table Columns names
private static final String KEY_surname = "surname";
private static final String KEY_ID = "id";
private static final String KEY_reg_no = "reg_no";
private static final String KEY_firstname = "firstname";
private static final String KEY_lastname = "lastname";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_AttendanceList_TABLE = "CREATE TABLE " + TABLE_AttendanceList + "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_reg_no + " TEXT"
+ KEY_firstname + " TEXT"
+ KEY_lastname + "TEXT"
+ KEY_surname + "TEXT" + ")";
db.execSQL(CREATE_AttendanceList_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_AttendanceList);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new contact
void addAttendanceList (AttendanceList AttendanceList) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID, AttendanceList.getID());
values.put(KEY_reg_no, AttendanceList.getRegNo()); // RegNo
values.put(KEY_firstname, AttendanceList.getFirstname());
values.put(KEY_lastname, AttendanceList.getLastname()); // lasttname
values.put(KEY_surname, AttendanceList.getSurname());// surname
// Inserting Row
db.insert(TABLE_AttendanceList,null,values);
db.close(); // Closing database connection
}
// Getting single contact
AttendanceList getAttendanceList(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_AttendanceList, new String[] { KEY_ID,
KEY_reg_no, KEY_firstname, KEY_lastname, KEY_surname }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
AttendanceList AttendanceList = new AttendanceList(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2), cursor.getString(3),cursor.getString(4));
// return AttendanceList
return AttendanceList;
}
// Getting All details
public List<AttendanceList> getAllAttendanceList() {
List<AttendanceList> contactList = new ArrayList<AttendanceList>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_AttendanceList;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
AttendanceList AttendanceList = new AttendanceList();
AttendanceList.setID(Integer.parseInt(cursor.getString(0)));
AttendanceList.setRegNo(cursor.getString(1));
AttendanceList.setFirstname(cursor.getString(2));
AttendanceList.setLastname(cursor.getString(3));
AttendanceList.setSurname(cursor.getString(4));
// Adding Attendance to list
contactList.add(AttendanceList);
} while (cursor.moveToNext());
}
// return Attendancelist
return contactList;
}
// Updating single Attendance List
public int updateContact(AttendanceList AttendanceList) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_reg_no, AttendanceList.getRegNo());
values.put(KEY_firstname, AttendanceList.getFirstname());
values.put(KEY_lastname, AttendanceList.getLastname());
values.put(KEY_surname, AttendanceList.getSurname());
// updating row
return db.update(TABLE_AttendanceList, values, KEY_ID + " = ?",
new String[] { String.valueOf(AttendanceList.getID()) });
}
// Deleting single List item
public void deleteListItem(AttendanceList AttendanceList) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_AttendanceList, KEY_ID + " = ?",
new String[] { String.valueOf(AttendanceList.getID()) });
db.close();
}
// Getting List Count
public int getListCount() {
String countQuery = "SELECT * FROM " + TABLE_AttendanceList;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
StudentTake100Activity.java
public class StudentTake100Activity extends AppCompatActivity {
private ListView lvStudentlist;
private StudentListAdapter adapter;
private List<StudentList> mStudentList;
private CheckBox checkBox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_take100);
lvStudentlist= (ListView) findViewById(R.id.listview_studentlist);
final DatabaseHandler db = new DatabaseHandler(this);
mStudentList = new ArrayList<>();
//Add sample data for list
//We can get data from DB, webservice here
mStudentList.add(new StudentList(1, "U11EE1001", "Bargo","S.","Mayafi"));
mStudentList.add(new StudentList(2, "U11EE1002", "Barnsbas","Snake.","Maciji"));
mStudentList.add(new StudentList(3, "U11EE1004", "Adamu","Tanko.","Sadau"));
mStudentList.add(new StudentList(4, "U11EE1005", "Munzali","","Cire Tallafi"));
//Init adapter
adapter = new StudentListAdapter(getApplicationContext(), mStudentList);
lvStudentlist.setAdapter(adapter);
checkBox = (CheckBox) findViewById(R.id.checkBox);
lvStudentlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
StudentList studentList = (StudentList)parent.getItemAtPosition(position);
String reg_no = studentList.getReg_no();
String firstname = studentList.getFirstname();
String lastname = studentList.getLasttname();
String surname = studentList.getSurname();
db.addAttendanceList(new AttendanceList(reg_no,firstname,lastname,surname));
}
});
}
}
AttendaneList.java
public class AttendanceList {
//private variables
int _id;
String _reg_no;
String _firstname;
String _lastname;
String _surname;
// Empty constructor
public AttendanceList(){
}
// constructor
public AttendanceList(int id, String _reg_no, String _firstname, String _lastname, String _surname){
this._id = id;
this._reg_no = _reg_no;
this._firstname = _firstname;
this._lastname = _lastname;
this._surname = _surname;
}
// constructor
public AttendanceList(String _reg_no, String _firstname, String _lastname, String _surname){
this._reg_no = _reg_no;
this._firstname = _firstname;
this._lastname = _lastname;
this._surname = _surname;
}
// getting ID
public int getID(){
return this._id;
}
// setting id
public void setID(int id){
this._id = id;
}
// getting regNo
public String getRegNo(){
return this._reg_no;
}
// setting regNo
public void setRegNo(String reg_no){
this._reg_no = reg_no;
}
// getting firstname
public String getFirstname(){
return this._firstname;
}
// setting firstname
public void setFirstname(String firstname){
this._firstname = firstname;
}
// getting lastname
public String getLastname(){
return this._lastname;
}
// setting lastname
public void setLastname(String lastname){
this._lastname = lastname;
}
// getting surname
public String getSurname(){
return this._surname;
}
// setting surname
public void setSurname(String surname){
this._surname = surname;
}
}
logcat image
syntax error
06-22 10:58:04.576 2936-2961/com.sunusi2sim.mobileattendance E/Surface: getSlotFromBufferLocked: unknown buffer: 0xeeab85e0
06-22 10:58:05.957 2936-2936/com.sunusi2sim.mobileattendance E/SQLiteLog: (1) near ")": syntax error
06-22 10:58:05.959 2936-2936/com.sunusi2sim.mobileattendance E/InputEventReceiver: Exception dispatching input event.
06-22 10:58:05.959 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: android.database.sqlite.SQLiteException: near ")": syntax error (code 1): , while compiling: CREATE TABLE AttendanceList(id INTEGER PRIMARY KEY,reg_no TEXT,firstname TEXT,lastname TEXT,surname TEXT,)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1674)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1605)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at com.sunusi2sim.mobileattendance.DatabaseHandler.onCreate(DatabaseHandler.java:47)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at com.sunusi2sim.mobileattendance.DatabaseHandler.addAttendanceList(DatabaseHandler.java:66)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at com.sunusi2sim.mobileattendance.StudentTake100Activity$1.onItemClick(StudentTake100Activity.java:54)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.widget.AdapterView.performItemClick(AdapterView.java:310)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.widget.AbsListView.performItemClick(AbsListView.java:1145)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.widget.AbsListView$PerformClick.run(AbsListView.java:3042)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.widget.AbsListView.onTouchUp(AbsListView.java:3891)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.widget.AbsListView.onTouchEvent(AbsListView.java:3656)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.view.View.dispatchTouchEvent(View.java:9294)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2547)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2240)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2553)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2254)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2553)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2254)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2553)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2254)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2553)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2254)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2553)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2254)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2553)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2254)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at com.android.internal.policy.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2403)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1737)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.app.Activity.dispatchTouchEvent(Activity.java:2765)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:60)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at com.android.internal.policy.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2364)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.view.View.dispatchPointerEvent(View.java:9514)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4230)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4096)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3642)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3695)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3661)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3787)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3669)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3844)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3642)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3695)
06-22 10:58:05.961 2936-2936/com.sunusi2sim.mobileattendance E/MessageQueue-JNI: at android.view.ViewRootImpl$InputS
ViewAttendanceActivity
public class ViewAttendanceActivity extends AppCompatActivity {
private ListView lvStudentlist;
private StudentListAdapter adapter;
private List<StudentList> mStudentList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_attendance);
lvStudentlist= (ListView) findViewById(R.id.listview_studentlist);
DatabaseHandler db = new DatabaseHandler(this);
SQLiteDatabase connection;
connection = db.getReadableDatabase();
Cursor result=connection.rawQuery("SELECT * FROM AttendanceList", null);// database query for all AttendanceList in your table
while(result.moveToNext ())
mStudentList.add(new StudentList(result.getInt(0),result.getString(1),result.getString(2),result.getString(3),result.getString(4)));
mStudentList = new ArrayList<>();
adapter = new StudentListAdapter(getApplicationContext(), mStudentList);
lvStudentlist.setAdapter(adapter);
}
}
Error
06-24 17:41:05.354 1650-1650/com.sunusi2sim.mobileattendance E/AndroidRuntime: FATAL EXCEPTION: main
06-24 17:41:05.354 1650-1650/com.sunusi2sim.mobileattendance E/AndroidRuntime: Process: com.sunusi2sim.mobileattendance, PID: 1650
06-24 17:41:05.354 1650-1650/com.sunusi2sim.mobileattendance E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.sunusi2sim.mobileattendance/com.sunusi2sim.mobileattendance.ViewAttendanceActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'boolean java.util.List.add(java.lang.Object)' on a null object reference
06-24 17:41:05.354 1650-1650/com.sunusi2sim.mobileattendance E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
06-24 17:41:05.354 1650-1650/com.sunusi2sim.mobileattendance E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
06-24 17:41:05.354 1650-1650/com.sunusi2sim.mobileattendance E/AndroidRuntime: at android.app.ActivityThread.-wrap11(ActivityThread.java)
06-24 17:41:05.354 1650-1650/com.sunusi2sim.mobileattendance E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
06-24 17:41:05.354 1650-1650/com.sunusi2sim.mobileattendance E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102)
06-24 17:41:05.354 1650-1650/com.sunusi2sim.mobileattendance E/AndroidRuntime: at android.os.Looper.loop(Looper.java:148)
06-24 17:41:05.354 1650-1650/com.sunusi2sim.mobileattendance E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5417)
06-24 17:41:05.354 1650-1650/com.sunusi2sim.mobileattendance E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
06-24 17:41:05.354 1650-1650/com.sunusi2sim.mobileattendance E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
06-24 17:41:05.354 1650-1650/com.sunusi2sim.mobileattendance E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
06-24 17:41:05.354 1650-1650/com.sunusi2sim.mobileattendance E/AndroidRuntime: Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'boolean java.util.List.add(java.lang.Object)' on a null object reference
06-24 17:41:05.354 1650-1650/com.sunusi2sim.mobileattendance E/AndroidRuntime: at com.sunusi2sim.mobileattendance.ViewAttendanceActivity.onCreate(ViewAttendanceActivity.java:31)
06-24 17:41:05.354 1650-1650/com.sunusi2sim.mobileattendance E/AndroidRuntime: at android.app.Activity.performCreate(Activity.java:6237)
06-24 17:41:05.354 1650-1650/com.sunusi2sim.mobileattendance E/AndroidRuntime: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
06-24 17:41:05.354 1650-1650/com.sunusi2sim.mobileattendance E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
06-24 17:41:05.354 1650-1650/com.sunusi2sim.mobileattendance E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
06-24 17:41:05.354 1650-1650/com.sunusi2sim.mobileattendance E/AndroidRuntime: at android.app.ActivityThread.-wrap11(ActivityThread.java) 
06-24 17:41:05.354 1650-1650/com.sunusi2sim.mobileattendance E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
06-24 17:41:05.354 1650-1650/com.sunusi2sim.mobileattendance E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102) 
06-24 17:41:05.354 1650-1650/com.sunusi2sim.mobileattendance E/AndroidRuntime: at android.os.Looper.loop(Looper.java:148) 

Your create table query is messing it up. Column name and its type should have a space in between and also comma is missing. Use this
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_AttendanceList_TABLE = "CREATE TABLE " + TABLE_AttendanceList + "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_reg_no + " TEXT,"
+ KEY_firstname + " TEXT,"
+ KEY_lastname + " TEXT,"
+ KEY_surname + " TEXT" + ")";
db.execSQL(CREATE_AttendanceList_TABLE);
}
You will have to uninstall the app first then run the updated code.

Related

E/SQLiteLog: (1) no such column: 100

I had a long time to fix this issue but couldn't solve it.
I was sure there were no wrong codes, but if I execute the emulator then the problem is when I click the specific item on the listview, it is shown, "open app again". I made database and put datas in it from csv file. Here are the codes:
word_db.csv
word_db.csv
DB_Word.java
public class DB_Word extends SQLiteOpenHelper {
public DB_Word(Context context){
super(context, "word.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table if not exists word (word_id integer primary key, category_id_fk integer, word_kor text, word_eng text, word_pro text, foreign key(category_id_fk) references category(category_id));");
System.out.println("Create table word success");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table word;");
onCreate(db);
}
}
Categories_wordview1.java
public class Categories_wordview1 extends AppCompatActivity {
ArrayAdapter<String> Adapter;
ListView wordlist;
DB_Word dbc;
SQLiteDatabase db;
String sql;
Cursor cursor;
String[] result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category_wv);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
wordlist = (ListView) findViewById(R.id.wordlist);
dbc = new DB_Word(this);
delete();
insertAll();
select();
}
public void delete(){
try {
System.out.println("delete complete");
db = dbc.getWritableDatabase();
db.execSQL("delete from word;");
} catch (Exception e) {
e.printStackTrace();
}
}
public void select(){
System.out.println("select");
try {
System.out.println("select try");
db = dbc.getReadableDatabase();
sql = "select word_kor, word_eng, word_pro from word;";
cursor = db.rawQuery(sql, null);
int count = cursor.getCount();
result = new String[count];
for(int i = 0; i < count; i++){
System.out.println("select for");
cursor.moveToNext();
String str_kor = cursor.getString(0);
String str_eng = cursor.getString(1);
String str_pro = cursor.getString(2);
result[i] = str_kor + " " + str_eng + " " + str_pro;
}
Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, result);
wordlist.setAdapter(Adapter);
wordlist.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
} catch (Exception e) {
e.printStackTrace();
}
}
public void insertAll(){
System.out.println("insert");
db = dbc.getWritableDatabase();
InputStream is = this.getResources().openRawResource(R.raw.word_db);
BufferedReader buffer = new BufferedReader(new InputStreamReader(is));
String tableName ="word";
String columns = "word_id, category_id_fk, word_kor";
String str1 = "insert into " + tableName + "(" + columns + ") values(";
String str2 = ");";
String line ="";
db.beginTransaction();
try {
System.out.println("transaction try");
while ((line = buffer.readLine()) != null) {
System.out.println("transaction while");
StringBuilder sb = new StringBuilder(str1);
String[] str = line.split(",");
sb.append(str[0] + ", ");
sb.append(str[1] + ", '");
sb.append(str[2] + "'");
sb.append(str2);
System.out.println(sb.toString());
db.execSQL(sb.toString());
//db.rawQuery(sb.toString(), null);
}
db.setTransactionSuccessful();
db.endTransaction();
}
catch (IOException ex) {
ex.printStackTrace();
}
finally {
try {
is.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
Here is the logcat showing:
12-28 00:04:05.106 1554-1651/? E/TaskPersister: File error accessing recents directory (directory doesn't exist?).
12-28 00:04:15.182 1554-1795/? I/ActivityManager: START u0 {cmp=com.example.project2/.Categories_word.Categories_wordview1} from uid 10009
12-28 00:04:15.194 1380-2231/? W/audio_hw_generic: Not supplying enough data to HAL, expected position 3729276 , only wrote 3728880
12-28 00:04:15.315 3259-3259/? I/System.out: delete complete
12-28 00:04:15.401 3259-3259/? I/System.out: Create table word success
12-28 00:04:15.409 3259-3259/? I/System.out: insert
12-28 00:04:15.411 3259-3259/? I/System.out: transaction try
12-28 00:04:15.412 3259-3259/? I/System.out: transaction while
12-28 00:04:15.412 3259-3259/? I/System.out: insert into word(word_id, category_id_fk, word_kor) values(100, 100, '안녕하세요');
12-28 00:04:15.413 3259-3259/? E/SQLiteLog: (1) no such column: 100
12-28 00:04:15.413 3259-3259/? D/AndroidRuntime: Shutting down VM
12-28 00:04:15.418 3259-3259/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.project2, PID: 3259
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.project2/com.example.project2.Categories_word.Categories_wordview1}: android.database.sqlite.SQLiteException: no such column: 100 (code 1): , while compiling: insert into word(word_id, category_id_fk, word_kor) values(100, 100, '안녕하세요');
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: android.database.sqlite.SQLiteException: no such column: 100 (code 1): , while compiling: insert into word(word_id, category_id_fk, word_kor) values(100, 100, '안녕하세요');
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
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.executeSql(SQLiteDatabase.java:1677)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1608)
at com.example.project2.Categories_word.Categories_wordview1.insertAll(Categories_wordview1.java:117)
at com.example.project2.Categories_word.Categories_wordview1.onCreate(Categories_wordview1.java:51)
at android.app.Activity.performCreate(Activity.java:6975)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6541) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 
12-28 00:04:15.483 1554-1566/? W/ActivityManager: Force finishing activity com.example.project2/.Categories_word.Categories_wordview1
12-28 00:04:15.503 1554-1566/? W/ActivityManager: Force finishing activity com.example.project2/.Categories
This is the issue:
E/SQLiteLog: (1) no such column: 100
android.database.sqlite.SQLiteException: no such column: 100 (code 1): , while compiling: insert into word(word_id, category_id_fk, word_kor) values(100, 100, '안녕하세요');
The first line of your CSV file contains an invisible control character (zero width no-break space) that is written by some Windows programs to mark the file as containing Unicode. Remove it.

getting runtime error "java.lang.IllegalStateException: Could not execute method for android:onClick" [closed]

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 10 months ago.
Improve this question
I'm not familiar with SQlite so I'm not sure if I'm passing incorrect data type to the DBHelper class or what I'm doing wrong.
This is my logcat
04-16 22:31:07.341 21052-21052/com.example.android.inputtest E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.inputtest, PID: 21052
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:5156)
at android.view.View$PerformClick.run(View.java:20755)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5835)
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:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5156)
at android.view.View$PerformClick.run(View.java:20755)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5835)
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:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Caused by: android.database.sqlite.SQLiteException: near "jordytip": syntax error (code 1): , while compiling: CREATE TABLE Tips(_id INTEGER PRIMARY KEY AUTOINCREMENT jordytip INTEGER mariatip INTEGER )
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1093)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:670)
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.executeSql(SQLiteDatabase.java:1795)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1726)
at com.example.android.inputtest.MyDBHandler.onCreate(MyDBHandler.java:32)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
at com.example.android.inputtest.MyDBHandler.addJordyTip(MyDBHandler.java:44)
at com.example.android.inputtest.MainActivity.submit(MainActivity.java:50)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5156)
at android.view.View$PerformClick.run(View.java:20755)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5835)
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:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
This is my main activity:
package com.example.android.inputtest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int jordyTips = 388;
int mariaTips = 388;
int more;
int less;
EditText tipInput;
TextView jordyOutput;
MyDBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tipInput = (EditText) findViewById(R.id.tipInput);
jordyOutput = (TextView) findViewById(R.id.jordyOutput);
dbHandler = new MyDBHandler(this,null, null,1);
}
public void submit (View view){
String value= tipInput.getText().toString();
int newTip =Integer.parseInt(value);
if (newTip % 2 == 0){
more = newTip/2;
less = newTip/2;
} else {
more = newTip/2 + 1;
less = newTip/2;
}
if (jordyTips <= mariaTips) {
jordyTips += more;
TipData tip = new TipData(more);
dbHandler.addJordyTip(tip);
printDatabase();
mariaTips += less;
} else {
jordyTips += less;
TipData tip = new TipData(less);
dbHandler.addJordyTip(tip);
printDatabase();
mariaTips += more;}
displayQuantity();
}
public void displayQuantity() {
TextView quantityTextView1 = jordyOutput;
TextView quantityTextView2 = (TextView)findViewById(R.id.mariaOutput);
quantityTextView1.setText((jordyTips-more)+ "+" + more + " " + String.valueOf(jordyTips));
quantityTextView2.setText(String.valueOf(mariaTips)+ "+" + less);
}
public void printDatabase(){
String dbString = dbHandler.databaseToString();
jordyOutput.setText(dbString);
tipInput.setText("");
}
}
This is my TipData class:
package com.example.android.inputtest;
/**
* Created by jordy on 4/16/2017.
*/
public class TipData {
private int _id;
private int _jordytip;
public TipData(int jordytip) {
this._jordytip = jordytip;
}
public void set_id(int _id) {
this._id = _id;
}
public void set_jordytip(int _jordytip) {
this._jordytip = _jordytip;
}
public int get_id() {
return _id;
}
public int get_jordytip() {
return _jordytip;
}
}
and this is my DBHandler class:
package com.example.android.inputtest;
/**
* Created by jordy on 4/16/2017.
*/
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class MyDBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "tips.db";
public static final String TABLE_NAME = "Tips";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_JORDYTIP = "jordytip";
public static final String COLUMN_MARIATIP = "mariatip";
public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_NAME + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT " +
COLUMN_JORDYTIP + " INTEGER " +
COLUMN_MARIATIP + " INTEGER " +
")";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
onCreate(db);
}
public void addJordyTip(TipData jordytip){
ContentValues values = new ContentValues();
values.put(COLUMN_JORDYTIP,jordytip.get_jordytip() );
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_NAME, null, values);
db.close();
}
public void deleteTip(String jordyTip){
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM" + TABLE_NAME + " WHERE " + COLUMN_JORDYTIP + "=\"" + jordyTip + "\";");
}
public String databaseToString(){
String dbString= "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM" + TABLE_NAME + "WHERE 1";
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
while(!c.isAfterLast()){
if (c.getString(c.getColumnIndex("jordytip"))!=null){
dbString += c.getString(c.getColumnIndex("jordytip"));
dbString += "\n";
}
}
db.close();
return dbString;
}
}
Getting this now:
04-17 00:17:58.181 20893-20893/com.example.android.inputtest E/SQLiteLog: (1) near "1": syntax error
04-17 00:17:58.191 20893-20893/com.example.android.inputtest E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.inputtest, PID: 20893
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:5156)
at android.view.View$PerformClick.run(View.java:20755)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5835)
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:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5156)
at android.view.View$PerformClick.run(View.java:20755)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5835)
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:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Caused by: android.database.sqlite.SQLiteException: near "1": syntax error (code 1): , while compiling: SELECT * FROM TipsWHERE 1
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1093)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:670)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:59)
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:1437)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1376)
at com.example.android.inputtest.MyDBHandler.databaseToString(MyDBHandler.java:63)
at com.example.android.inputtest.MainActivity.printDatabase(MainActivity.java:83)
at com.example.android.inputtest.MainActivity.submit(MainActivity.java:51)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5156)
at android.view.View$PerformClick.run(View.java:20755)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5835)
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:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
However when I add the space before where
String query = "SELECT * FROM " + TABLE_NAME + " WHERE 1";
I get "app not responding".
Caused by: android.database.sqlite.SQLiteException: near "jordytip":
syntax error (code 1): , while compiling: CREATE TABLE Tips(_id
INTEGER PRIMARY KEY AUTOINCREMENT jordytip INTEGER mariatip INTEGER )
At first Rectify Query
String query = "CREATE TABLE " + TABLE_NAME + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL ,"
+ COLUMN_JORDYTIP + " INTEGER ,"
+ COLUMN_MARIATIP + " INTEGER" + ")";

How to rectify this error iin Recyclerview with database

When i am trying to display the contacts in card view when i click on Button it shows fatal exception error it doesnot display cardview anyone can solve this programming with brillliance and another error is it show only one cardview when i click on again the app will be strucked?
Showcontacts.java
public class ShowContacts extends Activity
{
private SQLiteDatabase db;
DbOperations doo;
private List<Contacts> contactsList;
private RecyclerView rv;
private Cursor c;
String names,email,address;
int phone;
String read_query = "select * from"+ ContactsTask.ContactsEntry.TABLE_NAME;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recycle_layout);
doo = new DbOperations(this);
openDatabase();
rv = (RecyclerView)findViewById(R.id.recyclerview);
initializeData();
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
rv.setLayoutManager(linearLayoutManager);
rv.setHasFixedSize(true);
ContactAdapter cc = new ContactAdapter(contactsList);
rv.setAdapter(cc);
}
public void initializeData() {
contactsList = new ArrayList<>();
c = db.rawQuery(read_query,null);
c.moveToFirst();
while (!c.isLast())
{
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
}
c.isLast();
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
}
private void openDatabase() {
db = openOrCreateDatabase("contactDB", Context.MODE_PRIVATE,null);
}
}
Logacat error
06-28 08:57:43.107 568-568/com.example.anilkumar.contactstask E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.anilkumar.contactstask/com.example.anilkumar.contactstask.ShowContacts}: android.database.sqlite.SQLiteException: near "fromcontacts": syntax error: , while compiling: select * fromcontacts
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
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:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.database.sqlite.SQLiteException: near "fromcontacts": syntax error: , while compiling: select * fromcontacts
at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:68)
at android.database.sqlite.SQLiteProgram.compileSql(SQLiteProgram.java:143)
at android.database.sqlite.SQLiteProgram.compileAndbindAllArgs(SQLiteProgram.java:361)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:127)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:94)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:53)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:47)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1564)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1538)
at com.example.anilkumar.contactstask.ShowContacts.initializeData(ShowContacts.java:44)
at com.example.anilkumar.contactstask.ShowContacts.onCreate(ShowContacts.java:34)
at android.app.Activity.performCreate(Activity.java:4466)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981) 
at android.app.ActivityThread.access$600(ActivityThread.java:123) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4424) 
at java.lang.reflect.Method.invokeNative(Native Method) 
Another logact error
06-28 13:14:40.552 11252-11261/com.example.anilkumar.contactstask E/SQLiteDatabase: close() was never explicitly called on database '/data/data/com.example.anilkumar.contactstask/databases/contactDB'
android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here
at android.database.sqlite.SQLiteDatabase.<init>(SQLiteDatabase.java:1943)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:1007)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:986)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:962)
at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:1043)
at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:1036)
at android.app.ContextImpl.openOrCreateDatabase(ContextImpl.java:761)
at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:215)
at com.example.anilkumar.contactstask.ShowContacts.openDatabase(ShowContacts.java:66)
at com.example.anilkumar.contactstask.ShowContacts.onCreate(ShowContacts.java:33)
at android.app.Activity.performCreate(Activity.java:4466)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
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:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
Just update
String read_query = "select * from"+ ContactsTask.ContactsEntry.TABLE_NAME;
to
String read_query = "select * from "+ ContactsTask.ContactsEntry.TABLE_NAME;
Always close cursor. update your initializeData method
public void initializeData() {
try {
contactsList = new ArrayList<>();
try{
c = db.rawQuery(read_query,null);
c.moveToFirst();
while (!c.isLast())
{
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
}
c.isLast();
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
} catch (Exception e) {
// exception handling
} finally {
if(c != null){
c.close();
}
}
}

SQLiteDatabse giving unexpected errors

All files under my SQLite package are giving errors. As these are predefined classes and don't require or allow editing, I'm having a hard time making my project.
The codes are too long to be posted here.
For instance, these imports in SQLiteDatabase.java are appearing in red:
import android.database.sqlite.SQLiteDebug.DbStats;
import dalvik.system.CloseGuard;
and my logcat shows the following errors:
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: FATAL EXCEPTION: main
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: android.database.sqlite.SQLiteException: no such table: user (code 1): , while compiling: select * from user
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1253)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at com.example.abcd.helloworld.DatabaseHelper.insertUser(DatabaseHelper.java:40)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at com.example.abcd.helloworld.SignUp$1.onClick(SignUp.java:52)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.view.View.performClick(View.java:4240)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.view.View$PerformClick.run(View.java:17721)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:730)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:92)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.os.Looper.loop(Looper.java:137)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5103)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:525)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
02-04 12:47:55.781 2666-2666/? E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method)
All coding done by me seems to be correct.
The code for table creation is:
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "user.db";
private static final String TABLE_NAME = "user";
private static final String COLUMN_ID = "id";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_EMAIL = "email";
private static final String COLUMN_UNAME = "uname";
private static final String COLUMN_PASS = "pass";
SQLiteDatabase db;
private static final String TABLE_CREATE = "create table user (id integer primary key autoincrement," +
"name text, email text, uname text, pass text);";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE_CREATE);
this.db = db;
}
public void insertUser(User u) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
String query = "select * from user";
Cursor cursor = db.rawQuery(query, null);
int count = cursor.getCount();
values.put(COLUMN_ID, count);
values.put(COLUMN_NAME, u.getName());
values.put(COLUMN_EMAIL, u.getEmail());
values.put(COLUMN_UNAME, u.getUname());
values.put(COLUMN_PASS, u.getPass());
db.insert(TABLE_NAME, null, values);
}
public String searchPass(String uname) {
db = this.getReadableDatabase();
String query = "select uname, pass from" + TABLE_NAME;
Cursor cursor = db.rawQuery(query, null);
String a, b;
b = "not found";
if (cursor.moveToFirst()) {
do {
a = cursor.getString(0);
if (a.equals(uname)) {
b = cursor.getString(1);
break;
}
}
while (cursor.moveToNext());
}
db.close();
return b;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String query = "DROP TABLE IF EXISTS" + TABLE_NAME;
db.execSQL(query);
this.OnCreate(db);
}
private void OnCreate(SQLiteDatabase db) {
db.execSQL(TABLE_CREATE);
this.db = db;
}
}
You are using onCreate method twice in your code. Remove duplication.
Try below code:
public class DBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "user.db";
public DBHandler(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "create table user(" +
"id integer primary key autoincrement, " +
"name text, "+
"email text, "+
"uname text, "+
"pass text"+
");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String query = "drop table if exists user";
db.execSQL(query);
onCreate(db);
}
/*
Remaining code
Please do not add onCreate and onUpgrade method anymore.
*/
}
Your code seems to be ok, try to debug the SQLite code. Execute the statement outside the android code. Open your terminal and execute the sql statement, and after that execute .tables, this command will show you the existed tables in your db.
More info, you can find here,
http://www.tutorialspoint.com/sqlite/sqlite_create_table.htm

Fetching Sms Conversation in android

I am developing an android application in which I am displaying conversation List.
My code works fine in Samsung Galaxy S,Nexus one and Galaxy Nexus but the query is giving a problem in my Galaxy Grand phone.
Here is my code:
public ArrayList<String> getSMS()
{
ArrayList<String> sms = new ArrayList<String>();
Uri uriSMSURI = Uri.parse("content://mms-sms/conversations/");
Cursor cursor = getContentResolver().query(uriSMSURI, null, null, null, "date desc");
//cursor.moveToFirst();
while (cursor.moveToNext())
{
String address = cursor.getString(cursor.getColumnIndex("address"));
String body = cursor.getString(cursor.getColumnIndexOrThrow("body"));
String read = cursor.getString(cursor.getColumnIndexOrThrow("read"));
//to fetch the contact name of the conversation
String contactName = address;
Uri Nameuri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(address));
Cursor cs= getContentResolver().query(Nameuri, new String[]{PhoneLookup.DISPLAY_NAME},PhoneLookup.NUMBER+"='"+address+"'",null,null);
if(cs.getCount()>0)
{
cs.moveToFirst();
contactName = cs.getString(cs.getColumnIndex(PhoneLookup.DISPLAY_NAME));
}
sms.add(contactName + "\n"+body);
}
return sms;
}
The following is the stackTrace:
06-24 17:26:21.744: E/AndroidRuntime(12764): FATAL EXCEPTION: main
06-24 17:26:21.744: E/AndroidRuntime(12764): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ssn.sms/com.ssn.sms.test}: java.lang.NullPointerException
06-24 17:26:21.744: E/AndroidRuntime(12764): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
06-24 17:26:21.744: E/AndroidRuntime(12764): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
06-24 17:26:21.744: E/AndroidRuntime(12764): at android.app.ActivityThread.access$700(ActivityThread.java:140)
06-24 17:26:21.744: E/AndroidRuntime(12764): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
06-24 17:26:21.744: E/AndroidRuntime(12764): at android.os.Handler.dispatchMessage(Handler.java:99)
06-24 17:26:21.744: E/AndroidRuntime(12764): at android.os.Looper.loop(Looper.java:137)
06-24 17:26:21.744: E/AndroidRuntime(12764): at android.app.ActivityThread.main(ActivityThread.java:4935)
06-24 17:26:21.744: E/AndroidRuntime(12764): at java.lang.reflect.Method.invokeNative(Native Method)
06-24 17:26:21.744: E/AndroidRuntime(12764): at java.lang.reflect.Method.invoke(Method.java:511)
06-24 17:26:21.744: E/AndroidRuntime(12764): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
06-24 17:26:21.744: E/AndroidRuntime(12764): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
06-24 17:26:21.744: E/AndroidRuntime(12764): at dalvik.system.NativeStart.main(Native Method)
06-24 17:26:21.744: E/AndroidRuntime(12764): Caused by: java.lang.NullPointerException
06-24 17:26:21.744: E/AndroidRuntime(12764): at android.os.Parcel.readException(Parcel.java:1431)
06-24 17:26:21.744: E/AndroidRuntime(12764): at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:188)
06-24 17:26:21.744: E/AndroidRuntime(12764): at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:140)
06-24 17:26:21.744: E/AndroidRuntime(12764): at android.content.ContentProviderProxy.query(ContentProviderNative.java:366)
06-24 17:26:21.744: E/AndroidRuntime(12764): at android.content.ContentResolver.query(ContentResolver.java:372)
06-24 17:26:21.744: E/AndroidRuntime(12764): at android.content.ContentResolver.query(ContentResolver.java:315)
06-24 17:26:21.744: E/AndroidRuntime(12764): at com.ssn.sms.test.getSMS(test.java:157)
06-24 17:26:21.744: E/AndroidRuntime(12764): at com.ssn.sms.test.onCreate(test.java:74)
06-24 17:26:21.744: E/AndroidRuntime(12764): at android.app.Activity.performCreate(Activity.java:5206)
06-24 17:26:21.744: E/AndroidRuntime(12764): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
06-24 17:26:21.744: E/AndroidRuntime(12764): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2074)
06-24 17:26:21.744: E/AndroidRuntime(12764): ... 11 more
I also referred to the below Link and used it,but still it is the same
SGS-3 bug related to SMS conversations list?
try this i have use function all sms return in json string
public JSONObject getsms()
{
JSONObject result = null;
JSONArray jarray = null;
String link[] = {"content://sms/inbox","content://sms/sent","content://sms/draft"};
try {
jarray = new JSONArray();
result = new JSONObject();
Uri uri = Uri.parse("content://sms/");
Cursor c= act.getContentResolver().query(uri, null, null ,null,null);
act.startManagingCursor(c);
// Read the sms data and store it in the list
if(c.moveToFirst()) {
for(int i=0; i < c.getCount(); i++) {
result.put("body",c.getString(c.getColumnIndexOrThrow("body")).toString());
result.put("date",c.getString(c.getColumnIndexOrThrow("date")).toString());
result.put("read",c.getString(c.getColumnIndexOrThrow("read")).toString());
result.put("type",c.getString(c.getColumnIndexOrThrow("type")).toString());
if((c.getString(c.getColumnIndexOrThrow("type")).toString()).equals("3"))
{
//Cursor cur= getContentResolver().query("", null, null ,null,null);
//startManagingCursor(cur);
String threadid = c.getString(c.getColumnIndexOrThrow("thread_id")).toString();
Cursor cur= act.getContentResolver().query(Uri.parse("content://mms-sms/conversations?simple=true"), null, "_id ="+threadid ,null,null);
act.startManagingCursor(cur);
if(cur.moveToFirst())
{
String recipientId = cur.getString(cur.getColumnIndexOrThrow("recipient_ids")).toString();
cur= act.getContentResolver().query(Uri.parse("content://mms-sms/canonical-addresses"), null, "_id = " + recipientId, null, null);
act.startManagingCursor(cur);
if(cur.moveToFirst())
{
String address = cur.getString(cur.getColumnIndexOrThrow("address")).toString();
result.put("address",address);
cur.close();
}
}
}else
{
result.put("address",c.getString(c.getColumnIndexOrThrow("address")).toString());
}
jarray.put(result);
result = new JSONObject();
c.moveToNext();
}
}
c.close();
result.put("smslist", jarray);
//result = new JSONObject(jarray.toString());
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}

Categories

Resources