Android sqlite:could not execute method onclick - java

I'm trying to login using the database by using the id of the specific members.
But the app crashes with log error.
Following various other similar errors, I included "c1.movetoFirst();" and "c2.movetoFirst();". But still its not working.
The logcat error is:
FATAL EXCEPTION: main
Process: no.nordicsemi.android.nrftoolbox, PID: 13196
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:4785)
at android.view.View$PerformClick.run(View.java:19888)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5276)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:911)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:706)
Caused by: java.lang.reflect.InvocationTargetException
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick
Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
at android.database.AbstractCursor.checkPosition(AbstractCursor.java:432)
at android.database.AbstractWindowedCursor.checkPosition
at android.database.AbstractWindowedCursor.getInt
at no.nordicsemi.android.nrftoolbox.LoginActivity.login
The LoginActivity is :
public class LoginActivity extends AppCompatActivity {
TextView email;
TextView pass;
private no.nordicsemi.android.nrftoolbox.myDbAdapter mydb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
email = (TextView) findViewById(R.id.editText_mail);
pass = (TextView) findViewById(R.id.editText_pass);
mydb = new no.nordicsemi.android.nrftoolbox.myDbAdapter(this);
}
public void register(View v) {
Intent goToSecond = new Intent();
goToSecond.setClass(this, Register_Page.class);
startActivity(goToSecond);
}
public void login(View v) {
Cursor c1 = mydb.getEmail(email);
c1.moveToFirst();
Cursor c2 = mydb.getpass(pass);
c2.moveToFirst();
int id1=c1.getInt(0);
int id2=c2.getInt(0);
if (id1>0 & id2>0) {
Intent goToSecond = new Intent();
goToSecond.setClass(this, Profile.class);
startActivity(goToSecond);
} else
message(getApplicationContext(), "not valid user");
}
}
The myDbHelper is:
public class myDbAdapter extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 4;
public static final String DATABASE_NAME = "MyDBName.db";
public static final String CONTACTS_TABLE_NAME = "contacts";
public static final String CONTACTS_COLUMN_ID = "id";
public static final String CONTACTS_COLUMN_NAME = "name";
public static final String CONTACTS_COLUMN_EMAIL = "email";
public static final String CONTACTS_COLUMN_PASS = "password";
public static final String CONTACTS_COLUMN_DOB = "dateofbirth";
public static final String CONTACTS_COLUMN_GENDER = "gender";
public static final String CONTACTS_COLUMN_PHONE="phone";
public static final String CONTACTS_COLUMN_CITY="city";
public static final String CONTACTS_COLUMN_WALLET="wallet";
private HashMap hp;
public myDbAdapter(Context context) {
super(context, DATABASE_NAME , null, 4);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"CREATE TABLE " + CONTACTS_TABLE_NAME + "(" + CONTACTS_COLUMN_ID + " INTEGER PRIMARY KEY," + CONTACTS_COLUMN_NAME + " TEXT," + CONTACTS_COLUMN_EMAIL + " TEXT," + CONTACTS_COLUMN_PASS +" TEXT," + CONTACTS_COLUMN_DOB + " TEXT," + CONTACTS_COLUMN_GENDER + " TEXT," + CONTACTS_COLUMN_PHONE + " INTEGER," + CONTACTS_COLUMN_CITY + " TEXT,"+CONTACTS_COLUMN_WALLET + " INTEGER DEFAULT 0);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
public boolean insertContact (String name, String email, String pass, String dob, String gender, String phone, String city) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("email", email);
contentValues.put("password", pass);
contentValues.put("dateofbirth", dob);
contentValues.put("gender", gender);
contentValues.put("phone", phone);
contentValues.put("city", city);
db.insert("contacts", null, contentValues);
return true;
}
//Cursor csr = no.nordicsemi.android.nrftoolbox.CommonSQLiteUtilities.getAllRowsFromTable(db,"contacts",true‌​,null)
//no.nordicsemi.android.nrftoolbox.CommonSQLiteUtilities.LogCursorData(csr);
public int updateWallet(String amount,Integer id)
{
SQLiteDatabase db=this.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put("wallet",amount);
return(db.update("contacts",contentValues,"id = ? ",new String[] { Integer.toString(id)}));
}
public Cursor getData(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts where id="+id+"", null );
return res;
}
public Cursor getEmail(TextView email)
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor= db.rawQuery( "select id from contacts where email='"+email.getText().toString()+"'",null);
return cursor;
}
public Cursor getpass(TextView pass)
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor= db.rawQuery( "select id from contacts where password='"+pass.getText().toString()+"'",null);
return cursor;
}
}
Where is the error? And how can it be recitified?

You better check whether cursor has next before invoking movetoFirst as in
Cursor c1 = mydb.getEmail(email);
if(c1.getcount() > 0)
c1.moveToFirst();
and make sure, email id is already in database and check for case sensitive.

Related

ID won't save in long format in database Sqlite

I'm making an Android Note Taking app, which save a note and display it in list of notes. if you touch each note it show a title and details of it in another layout. i can save note and i can show them in list but my problem is when i try to use intent to show that specific note's title and details.
what is do is use intent.putExtra("ID",...) and get that intent and show the note's detail and title with use of its ID. but i get "android.database.CursorIndexOutOfBoundsException" error and app crash.
this is part of my Note class:
public class Note {
private String Title, Content, Date, Time;
private long ID;
Note(){}
Note(String Title,String Content,String Date,String Time){
this.Title = Title;
this.Content = Content;
this.Date = Date;
this.Time = Time;
}
Note(long ID,String Title,String Content,String Date,String Time) {
this.ID = ID;
this.Title = Title;
this.Content = Content;
this.Date = Date;
this.Time = Time;
}
this is my NoteDataBase:
public class NoteDataBase extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_NAME = "notedbs";
private static final String DATABASE_TABLE = "notestables";
//column name for database tables
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_CONTENT = "content";
private static final String KEY_DATE = "date";
private static final String KEY_TIME = "time";
public NoteDataBase(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db){
//create table
String query = "CREATE TABLE " + DATABASE_TABLE + "("+
KEY_ID + " INT PRIMARY KEY," +
KEY_TITLE + " TEXT," +
KEY_CONTENT + " TEXT," +
KEY_DATE + " TEXT," +
KEY_TIME + " TEXT" + ")";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
if(oldVersion >= newVersion) {
return;
} else {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public long addNote(Note note) {
SQLiteDatabase db= this.getWritableDatabase();
ContentValues c = new ContentValues();
c.put(KEY_TITLE,note.getTitle());
c.put(KEY_CONTENT,note.getContent());
c.put(KEY_DATE,note.getDate());
c.put(KEY_TIME,note.getTime());
long ID = db.insert(DATABASE_TABLE,"null",c);
//c.put(KEY_ID,ID);
Log.d("Inserted", "addNote: note with id number " + KEY_ID + " has been inserted");
return ID;
}
public Note getNote(long ID){
//Select * from DatabaseTable where id = 1
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(DATABASE_TABLE,
new String []{KEY_ID,KEY_TITLE,KEY_CONTENT,
KEY_DATE,KEY_TIME},KEY_ID + "=?",
new String[]{String.valueOf(ID)},
null, null,null);
if(cursor != null)
cursor.moveToFirst();
return new Note(cursor.getLong(0), cursor.getString(1), cursor.getString(2),
cursor.getString(3),cursor.getString(4));
}
public List<Note> getNotes() {
SQLiteDatabase db = getReadableDatabase();
List<Note> allNotes = new ArrayList<>();
// Select * from databaseTable
String query = "SELECT * FROM "+ DATABASE_TABLE;
Cursor cursor = db.rawQuery(query,null);
if(cursor.moveToFirst()){
do{
Note note = new Note();
note.setID(cursor.getLong(0));
note.setTitle(cursor.getString(1));
note.setContent(cursor.getString(2));
note.setDate(cursor.getString(3));
note.setTime(cursor.getString(4));
allNotes.add(note);
}while(cursor.moveToNext());
}
return allNotes;
}
}
this is my DetailActivity :
public class DetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
Intent intent = getIntent();
Long id = intent.getLongExtra("ID",0);
NoteDataBase db = new NoteDataBase(this);
Note note = db.getNote(id);
Toast.makeText(this, "Title is "+ note.getTitle(), Toast.LENGTH_SHORT).show();
my error is in lines of both my Intent in DetailActivity and getNote method of NoteDataBase.
By defining the column id of your table as:
INT PRIMARY KEY
it is not defined as AUTOINCREMENT, so in every row that you add to the table, the column id is null, because you don't provide any value for it.
The value that is returned by the method addNote(), when you insert a new row, is the value of the column rowid and not the column id.
You must define the column as:
INTEGER PRIMARY KEY
You can also add AUTOINCREMENT in the above definition, if you don't want any deleted ids to be reused.
After you make this change you must uninstall the app from the device, so that the db is deleted and rerun to recreate the db and the table.
Also in the method getNote(), first check with moveToFirst() if the query returned any row:
public Note getNote(long ID){
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(DATABASE_TABLE,
new String []{KEY_ID,KEY_TITLE,KEY_CONTENT,
KEY_DATE,KEY_TIME},KEY_ID + "=?",
new String[]{String.valueOf(ID)},
null, null,null);
if(cursor.moveToFirst())
return new Note(
cursor.getLong(0), cursor.getString(1), cursor.getString(2),
cursor.getString(3),cursor.getString(4)
);
else return null;
}

ANDROID SQLITE DATABASE insert [duplicate]

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 7 years ago.
the database class
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "MyDBName.db";
public static final String CONTACTS_TABLE_NAME = "contacts";
public static final String CONTACTS_COLUMN_ID = "id";
public static final String CONTACTS_COLUMN_NAME = "name";
public static final String CONTACTS_COLUMN_EMAIL = "email";
public static final String CONTACTS_COLUMN_STREET = "street";
public static final String CONTACTS_COLUMN_CITY = "place";
public static final String CONTACTS_COLUMN_PHONE = "phone";
private HashMap hp;
public DBHelper(Context context)
{
super(context, DATABASE_NAME , null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table contacts " +
"(id integer primary key, name text,phone text,email text, street text,place text)"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
public boolean insertContact (String name, String phone, String email, String street,String place)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("phone", phone);
contentValues.put("email", email);
contentValues.put("street", street);
contentValues.put("place", place);
db.insert("contacts", null, contentValues);
return true;
}
public Cursor getData(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts where id="+id+"", null );
return res;
}
public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, CONTACTS_TABLE_NAME);
return numRows;
}
public boolean updateContact (Integer id, String name, String phone, String email, String street,String place)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("phone", phone);
contentValues.put("email", email);
contentValues.put("street", street);
contentValues.put("place", place);
db.update("contacts", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
public Integer deleteContact (Integer id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("contacts",
"id = ? ",
new String[] { Integer.toString(id) });
}
public ArrayList<String> getAllCotacts()
{
ArrayList<String> array_list = new ArrayList<String>();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts", null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME)));
res.moveToNext();
}
return array_list;
}
the activity class
public class MainActivity extends AppCompatActivity {
Button login;
EditText student_id;
EditText password;
TextView message;
DBHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DBHelper(this);
login = (Button) findViewById(R.id.button);
student_id = (EditText) findViewById(R.id.student_id);
password = (EditText) findViewById(R.id.password);
message=(TextView)findViewById(R.id.logResult);
message.setText("");
db.insertContact("jon","9595749944","r#hotmail.com","a","usa");
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String pass = password.getText().toString();
int id = Integer.parseInt(student_id.getText().toString());
int result= db.numberOfRows();
if (result == 1) {
message.setText("Invalid User");
} else {
message.setText("valid User" );
}
}
});
}
But,When the button is pressed the insertion in not occur and app close
where is the problem?? help?????????????? I want to insert data in database when the app is created how?
your call is outside of the onclick , first try:
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
db.insertContact("jon","9595749944","r#hotmail.com","a","usa");
}
});

Android NullpointerException when trying to retrieve data from SQLiteOpenHelper

I get following error in logcat when trying to retrieve all SQLite rows from SQLiteOpenHelper.
Caused by: java.lang.NullPointerException at notes.dev.tauhid.com.mynotes.fragment.MyNotes.onCreateView(MyNotes.java:89)
My SQLiteOpenHelper class is
public class DatabaseHandlerNotes extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "my_notes";
private static final String TABLE_NOTES = "my_notes_table";
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_DESCRIPTION = "phone_number";
private static final String KEY_DATE = "date";
private static final String KEY_REMINDER_DATE = "reminder_date";
private static final String KEY_CATEGORY = "category";
private static final String KEY_LOCK = "lock";
public DatabaseHandlerNotes(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_NOTES_TABLE = "CREATE TABLE " + TABLE_NOTES + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_TITLE + " TEXT,"
+ KEY_DESCRIPTION + " TEXT," + KEY_DATE + " INTEGER," + KEY_REMINDER_DATE + " INTEGER," + KEY_CATEGORY + " INTEGER," + KEY_LOCK + " TEXT" + ")";
db.execSQL(CREATE_NOTES_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NOTES);
onCreate(db);
}
public void addNote(Note note) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE, note.getTitle());
values.put(KEY_DESCRIPTION, note.getDescription());
values.put(KEY_DATE, note.getDate());
values.put(KEY_REMINDER_DATE, note.getReminderDate());
values.put(KEY_CATEGORY, note.getCategory());
values.put(KEY_LOCK, note.getLock());
db.insert(TABLE_NOTES, null, values);
db.close();
}
public Note getNote(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NOTES, new String[] { KEY_ID,
KEY_TITLE, KEY_DESCRIPTION, KEY_DATE, KEY_REMINDER_DATE, KEY_CATEGORY }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Note note = new Note(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2), Integer.parseInt(cursor.getString(3)), Integer.parseInt(cursor.getString(4)), Integer.parseInt(cursor.getString(5)), cursor.getString(6));
return note;
}
public List<Note> getAllNotes() {
List<Note> noteList = new ArrayList<Note>();
String selectQuery = "SELECT * FROM " + TABLE_NOTES;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Note note = new Note();
note.setID(Integer.parseInt(cursor.getString(0)));
note.setTitle(cursor.getString(1));
note.setDescription(cursor.getString(2));
note.setDate(Integer.parseInt(cursor.getString(3)));
note.setReminderDate(Integer.parseInt(cursor.getString(4)));
note.setCategory(Integer.parseInt(cursor.getString(5)));
note.setLock(cursor.getString(6));
noteList.add(note);
} while (cursor.moveToNext());
}
return noteList;
}
public int updateNote(Note note) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE, note.getTitle());
values.put(KEY_DESCRIPTION, note.getDescription());
values.put(KEY_DATE, note.getDate());
values.put(KEY_REMINDER_DATE, note.getReminderDate());
values.put(KEY_CATEGORY, note.getCategory());
values.put(KEY_LOCK, note.getLock());
// updating row
return db.update(TABLE_NOTES, values, KEY_ID + " = ?",
new String[] { String.valueOf(note.getID()) });
}
public void deleteNote(Note note) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NOTES, KEY_ID + " = ?",
new String[] { String.valueOf(note.getID()) });
db.close();
}
public int getNotesCount() {
String countQuery = "SELECT * FROM " + TABLE_NOTES;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
return cursor.getCount();
}
And in my Fragment class where i want to retrieve all rows
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
databaseHandlerNote = new DatabaseHandlerNotes(getActivity());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.my_notes_fragment_notes, container, false);
ListView allNotes = (ListView) rootView.findViewById(R.id.my_notes_all);
List<Note> noteList = databaseHandlerNote.getAllNotes();
for (Note note : noteList) {
Note noteEach = new Note();
noteEach.setID(note.getID());
noteEach.setTitle(note.getTitle());
noteEach.setDescription(note.getDescription());
noteEach.setCategory(note.getCategory());
noteEach.setLock(note.getLock());
noteEach.setDate(note.getDate());
noteEach.setReminderDate(note.getReminderDate());
this.customNotesList.add(noteEach);
}
customNoteAdapter = new CustomNoteAdapter(getActivity(), customNotesList);
allNotes.setAdapter(customNoteAdapter);
return rootView;
}
Here 89th line in onCreateView is
List<Note> noteList = databaseHandlerNote.getAllNotes();
Thanks in advance.
The problem is that onActivityCreated() is called after onCreateView(). Thus your databaseHandlerNote hasn't been created yet, and trying to use it will result in a NullPointerException.
Check out the Fragment lifecycle diagram from the Fragment documentation.
From Fragment lifecircle, onCreateView() is called before onActivityCreated(), so when you call:
List<Note> noteList = databaseHandlerNote.getAllNotes();
in onCreateView(), databaseHandlerNote is not yet created, then you got exception. So solution is that:
move your:
databaseHandlerNote = new DatabaseHandlerNotes(getActivity());
from onActivityCreated() to onCreate()

Android SQLite Colunm not found error [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 8 years ago.
Improve this question
Im trying to store data from some editTexts on a local android database and then eventually show it on a listview, but right now Im getting an error that says a column doesnt exist, I was following a tutorial on android hive so some of the variable names might look weird, but everything should be accurate.
StackTrace
2038-12038/com.example.adrian.legioncheck_in E/SQLiteLog﹕ (1) table contacts has no column named Longitude
08-25 12:12:19.121 12038-12038/com.example.adrian.legioncheck_in E/SQLiteDatabase﹕ Error inserting Latitude=-85 Longitude=50 POnumber=255902
android.database.sqlite.SQLiteException: table contacts has no column named Longitude (code 1): , while compiling: INSERT INTO contacts(Latitude,Longitude,POnumber) VALUES (?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:923)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:534)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1523)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1395)
at com.example.adrian.legioncheck_in.DatabaseHandler.addContact(DatabaseHandler.java:67)
at com.example.adrian.legioncheck_in.MapsActivity.SaveAction(MapsActivity.java:67)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3850)
at android.view.View.performClick(View.java:4470)
at android.view.View$PerformClick.run(View.java:18593)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5867)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674)
at dalvik.system.NativeStart.main(Native Method)
Database Handle.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "POnumber";
private static final String KEY_PH_NO = "Latitude";
private static final String KEY_LONG = "Longitude";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + KEY_LONG + " TEXT" +")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new contact
/* line 67 */ void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getPO());
values.put(KEY_PH_NO, contact.getLat());
values.put(KEY_LONG, contact.getLong());
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO, KEY_LONG }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2), cursor.getString(3));
// return contact
return contact;
}
// Getting All Contacts
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setPO(cursor.getString(1));
contact.setLat(cursor.getString(2));
contact.setLong(cursor.getString(3));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// Updating single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getPO());
values.put(KEY_PH_NO, contact.getLat());
values.put(KEY_LONG, contact.getLong());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
contact.java
public class Contact {
//private variables
int _id;
String _PO;
String _lat;
String _longi;
// Empty constructor
public Contact(){
}
// constructor
public Contact(int id, String PO, String _lat, String _longi){
this._id = id;
this._PO = PO;
this._lat = _lat;
this._longi = _longi;
}
// constructor
public Contact(String PO, String _lat, String _longi){
this._PO = PO;
this._lat = _lat;
this._longi = _longi;
}
// getting ID
public int getID(){
return this._id;
}
// setting id
public void setID(int id){
this._id = id;
}
// getting name
public String getPO(){
return this._PO;
}
// setting name
public void setPO(String PO){
this._PO = PO;
}
// getting phone number
public String getLat(){
return this._lat;
}
// setting phone number
public void setLat(String lat){
this._lat = lat;
}
public String getLong()
{
return this._longi;
}
public void setLong(String longi)
{
this._longi = longi;
}
}
Button that saves data to database:
public void SaveAction(View view)
{
EditText po = (EditText)findViewById(R.id.POnumber);
String PO = po.getText().toString();
EditText textlat = (EditText)findViewById(R.id.textLat);
String LAT = textlat.getText().toString();
EditText textlong = (EditText)findViewById(R.id.textLong);
String LONG = textlong.getText().toString();
DatabaseHandler db = new DatabaseHandler(MapsActivity.this);
db.addContact(new Contact(PO,LAT,LONG));
// Reading all Data
Log.d("Reading: ", "Reading all inputs..");
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
String log = "Id: "+cn.getID()+" ,PO number: " + cn.getPO() + " ,Latitude: " + cn.getLat() + " ,Longitude: " + cn.getLong();
// Writing Data to log
Log.d("Name: ", log);
}
}
KEY_PH_NO + " TEXT" + KEY_LONG + " TEXT" +")"
Add the missing , before KEY_LONG:
KEY_PH_NO + " TEXT," + KEY_LONG + " TEXT" +")"
Uninstall your app so the onCreate() is run again. See
When is SQLiteOpenHelper onCreate() / onUpgrade() run?
for more about that.

My program can not find tables in sqlite database on Android

I have SQLite database file (which I did not create in this program, and it has its tables and datas), I open it in my android program, but when I write SELECT statement program can not find tables and I get error:
Error: no such table: Person
This is code:
public class SQLiteAdapter {
private DbDatabaseHelper databaseHelper;
private static String dbfile = "/data/data/com.example.searchpersons/databases/";
private static String DB_NAME = "Person.db";
static String myPath = dbfile + DB_NAME;
private static SQLiteDatabase database;
private static final int DATABASE_VERSION = 3;
private static String table = "Person";
private static Context myContext;
public SQLiteAdapter(Context ctx) {
SQLiteAdapter.myContext = ctx;
databaseHelper = new DbDatabaseHelper(SQLiteAdapter.myContext);
}
public static class DbDatabaseHelper extends SQLiteOpenHelper {
public DbDatabaseHelper(Context context) {
super(context, DB_NAME, null, DATABASE_VERSION);
dbfile = "/data/data/" + context.getPackageName() + "/databases/";
myPath = dbfile + DB_NAME;
//this.myContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
public SQLiteDatabase open() {
try {
database = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
Log.v("db log", "database exist open");
} catch (SQLiteException e) {
Log.v("db log", "database does't exist");
}
if (database != null && database.isOpen())
return database;
else {
database = databaseHelper.getReadableDatabase();
Log.v("db log", "database exist helper");
}
return database;
}
public Cursor onSelect(String firstname, String lastname) {
Log.v("db log", "database exist select");
Cursor c = database.rawQuery("SELECT * FROM " + table + " where Firstname='" + firstname + "' And Lastname='" + lastname + "'", null);
c.moveToFirst();
return c;
}
public void close() {
if (database != null && database.isOpen()) {
database.close();
}
}
}
And this is button click function:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button btn1 = (Button) rootView.findViewById(R.id.button1);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText t = (EditText) rootView.findViewById(R.id.editText1);
String name = t.getText().toString();
EditText tt = (EditText) rootView.findViewById(R.id.editText2);
String lastname = tt.getText().toString();
if (name.length() == 0 || lastname.length() == 0) {
Toast.makeText(rootView.getContext(), "Please fill both box", Toast.LENGTH_LONG).show();
} else {
GridView gridview = (GridView) rootView.findViewById(R.id.gridView1);
List < String > li = new ArrayList < String > ();
ArrayAdapter < String > adapter = new ArrayAdapter < String > (rootView.getContext(), android.R.layout.simple_gallery_item, li);
try {
SQLiteAdapter s = new SQLiteAdapter(rootView.getContext());
s.open();
Cursor c = s.onSelect(name, lastname);
if (c != null) {
if (c.moveToFirst()) {
do {
String id = c.getString(c.getColumnIndex("ID"));
String name1 = c.getString(c.getColumnIndex("Firstname"));
String lastname1 = c.getString(c.getColumnIndex("Lastname"));
String personal = c.getString(c.getColumnIndex("PersonalID"));
li.add(id);
li.add(name1);
li.add(lastname1);
li.add(personal);
gridview.setAdapter(adapter);
} while (c.moveToNext());
}
} else {
Toast.makeText(rootView.getContext(), "There is no data", Toast.LENGTH_LONG).show();
}
c.close();
s.close();
} catch (Exception e) {
Toast.makeText(rootView.getContext(), "Error : " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
});
return rootView;
}
I check database in SQLite Database Browser, everything is normal (There are tables and data), but program still can not find them.
I added sqlitemanager to eclipse and it can not see tables too:
There is only one table android_metadata and there are no my tables.
Can anyone help me?
I thought about it for about a week, the answer is very simple. I resolved the problem so:
from sqlitemanager
I added database from that button.
And now everything works fine ;)
In oncreate you have to create your db. I am sending you my db class.
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DbAdapter extends SQLiteOpenHelper {
private static DbAdapter mDbHelper;
public static final String DATABASE_NAME = "demoDb";
public static final String TABLE_Coin= "coin_table";
public static final String TABLE_Inbox= "inbox";
public static final String TABLE_Feature= "feature";
public static final String TABLE_Time= "time";
public static final String TABLE_Deduct_money= "deduct_time";
public static final String TABLE_Unread_message= "unread_message";
public static final String COLUMN_Email= "email";
public static final String COLUMN_Appearence= "appearence";
public static final String COLUMN_Drivability= "drivability";
public static final String COLUMN_Fuel= "fuel";
public static final String COLUMN_Insurance= "insurance";
public static final String COLUMN_Wow= "wow";
public static final String COLUMN_CurrentValue= "current_value";
public static final String COLUMN_coin = "name";
public static final String COLUMN_seenTime = "seen";
public static final String COLUMN_number_of_times = "number_of_times";
public static final String COLUMN_name = "name";
public static final String COLUMN_type = "type";
public static final String COLUMN_text = "text";
public static final String COLUMN_image = "image";
public static final String COLUMN_created_time = "created_time";
public static final String COLUMN_unread = "unread";
// ****************************************
private static final int DATABASE_VERSION = 1;
private final String DATABASE_CREATE_BOOKMARK = "CREATE TABLE "
+ TABLE_Coin + "(" + COLUMN_coin
+ " Varchar,"+COLUMN_Email +" Varchar, UNIQUE("
+ COLUMN_Email + ") ON CONFLICT REPLACE)";
private final String DATABASE_CREATE_BOOKMARK1 = "CREATE TABLE "
+ TABLE_Feature + "(" + COLUMN_Appearence
+ " Integer,"+COLUMN_Email +" Varchar ,"+COLUMN_name +" Varchar ,"+COLUMN_Drivability +" Integer ,"+COLUMN_Wow +" Integer,"+COLUMN_CurrentValue +" Integer,"+COLUMN_Fuel +" Integer,"+COLUMN_Insurance +" Integer, UNIQUE("
+ COLUMN_Email + ") ON CONFLICT REPLACE)";
private final String DATABASE_CREATE_BOOKMARK2 = "CREATE TABLE "
+ TABLE_Time + "(" + COLUMN_Email +" Varchar ,"+COLUMN_seenTime +" Integer,"+COLUMN_number_of_times +" Integer, UNIQUE("
+ COLUMN_Email + ") ON CONFLICT REPLACE)";
private final String DATABASE_CREATE_BOOKMARK3 = "CREATE TABLE "
+ TABLE_Deduct_money + "(" + COLUMN_seenTime
+ " Varchar,"+ COLUMN_number_of_times
+ " Integer,"+COLUMN_Email +" Varchar, UNIQUE("
+ COLUMN_Email + ") ON CONFLICT REPLACE)";
private final String DATABASE_CREATE_BOOKMARK4 = "CREATE TABLE "
+ TABLE_Inbox + "(" + COLUMN_created_time
+ " DATETIME,"+ COLUMN_image
+ " Varchar,"
+ COLUMN_type
+ " Varchar,"+ COLUMN_name
+ " Varchar,"+ COLUMN_text
+ " Varchar,"+COLUMN_Email +" Varchar)";
private final String DATABASE_CREATE_BOOKMARK5 = "CREATE TABLE "
+ TABLE_Unread_message + "(" + COLUMN_unread
+ " Varchar,"+COLUMN_Email +" Varchar, UNIQUE("
+ COLUMN_Email + ") ON CONFLICT REPLACE)";
private DbAdapter(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static synchronized DbAdapter getInstance(Context context) {
if (mDbHelper == null) {
mDbHelper = new DbAdapter(context);
}
return mDbHelper;
}
/**
* Tries to insert data into table
*
* #param contentValues
* #param tablename
* #throws SQLException
* on insert error
*/
public void insertQuery(ContentValues contentValues, String tablename)
throws SQLException {
try {
final SQLiteDatabase writableDatabase = getWritableDatabase();
writableDatabase.insert(tablename, null, contentValues);
// writableDatabase.insertWithOnConflict(tablename, null,
// contentValues,SQLiteDatabase.CONFLICT_REPLACE);
} catch (Exception e) {
e.printStackTrace();
}
}
// public void insertReplaceQuery(ContentValues contentValues, String tablename)
// throws SQLException {
//
// try {
// final SQLiteDatabase writableDatabase = getWritableDatabase();
// writableDatabase.insertOrThrow(tablename, null, contentValues);
//
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
//
// /**
// * Update record by ID with contentValues
// *
// * #param id
// * #param contentValues
// * #param tableName
// * #param whereclause
// * #param whereargs
// */
public void updateQuery(ContentValues contentValues, String tableName,
String whereclause, String[] whereargs) {
try {
final SQLiteDatabase writableDatabase = getWritableDatabase();
writableDatabase.update(tableName, contentValues, whereclause,
whereargs);
} catch (Exception e) {
e.printStackTrace();
}
}
public Cursor fetchQuery(String query) {
final SQLiteDatabase readableDatabase = getReadableDatabase();
final Cursor cursor = readableDatabase.rawQuery(query, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
public Cursor fetchQuery(String query, String[] selectionArgs) {
final SQLiteDatabase readableDatabase = getReadableDatabase();
final Cursor cursor = readableDatabase.rawQuery(query, selectionArgs);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
public void delete(String table) {
final SQLiteDatabase writableDatabase = getWritableDatabase();
writableDatabase.delete(table, null, null);
}
public void delete(String table, String whereClause, String[] selectionArgs) {
final SQLiteDatabase writableDatabase = getWritableDatabase();
writableDatabase.delete(table, whereClause, selectionArgs);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE_BOOKMARK);
db.execSQL(DATABASE_CREATE_BOOKMARK1);
db.execSQL(DATABASE_CREATE_BOOKMARK2);
db.execSQL(DATABASE_CREATE_BOOKMARK3);
db.execSQL(DATABASE_CREATE_BOOKMARK4);
db.execSQL(DATABASE_CREATE_BOOKMARK5);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Coin);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Feature);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Time);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Deduct_money);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Inbox);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Unread_message);
onCreate(db);
}
}
You are messing up the paths.
Please clean up every definition or reference to dbfile and myPath.You are initializing them in the definition with some values (probably copy-pasted), then giving them new different values in the DbDatabaseHelper constructor. And the helper will not use these paths, it will just create the database in the default directory.
Then after this, in the open method you are calling SQLiteDatabase.openDatabase with your intended paths. Use instead getReadableDatabase and getWritableDatabase from the Helper.

Categories

Resources