teH
I am trying to get started with SQLite databases. Unfortunately, on my onCreate method, my database is never getting created and crashing can anyone help me out.
Error I get is: No such table: firstdatabase.
This is my MySQLiteHelper class:
public class MySQLiteHelper extends SQLiteOpenHelper {
//Database instance
//private static MySQLiteHelper sInstance;
//Database name
private static final String DATABASE_NAME = "TestDB";
//Table name
private static final String TABLE_NAME = "firstdatabase";
//column names of the table
private static final String KEY_ID = "id";
private static final String KEY_ISBN = "isbn";
private static final String KEY_INGREDIENTS = "ingredients";
//Database Version
private static final int DATABASE_VERSION = 2;
// Log TAG for debugging purpose
private static final String TAG = "SQLiteAppLog";
//Method that will ensure only one instance of the database is created.
/* public static synchronized MySQLiteHelper getsInstance(Context context){
if(sInstance == null){
sInstance = new MySQLiteHelper(context.getApplicationContext());
}
return sInstance;
}
*/
// Constructor
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.d(TAG, "Inside SQLITEHELPER METHOD()");
}
#Override
public void onCreate(SQLiteDatabase db) {
//SQLite statement to create a table called 'TestDB'.
String CREATE_PROTOTYPE_TABLE = "CREATE TABLE " + TABLE_NAME + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_ISBN + " TEXT,"
+ KEY_INGREDIENTS + " TEXT" + ")";
Log.d(TAG, "DB created");
db.execSQL(CREATE_PROTOTYPE_TABLE);
//Log.d(TAG, "DB created");
}
// onUpdate() is invoked when you upgrade the database scheme.
// Don’t consider it seriously for the sample app.
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older prototype table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
this.onCreate(db);
}
public void addIngredientsToTable(Product product){
Log.d(TAG, "adding ingredients to table");
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ISBN, product.getIsbn());
values.put(KEY_ISBN, product.getIngredients());
db.insert(TABLE_NAME,null, values);
db.close();
}
//Method to get the ingredients list based on the isbn passed in.
public ArrayList<String> getIngredients(String isbn){
ArrayList<String> ingredientList = new ArrayList<String>();
String isbnPassedIn = isbn;
String query = "SELECT isbn, ingredients FROM " + TABLE_NAME + " WHERE isbn = " + isbnPassedIn;
//Getting instance to a readable database
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
if(cursor.moveToFirst()){
do{
ingredientList.add(cursor.getString(1));
ingredientList.add(cursor.getString(2));
}while (cursor.moveToFirst());
}
Log.d(TAG, "Inside getIngredients()");
return ingredientList;
}
//Method to get all the list of products in the datbase.
public ArrayList<Product> getAllProducts(){
ArrayList<Product> productList = new ArrayList<Product>();
String selectQuery = "SELECT * FROM firstdatabase";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery,null);
if(cursor.moveToFirst()){
do{
Product product = new Product();
product.setId(Integer.parseInt(cursor.getString(0)));
product.setIsbn(cursor.getString(1));
product.setIngredients(cursor.getString(2));
productList.add(product);
}while (cursor.moveToNext());
}
return productList;
}
Java file:
public class BarCodeActivity extends AppCompatActivity {
MySQLiteHelper db1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bar_code);
db1 = new MySQLiteHelper(this);
Log.d("Insert", "Inserting data...");
db1.addIngredientsToTable(new Product(1, "89470001033", "Lowfat yogurt, mango, milk, water"));
Log.d("Reading: ", "Reading all products");
ArrayList<Product> products = db1.getAllProducts();
for(Product product : products){
String log = "Id: " + product.getId() + ", ISBN: " + product.getIsbn() + ", Ingredients: " + product.getIngredients();
Log.d("Product:", log);
}
Your CREATE_PROTOTYPE_TABLE String is not correct, the semicolon is missing(;) :
Use the following:
String CREATE_PROTOTYPE_TABLE = "CREATE TABLE " + TABLE_NAME + "("
+ KEY_ID + " INTEGER PRIMARY KEY autoincrement," + KEY_ISBN + " TEXT,"
+ KEY_INGREDIENTS + " TEXT" + ");";
Related
When I was releasing an apk on google play I had to use a different package name cause of "com.example". I tried this and I get crash after testing an application. Before that everything was ok. I can send a manifest.
There are my errors.
My classes
Details.java
public class Details extends AppCompatActivity {
NoteDatabase db;
Note note;
TextView mDetails;
TextView clientDetails;
TextView timeDetails;
TextView nameDetails;
TextView detailsDetails;
ImageView noteDetails;
private Bitmap getImageFromByte(byte[] zdjecie){
return BitmapFactory.decodeByteArray(zdjecie, 0, zdjecie.length);
}
#SuppressLint("WrongThread")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDetails = findViewById(R.id.detailsOfNote);
mDetails.setMovementMethod(new ScrollingMovementMethod());
clientDetails = findViewById(R.id.clientOfNote);
timeDetails = findViewById(R.id.timeofNote);
nameDetails = findViewById(R.id.nameOfNote);
detailsDetails = findViewById(R.id.detailsOfNote);
noteDetails = findViewById(R.id.noteImage);
Intent i = getIntent();
Long id = i.getLongExtra("ID", 0);
db = new NoteDatabase(this);
note = db.getNote(id);
getSupportActionBar().setTitle(note.getTitle());
mDetails.setText(note.getContent());
clientDetails.setText(note.getTitle());
timeDetails.setText(note.getTime());
nameDetails.setText(note.getName());
detailsDetails.setText(note.getDetails());
noteDetails.setImageBitmap(stringToImage(note.getImage()));
Toast.makeText(this, "Podgląd klienta", Toast.LENGTH_SHORT).show();
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
db.deleteNote(note.getID());
Toast.makeText(getApplicationContext(), "Klient usunięty", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),klienci.class));
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.edit_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(item.getItemId() == R.id.editNote){
Toast.makeText(this, "Edytowanie notatki", Toast.LENGTH_SHORT).show();
Intent i = new Intent(this,Edit.class);
i.putExtra("ID",note.getID());
startActivity(i);
}
return super.onOptionsItemSelected(item);
}
private void goToMain() {
Intent i = new Intent(this,klienci.class);
startActivity(i);
}
private Bitmap stringToImage(String imgString){
byte[] decodedString = Base64.decode(imgString,Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString,0,decodedString.length);
return decodedByte;
}
NoteDatabase.java
public class NoteDatabase extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 42;
private static final String DATABASE_NAME = "notedbs";
private static final String DATABASE_TABLE = "notestables";
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";
private static final String KEY_PHONE = "phone";
private static final String KEY_CLIENT = "client";
private static final String KEY_DETAILS = "details";
private static final String KEY_IMAGE = "image";
NoteDatabase(Context context) {
super(context, DATABASE_NAME,null,DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE "+ DATABASE_TABLE + "("+ KEY_ID+" INT PRIMARY KEY,"+
KEY_TITLE + " TEXT,"+
KEY_CONTENT + " TEXT,"+
KEY_DATE + " TEXT,"+
KEY_TIME + " TEXT,"+
KEY_CLIENT + " TEXT,"+
KEY_DETAILS + " TEXT,"+
KEY_PHONE + " TEXT,"+
KEY_IMAGE + " TEXT"+")";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if(oldVersion >= newVersion)
return;
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_PHONE,note.getPhone());
c.put(KEY_CLIENT,note.getClient());
c.put(KEY_DETAILS,note.getDetails());
c.put(KEY_DATE,note.getDate());
c.put(KEY_TIME,note.getTime());
c.put(KEY_IMAGE,note.getImage());
long ID = db.insert(DATABASE_TABLE,null, c);
Log.d("Inserted", "ID -> " + ID);
return ID;
}
public Note getNote(long id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(DATABASE_TABLE,new String[] {KEY_ID,KEY_TITLE,KEY_CONTENT,KEY_PHONE,KEY_CLIENT,KEY_DETAILS,KEY_DATE,KEY_TIME,KEY_IMAGE}, 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)
,cursor.getString(5)
,cursor.getString(6)
,cursor.getString(7)
,cursor.getString(8));
}
public List<Note> getNotes() {
SQLiteDatabase db = this.getReadableDatabase();
List<Note> allNotes = new ArrayList<>();
String query = "SELECT * FROM " + DATABASE_TABLE + " ORDER BY "+KEY_TITLE+" ASC";
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.setDetails(cursor.getString(2));
note.setPhone(cursor.getString(3));
note.setClient(cursor.getString(4));
note.setContent(cursor.getString(5));
note.setDate(cursor.getString(6));
note.setTime(cursor.getString(7));
note.setImage(cursor.getString(8));
allNotes.add(note);
}while(cursor.moveToNext());
}
return allNotes;
}
public int editNote(Note note){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues c = new ContentValues();
Log.d("Edited", "Edited Title: -> "+ note.getTitle() + "\n ID -> "+note.getZdjecie());
c.put(KEY_TITLE,note.getTitle());
c.put(KEY_CONTENT,note.getContent());
c.put(KEY_PHONE,note.getPhone());
c.put(KEY_CLIENT,note.getClient());
c.put(KEY_DETAILS,note.getDetails());
c.put(KEY_DATE,note.getDate());
c.put(KEY_TIME,note.getTime());
c.put(KEY_IMAGE,note.getImage());
return db.update(DATABASE_TABLE,c,KEY_ID +"=?",new String[]{String.valueOf(note.getID())});
}
void deleteNote(long id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(DATABASE_TABLE, KEY_ID + "=?", new String[]{String.valueOf(id)});
db.close();
}
You are trying to get 0 index in the database. Every time you add a new Note its ID will be 0. So, change your database KEY_ID to AUTOINCREMENT.
String query = "CREATE TABLE " + DATABASE_TABLE + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
KEY_TITLE + " TEXT," +
KEY_CONTENT + " TEXT," +
KEY_DATE + " TEXT," +
KEY_TIME + " TEXT," +
KEY_PIES + " TEXT," +
KEY_RASAPSA + " TEXT," +
KEY_TEL + " TEXT," +
KEY_ZDJECIE + " TEXT" + ")";
db.execSQL(query);
Then check your cursor not null in
getNote()
I'm developing an app which is used for contacts and for this i used sqlite database to store name and number so i want to filter name and number for searching for which
i tried that query but
it's not working for me
any solution for problem i used like and "=" both?
public boolean onQueryTextChange(String newText) {
try {
final String temp = newText.toLowerCase();
final ArrayList<Map> map1 = new ArrayList();
try {
dbhelper =new FeedReaderDbHelper(getActivity());
SQLiteDatabase db=dbhelper.getReadableDatabase();
String projection[]={FeedReaderContract.FeedEntry.COLUMNS_TITLE,FeedReaderContract.FeedEntry.COLUMN_SUB_TITLE};
Cursor cursor =db.query(FeedReaderContract.FeedEntry.TABLE_NAME,projection ,FeedReaderContract.FeedEntry.COLUMNS_TITLE+"= ?",new String[]{newText},null,null,null);
while(cursor.moveToFirst()){
String name = cursor.getString(cursor.getColumnIndex(FeedReaderContract.FeedEntry.COLUMNS_TITLE));
String number = cursor.getString(cursor.getColumnIndex(FeedReaderContract.FeedEntry.COLUMN_SUB_TITLE));
Map<String, Object> map = new HashMap();
map.put(name, number);
if (name.toLowerCase().contains(temp)) {
map1.add(map);
Phone.this.adapter.Filter(map1);
}
} }
catch(Exception e){
System.out.print(Retriving_list);
}
}catch(Exception e){
Toast.makeText(getActivity(), First_Retrive_Data, Toast.LENGTH_SHORT).show();
}
//DbHelperClass
public class FeedReaderDbHelper extends SQLiteOpenHelper{
public static final int DB_VERSION =1;
public static String getDataBASE_NAME() {
return DataBASE_NAME;
}
public static void setDataBASE_NAME(String dataBASE_NAME) {
DataBASE_NAME = dataBASE_NAME;
}
public static String DataBASE_NAME;
Context context;
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + FeedReaderContract.FeedEntry.TABLE_NAME + "(" +
FeedReaderContract.FeedEntry._ID + "INTEGER PRIMARY KEY," +
FeedReaderContract.FeedEntry.COLUMNS_TITLE + " TEXT ," +
FeedReaderContract.FeedEntry.COLUMN_SUB_TITLE + " TEXT UNIQUE)";
private static final String SQL_DELETE_ENTRIES =
"DROP TABLE IF EXISTS " + FeedReaderContract.FeedEntry.TABLE_NAME;
public FeedReaderDbHelper(Context context) {
super(context, FeedReaderDbHelper.getDataBASE_NAME(), null, DB_VERSION);
this.context=context;
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(SQL_CREATE_ENTRIES);
}
void addContactValues(FeedReaderDbHelper dbhelper ,String name ,String number){
SQLiteDatabase db= dbhelper.getWritableDatabase();
ContentValues values =new ContentValues();
values.put(FeedReaderContract.FeedEntry.COLUMNS_TITLE ,name);
values.put(FeedReaderContract.FeedEntry.COLUMN_SUB_TITLE,number);
long rows= db.insertWithOnConflict(FeedReaderContract.FeedEntry.TABLE_NAME,null,values,SQLiteDatabase.CONFLICT_IGNORE);
if (rows==-1){
// Toast.makeText(context, String.valueOf(rows)+"not interested", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(context, String.valueOf(rows)+"inserted", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL(SQL_DELETE_ENTRIES);
onCreate(sqLiteDatabase);
}
}
It's not clear what exact do you want, but if you want do get only rows with given values, it should looks like this:
String mSearchString = "what do you want to search";
String selection = setupSelectionString();
cursor = database.query(NoteContract.NoteEntry.NOTES_TABLE_NAME, projection, selection, selectionArgs,
null, null, sortOrder);
private String setupSelectionString() {
String selection = null;
if (mSearchString != null) {
selection = FeedReaderContract.FeedEntry.COLUMNS_TITLE + " LIKE '%"
+ mSearchString + "%'"
+ " OR " + FeedReaderContract.FeedEntry.COLUMN_SUB_TITLE + " LIKE '%"
+ mSearchString + "%'";
}
return selection;
It works in my app
I have a database made with OpenSQLiteHelper which where I am getting a String of names from and adding it to a ListView. I can never see the first item in the database and the ListView only starts from the second item in the Database.
I am getting Strings from COL_2 (names) in my database.
ListView Class
public class Castawaylist extends AppCompatActivity {
private static final String TAG = "CastList";
myDbAdapter mydb;
private ListView castview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_castawaylist);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
castview = (ListView) findViewById(R.id.listView);
mydb = new myDbAdapter(this);
populateCastList();
}
String score;
private void populateCastList()
{
//get the data and append to the list
Log.d(TAG, "populateCastList: Displaying List of Castaways.");
Cursor data = mydb.getData();
//int save = data.getInt(2);
ArrayList<String> listData = new ArrayList<>();
while(data.moveToNext())
{
listData.add(data.getString(1) +
" " + data.getInt(2)); //get value from database at column 1, then add it to array list
}
ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData); //Creates the list adapter and set it
castview.setAdapter(adapter);
castview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String nametest = "";
int u = 0;
while(!adapterView.getItemAtPosition(i).toString().substring(u,u+1).equals(" "))
{
nametest = nametest + adapterView.getItemAtPosition(i).toString().substring(u, u+1);
u = u + 1;
}
Log.d(TAG, "onItemClick: You Clicked on " + nametest);
Cursor data = mydb.getItemID(nametest); //Get the ID associated with that name
int itemID = -1;
while(data.moveToNext())
{
itemID = data.getInt(0);
}
if(itemID > -1)
{
Log.d(TAG, "onItemClick: The ID is: " + itemID);
Intent editCastaway = new Intent(Castawaylist.this, EditCastaway.class);
editCastaway.putExtra("id", itemID);
editCastaway.putExtra("name", nametest);
//editCastaway.putExtra("score", data.getInt(2));
startActivity(editCastaway);
}else
{
toastText("No ID associated with that name");
}
}
});
}
private void toastText(String text)
{
Toast.makeText(this,text, Toast.LENGTH_SHORT).show();
}}
ListView XML Code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listView"/>
</LinearLayout>
Database Helper Class
public class myDbAdapter extends SQLiteOpenHelper{
public static final String DATABASE_NAME = "Castaways.db";
public static final String TABLE_NAME = "Survivor_Table";
public static final String COL_1 = "ID";
public static final String COL_2 = "NAME";
public static final String COL_3 = "MARK";
public myDbAdapter(Context context) {
super(context, DATABASE_NAME, null, 2);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME +" (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,MARK INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean addData(String name,int score) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,name);
contentValues.put(COL_3,score);
long result = db.insert(TABLE_NAME,null ,contentValues);
if(result == -1)
return false;
else
return true;
}
public Cursor getData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+TABLE_NAME,null);
return res;
}
public Cursor getItemID(String name){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT " + COL_1 + " FROM " + TABLE_NAME +
" WHERE " + COL_2 + " = '" + name + "'";
Cursor data = db.rawQuery(query, null);
return data;
}
public boolean updateData(String id,String name,String surname,int score) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1,id);
contentValues.put(COL_2,name);
contentValues.put(COL_3,score);
db.update(TABLE_NAME, contentValues, "ID = ?",new String[] { id });
return true;
}
public void updateName(String newName, int id, String oldName){
SQLiteDatabase db = this.getWritableDatabase();
String query = "UPDATE " + TABLE_NAME + " SET " + COL_2 +
" = '" + newName + "' WHERE " + COL_1 + " = '" + id + "'" +
" AND " + COL_2 + " = '" + oldName + "'";
Log.d(TAG, "updateName: query: " + query);
Log.d(TAG, "updateName: Setting name to " + newName);
db.execSQL(query);
}
public Integer deleteData(String id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "ID = ?",new String[] {id});
}
public void deleteName(int id, String name){
SQLiteDatabase db = this.getWritableDatabase();
String query = "DELETE FROM " + TABLE_NAME + " WHERE "
+ COL_1 + " = '" + id + "'" +
" AND " + COL_2 + " = '" + name + "'";
Log.d(TAG, "deleteName: query: " + query);
Log.d(TAG, "deleteName: Deleting " + name + " from database.");
db.execSQL(query);
}
public void updateScore(int newScore, int id, int oldScore){
SQLiteDatabase db = this.getWritableDatabase();
String query = "UPDATE " + TABLE_NAME + " SET " + COL_3 +
" = '" + newScore + "' WHERE " + COL_1 + " = '" + id + "'" +
" AND " + COL_3 + " = '" + oldScore + "'";
Log.d(TAG, "updateName: query: " + query);
Log.d(TAG, "updateName: Setting name to " + newScore);
db.execSQL(query);
}
public void clearData()
{
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME,null,null);
db.close();
}}
Thanks for the help!
Not sure but it seems that the problem is here:
while(data.moveToNext())
It could be that moveToNext() is triggered on the move to the next item after leaving the previous one in other words it will be triggered for the first time after leaving item #1 behind)
Try using indexed loop instead.i.e. for (int i=0; ....
In this code:
while(data.moveToNext())
{
itemID = data.getInt(0);
}
It will trigger the moveToNext() function and then do the while. So you could solve it using a do while instead
do{
itemID = data.getInt(0);
}while(data.moveToNext())
In my research of using Cursor your initial setup is correct
while(data.moveToNext())...
Cursor starts before the rows and the initial call moveToNext() moves it to the first row.
One glaring issue is that you are not closing the Cursor.
while(data.moveToNext())
{
listData.add(data.getString(1) +
" " + data.getInt(2)); //get value from database at column 1, then add it to array list
}
// Close the Cursor here and again after the second one you create
data.close();
The second thing I see being a potential issue is that you are not accessing the correct value in the onClick
// int i might not be 0 at some point
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
i--;// maybe try subtracting 1 from i. Alternative is to do that when i is being used
String nametest = "";
int u = 0;
// or subtract here
while(!adapterView.getItemAtPosition(i-1).toString().substring(u,u+1).equals(" "))
{
nametest = nametest + adapterView.getItemAtPosition(i-1).toString().substring(u, u+1);
u = u + 1;
}
I have my code to create SQLite database, the code create database but does not create any table. I went through some of the similar errors that others had before, I couldn't find any error. Could anyone help me.
Here is my code
public class DBHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "swahilComm.db";
public static final String COUNTRY_TABLE = "countries";
public static final String COUNTRY_ID = "id";
public static final String COUNTRY_NAME = "country";
public static final String PROVINCE_TABLE = "province";
public static final String PROVINCE_ID = "id";
public static final String PROVINCE_NAME = "province";
public static final String CREATE_TABLE_PROVINCE = "CREATE TABLE " + PROVINCE_TABLE + "("
+ PROVINCE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ PROVINCE_NAME + " TEXT );";
public static final String CREATE_COUNTRY_TABLE = "CREATE TABLE " + COUNTRY_TABLE + "("
+ COUNTRY_ID + " INTEGET PRIMARY KEY AUTOINCREMENT,"
+ COUNTRY_NAME + " TEXT );";
public DBHelper(Context context ) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.d("Database Operation", "Database Created...");
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_PROVINCE);
db.execSQL(CREATE_COUNTRY_TABLE);
Log.d("Database Operation", "Tables Created...");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed, all data will be gone
db.execSQL("DROP TABLE IF EXISTS " + PROVINCE_TABLE);
db.execSQL("DROP TABLE IF EXISTS " + COUNTRY_TABLE);
// Create tables again
onCreate(db);
}
//Delete all data in the table
public void DeleteCountry() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(COUNTRY_TABLE, null, null);
db.close(); // Closing database connection
}
//Delete all data in the Province table
public void DeleteProvice() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(PROVINCE_TABLE, null, null);
db.close(); // Closing database connection
}
//Insert country records
public int insertCountry(Country country) {
// TODO Auto-generated method stub
//Integer noProvince = getProvinceCount();
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COUNTRY_ID, country.getId());
values.put(COUNTRY_NAME, country.getCountry());
// Inserting Row
long country_Id = db.insert(COUNTRY_TABLE, null, values);
db.close(); // Closing database connection
return (int) country_Id;
}
//Insert province records
public int insertProvince(Province province) {
// TODO Auto-generated method stub
//Integer noProvince = getProvinceCount();
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(PROVINCE_ID, province.getId());
values.put(PROVINCE_NAME, province.getProvince());
// Inserting Row
long province_Id = db.insert(PROVINCE_NAME, null, values);
db.close(); // Closing database connection
return (int) province_Id;
}
//Retrieve all records and populate into List<Country>
//This method allow you to retrieve more fields/information into List.
public List<Country> getAllCountry() {
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT " +
COUNTRY_ID + "," +
COUNTRY_NAME +
" FROM " + COUNTRY_TABLE;
List<Country> countryList = new ArrayList<Country>() ;
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Country country = new Country();
country.setId(cursor.getString(cursor.getColumnIndex(COUNTRY_ID)));
country.setCountry(cursor.getString(cursor.getColumnIndex(COUNTRY_NAME)));
countryList.add(country);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return countryList;
}
//Retrieve all records and populate into List<Province>
//This method allow you to retrieve more fields/information into List.
public List<Province> getAll() {
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT " +
PROVINCE_ID + "," +
PROVINCE_NAME +
" FROM " + PROVINCE_TABLE;
List<Province> provinceList = new ArrayList<Province>() ;
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Province province = new Province();
province.setId(cursor.getString(cursor.getColumnIndex(PROVINCE_ID)));
province.setProvince(cursor.getString(cursor.getColumnIndex(PROVINCE_NAME)));
provinceList.add(province);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return provinceList;
}
//Retrieve all records and populate into List<String>
public List<String> getAllStringCountry() {
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT " +
COUNTRY_ID + "," +
COUNTRY_NAME +
" FROM " + COUNTRY_TABLE;
List<String> countryList = new ArrayList<String>() ;
Cursor cursor = db.rawQuery(selectQuery, null);
Integer i=0;
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
countryList.add(i,cursor.getString(cursor.getColumnIndex(COUNTRY_NAME)));
i+=1;
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return countryList;
}
//Retrieve all records and populate into List<String>
public List<String> getAll_Simple() {
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT " +
PROVINCE_ID + "," +
PROVINCE_NAME +
" FROM " + PROVINCE_TABLE;
List<String> provinceList = new ArrayList<String>() ;
Cursor cursor = db.rawQuery(selectQuery, null);
Integer i=0;
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
provinceList.add(i,cursor.getString(cursor.getColumnIndex(PROVINCE_NAME)));
i+=1;
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return provinceList;
}
}
This is the the Activity Class
public class Register extends AppCompatActivity {
DBHelper repo = new DBHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
countries = getResources().getStringArray(R.array.countries);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, countries);
autoCompleteTextView.setAdapter(adapter);
insertDummyData();
loadProvince_Simple();
}
// This class insert data
private void insertDummyData(){
repo.DeleteProvice();
int i = 1;
String[] provinces = {"Prince Edward Island", "Quebec", "Saskatchewan", "Yukon","Northwest Territories", "Ontario", "Nunavut", "Nova Scotia", "Alberta", "British Columbia", "Manitoba", "New Brunswick", "Newfoundland and Labrador"};
for(int j=0; j < provinces.length; j++) {
Province province = new Province();
province.setId(Integer.toString(i));
province.setProvince(provinces[j]);
repo.insertProvince(province);
i++;
}
}
//This is the arrayadapter binding method as you can see
private void loadProvince_Simple(){
ArrayAdapter<String> spinnerAdapter;
DBHelper db = new DBHelper(getApplicationContext());
List<String> provinces = db.getAll_Simple();
spinnerAdapter = new ArrayAdapter<String>(Register.this,
android.R.layout.simple_spinner_item, provinces);
prov_spinner.setAdapter(spinnerAdapter);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}
}
Read my comments below:
// TRY TO REMOVE THE SPACE BETWEEN "TEXT" TO THE "(" IN THE LAST LINE OF BOTH STRINGS
public static final String CREATE_TABLE_PROVINCE = "CREATE TABLE " + PROVINCE_TABLE + "("
+ PROVINCE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ PROVINCE_NAME + " TEXT );";
// YOU WROTE "INTEGET"
public static final String CREATE_COUNTRY_TABLE = "CREATE TABLE " + COUNTRY_TABLE + "("
+ COUNTRY_ID + " INTEGET PRIMARY KEY AUTOINCREMENT,"
+ COUNTRY_NAME + " TEXT );";
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.