Table is not found in SQLiteDatabase - java

I am facing this strange problem that I searched alot, but no use so far.
The following code I am using to retrieve SQLite database using a DBHelper that extends from openhelper class.
public class DBHelper extends SQLiteOpenHelper {
public static final int DB_VERSION = 1;
public static final String DB_NAME = "cp.db";
public static final String DB_PATH = "/data/data/abdulla.com.test/databases/";
public static final String ID = "no";
public static final String NAME = "name";
public static final String FORMULA = "formula";
public static final String MW = "mw";
public static final String OMEGA = "omega";
public static final String TC = "tc";
public static final String PC = "pc";
SQLiteDatabase db;
Cursor cursor;
ArrayList<String> elementName;
public DBHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists elements");
this.onCreate(db);
}
public List<Element> getAllElements() {
List<Element> elementList = new ArrayList<Element>();
// Select All Query
Cursor cursor = null;
String selectQuery = "SELECT * FROM elements";
SQLiteDatabase db = this.getReadableDatabase();
cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Element element = new Element();
element.setNo(Integer.parseInt(cursor.getString(0)));
element.setFormula(cursor.getString(1));
element.setName(cursor.getString(2));
// Adding contact to list
elementList.add(element);
} while (cursor.moveToNext());
}
// return contact list
return elementList;
}
}
This is capture from MainActivity class
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DBHelper helper = new DBHelper(this);
List<Element> elementList = helper.getAllElements();
for(Element element : elementList){
String log = "no: "+element.getNo();
Log.d("No: ", log);
}
}
}
I am getting this error:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{abdulla.com.test/abdulla.com.test.MainActivity}:
android.database.sqlite.SQLiteException: no such table: elements (code 1):
, while compiling: SELECT * FROM elements
I know that elements table is there
Any help?

Probably the issue is in your onUpgrade() method. If your database doesn't have version, application tries to upgrade it, and drops your table (db.execSQL("drop table if exists elements");).
Solution: set version to DB or change onUpgrade() method (delete DROP statement).

Related

Android SQLite data fetching

Every time I run a "select *" query from my SQLite, the app keeps stopping. I've deduced it to it calling the database helper every time, but I don't know how to fix it.
MainActivity.java
public class MainActivity extends AppCompatActivity {
DatabaseHelper databaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().setStatusBarColor(Color.WHITE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
displayUsers();
}
public void displayUsers() {
Cursor cursor = databaseHelper.getAllUsers(); //here's where the error keeps on happening
if(cursor.getCount() == 0) {
Toast.makeText(this, "none", Toast.LENGTH_SHORT).show();
}
}
}
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "reminders.db";
public static final String T_1 = "tbl_users";
public static final String T1_COL_1 = "ID";
public static final String T1_COL_2 = "FIRST_NAME";
public static final String T1_COL_3 = "MIDDLE_INITIAL";
public static final String T1_COL_4 = "LAST_NAME";
public static final String T1_COL_5 = "PHONE";
public static final String T1_COL_6 = "EMAIL";
public static final String T1_COL_7 = "USERNAME";
public static final String T1_COL_8 = "PASSWORD";
public DatabaseHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, 1);
SQLiteDatabase database = this.getWritableDatabase();
}
...//other functions
public Cursor getAllUsers() {
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery("select * from " + T_1, null);
return cursor;
}
}
Your DatabaseHelper class doesn’t create any object cause you didn’t call new DatabaseHelper (this). Thats why databasehelper return null.
You can try those line in onCreate method,
databaseHelper= new DatabaseHelper(this);
Before returning cursor close your database
public Cursor getAllUsers() {
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery("select * from " + T_1, null);
database.close(); // Added
return cursor;
}
In following function at first your have to initialize database to get WritableDatabase in DatabaseHelper class.
public void displayUsers() {
databaseHelper = DatabaseHelper(MainActivity.this)
Cursor cursor = databaseHelper.getAllUsers();
if(cursor.getCount() == 0) {
Toast.makeText(this, "none", Toast.LENGTH_SHORT).show();
}
}

Missing Syntax for displaying data in listview [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I am a new to android world. I have a problem with the code. My listview is not displaying ArrayList method. It is returning blank as the value in the listview.
What could be the issue to this problem.
here is my db file which has the ArrayList execute select events. This will fetch the data from the database and then display it to listview.
public class UniversityFinderDB extends SQLiteOpenHelper{
private static final int DATABASE_VERSION= 1;
static final String DATABASE_NAME="universities.db";
private static final String TABLE_NAME="universityFinder";
private static final String COLUMN_UNIVID="univId";
private static final String COLUMN_UNIVERSITYNAME="univName";
private static final String COLUMN_SCORE="score";
SQLiteDatabase db;
private static final String TABLE_CREATE = "create table universityFinder (univId integer primary key not null, univName varchar not null, score integer not null);";
public UniversityFinderDB(Context context) {
super(context, DATABASE_NAME,null ,DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(TABLE_CREATE);
}
public void executeEventInsert(String name, String score){
String query="INSERT INTO universityFinder(univName, score) VALUES('"+name+"','"+score+"');";
db.execSQL(query);
}
public ArrayList<HashMap<String,String>> executeSelectEvents(int input){
String query="select * from "+TABLE_NAME+ " where " +COLUMN_SCORE+" >="+input;
Cursor cursor= db.rawQuery(query,null);
ArrayList<HashMap<String,String>> events=new ArrayList<>();
while (cursor.moveToNext()){
HashMap<String,String> event=new HashMap<>();
String colUniversityId=cursor.getColumnName(0);
String colUniversityIdValue=cursor.getString(0);
String colUniversityName=cursor.getColumnName(1);
String colUniversityValue=cursor.getString(1);
event.put(colUniversityId,colUniversityIdValue);
event.put(colUniversityName,colUniversityValue);
events.add(event);
}
return events;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String query = "DROP TABLE IF EXISTS "+TABLE_NAME;
db.execSQL(query);
}
}
and the listview class where it'll display the data from the database.
public class ListviewFinderUniversities extends AppCompatActivity {
UniversityFinderDB myDB;
ArrayList<HashMap<String, String>> eventData;
ListView finderListview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview_finder_universities);
myDB = new UniversityFinderDB(this);
finderListview = (ListView) findViewById(R.id.finderListView);
myDB.executeEventInsert("UCI","101");
myDB.executeEventInsert("UeI","100");
myDB.executeEventInsert("UgI","105");
myDB.executeEventInsert("UjI","107");
myDB.executeEventInsert("ewI","109");
loadUnivFromDb();
}
private void createUnivAdapter(){
String from[]={"univId","univName"};
int to[] = {R.id.eventId, R.id.evenLabel};
SimpleAdapter adapter = new SimpleAdapter(getApplicationContext(), eventData, R.layout.uni_item_finder, from, to);
finderListview.setAdapter(adapter);
}
private void loadUnivFromDb() {
int gre = getIntent().getIntExtra("Gre",0);
ArrayList<HashMap<String, String>> data= myDB.executeSelectEvents(gre);
if(data.size()>0){
eventData=data;
createUnivAdapter();
}else {
Toast.makeText(getApplicationContext(),"NoEvents",Toast.LENGTH_SHORT).show();
}
}
}
You are getting null object exception because you have not initialise SQLiteDatabase before do operation
Just need to replace your method
public void executeEventInsert(String name, String score){
//For write data to your database
SQLiteDatabase db = this.getWritableDatabase();
String query="INSERT INTO universityFinder(univName, score) VALUES('"+name+"','"+score+"');";
db.execSQL(query);
}
and
public ArrayList<HashMap<String,String>> executeSelectEvents(int input){
String query="select * from "+TABLE_NAME+ " where " +COLUMN_SCORE+" >="+input;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor= db.rawQuery(query,null);
ArrayList<HashMap<String,String>> events=new ArrayList<>();
while (cursor.moveToNext()){
HashMap<String,String> event=new HashMap<>();
String colUniversityId=cursor.getColumnName(0);
String colUniversityIdValue=cursor.getString(0);
String colUniversityName=cursor.getColumnName(1);
String colUniversityValue=cursor.getString(1);
event.put(colUniversityId,colUniversityIdValue);
event.put(colUniversityName,colUniversityValue);
events.add(event);
}
return events;
}
Happy coding :)

android-studio: using SQLite class correct

I'm trying to use a SQLite Class in Android Studio outside the class. My error is:
Error:(42, 51) error: incompatible types: bluetooth cannot be converted to Context
"Bluetooth" is my calling class, I wan't receive some strings and write them to a SQLite DB.
How can I use the class correctly?
I try this: Sqlite database can not be create , but no luck. I don't understand the problem. :-/
Thanks for any help.
Here's my code:
DatabaseHelper.java:
public class DatabaseHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "aprs";
private final Context context;
private SQLiteDatabase database;
private DBHelper helper;
private class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// SQL statement to create book table
String CREATE_POS_TABLE = "CREATE TABLE pos ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"call TEXT, " +
"time TEXT )";
// create books table
db.execSQL(CREATE_POS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older books table if existed
db.execSQL("DROP TABLE IF EXISTS books");
// create fresh books table
this.onCreate(db);
}
}
public DatabaseHelper(Context c) {
context = c;
}
public DatabaseHelper openDB(){
helper = new DBHelper(context);
database = helper.getWritableDatabase();
return this;
}
public void addPos(String call, String time) {
ContentValues values = new ContentValues();
values.put("call", call);
values.put("time", time);
database.insert("pos",null, values);
Log.e("DB", "written");
database.close();
}
public void getAllPos() {
// 1. build the query
String query = "SELECT * FROM pos;";
// 2. get reference to writable DB
Cursor cursor = database.rawQuery(query, null);
if (cursor.moveToFirst()) {
do {
Log.d("db", cursor.toString());
} while (cursor.moveToNext());
}
}
}
And this is bluetooth.java, my calling class:
public class bluetooth extends Thread {
<snip>
public void convertString() {
DatabaseHelper entry = new DatabaseHelper(this);
entry.addPos("text","test");
}
<snap>
}

Trying to make Android database for the first time using SQLite, my app keeps crashing [duplicate]

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 7 years ago.
Ive been trying to create a simplistic database on Android that has a table that gets three values,one for id, one for event desc. and the other for time which is on string format. problem is that it crashes for no reason and i cant find why. here is MainActivity:
public class MainActivity extends ListActivity {
private static final int MENU_EDIT = Menu.FIRST+1;
private static final int MENU_REMOVE = Menu.FIRST+2;
ArrayList <String> Events = new ArrayList<String>();
ArrayList <Integer> ids = new ArrayList<Integer>();
ListView lview = (ListView)findViewById(R.id.listview);
DBHandler db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// registerForContextMenu(getListView());
db = new DBHandler(this);
// db.addInfo(new Day_Info("stef", "123"));
loadList();
}
private void loadList() {
try{
Events.clear();
ids.clear();
for(Day_Info e:db.getAllInfo()){
Events.add(e.getEvents()+", "+e.getTime());
ids.add(e.getId());
}
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_2,Events);
lview.setAdapter(adapter);
}
catch(Exception e){
Toast.makeText(this, "Problem Loading List", Toast.LENGTH_LONG).show();
}
}
AND HERE is my database class:
class DBHandler extends SQLiteOpenHelper {
private static final String TABLE_NAME = "INFO";
private static final String DATABASE_NAME = "Schedule";
private static final String EVENT_DB ="event";
private static final String TIME_DB = "time";
public DBHandler(Context context) {
super(context, DATABASE_NAME, null, 1);
//Log.d("Database", "Database created");
}
#Override
public void onCreate(SQLiteDatabase db) {
String TABLE_CREATION = "CREATE TABLE "+ TABLE_NAME +" (_id INTEGER PRIMARY KEY AUTOINCREMENT, EVENT TEXT not null,TIME TEXT not null)";
db.execSQL(TABLE_CREATION);
Log.d("Database", "Tables created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion) {
}
void addInfo(Day_Info info){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(EVENT_DB, info.getEvents());
cv.put(TIME_DB, info.getTime());
db.insert(TABLE_NAME, null, cv);
db.close();
}
public ArrayList<Day_Info> getAllInfo(){
ArrayList<Day_Info> List = new ArrayList<Day_Info>();
String selectQuery = "SELECT * FROM "+TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if(cursor.moveToFirst()){
do{
Day_Info info= new Day_Info();
info.setId(Integer.parseInt(cursor.getString(0)));
info.setEvents(cursor.getString(1));
info.setTime(cursor.getString(2));
List.add(info);
}while(cursor.moveToNext());
cursor.close();
}
return List;
}
}
Your coloumn at position 0 is an integer type
`_id INTEGER PRIMARY KEY AUTOINCREMENT`
But you are trying to fetch it as string
info.setId(Integer.parseInt(cursor.getString(0)));
instead use
info.setId(cursor.getInt(0));
Without logcat, i think this is the error you are facing. if you show your logs i will help more to determine the issue
you also declare _id as integer on need to convert cursor position (0) into integer put cursor.getInt(0)

cannot bind data from sqlliteData-base to simplecursoradaptor

I don´t know how to connect the data my array String [] station = {"København", "Grenaa", "Hanstholm"}; in my MyListActivity to the simpleCursorAdaptor
I have made a SQLitedatabase, a Helperclass and anActivityclass - but I get the error " java.lang.IllegalArgumentException: column 'København' does not exist". I have additional code - but this code should be sufficient I think.
Any help would really be appreciated.
public class MyListActivity extends ListActivity {
String [] station = {"København", "Grenaa", "Hanstholm"};
Cursor stations;
SQLiteDatabase db;
SimpleCursorAdapter cursorAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DBAdapter dbaAdapter = new DBAdapter(this);
dbaAdapter.open();
Cursor stations = dbaAdapter.getStations();
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1,stations,station,new int [] {
android.R.id.text1
});
setListAdapter(cursorAdapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Cursor cursor = (Cursor) l.getItemAtPosition(position);
String value = station[(int)id];
Intent intent = new Intent();
intent.putExtra(TravelActivity.SELECTED_STATION_NAME, cursor.getString(cursor.getColumnIndexOrThrow("station")));
this.setResult(RESULT_OK,intent);
cursor.close();
finish();
}
#Override
protected void onDestroy() {
db.close();
}
}
public class MyHelper extends SQLiteOpenHelper {
public static final String DB_NAME = "database";
String DESTINATION = "DESTINATION";
int version = 1;
public MyHelper(Context context) {
super(context, "travel.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String TRAVELS = ( "create table travels (_id integer primary key autoincrement, start text, slut text)");
String STATIONS = ( "create table stations (_id integer primary key autoincrement, start text)" );
db.execSQL(TRAVELS);
db.execSQL(STATIONS);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS ");
onCreate(db);
}
}
public class DBAdapter {
MyHelper myHelper;
SQLiteDatabase db;
String TABLE_STATIONS = "stations";
String TABLE_TRAVELS = "travels";
String START = "start";
String SLUT = "slut";
String ID_COL = "_id";
Context context;
public static final int NUMBER_TRAVELS = 1;
public DBAdapter(Context context) {
this.context = context;
myHelper = new MyHelper(context);
}
public void open() {
db = myHelper.getWritableDatabase();
}
public void close() {
myHelper.close();
}
public Cursor getTravels() {
Cursor cursor = db.query(TABLE_TRAVELS,new String[]{ID_COL,START,SLUT},null,null,null,null,START);
return cursor;
}
public void saveTravels(String start, String slut) {
ContentValues values = new ContentValues();
values.put(START,start);
values.put(SLUT,slut);
db.insert(TABLE_TRAVELS,null,values);
}
public Cursor getStations() {
Cursor cursor = db.query(TABLE_STATIONS,new String[]{ID_COL,START},null,null,null,null,START);
return cursor;
}
public void saveStations(String start) {
ContentValues values = new ContentValues();
values.put(START,start);
db.insert(TABLE_TRAVELS,null,values);
}
}
The error is generated by your SimpleCursorAdapter constructor :
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,stations,station,new int [] {
android.R.id.text1
});
The 4td parameter is the column names, so a String array with START and/or SLUT values in your case.

Categories

Resources