android SQLite database.. no such table: [duplicate] - java

This question already has answers here:
When does SQLiteOpenHelper onCreate() / onUpgrade() run?
(15 answers)
Closed 9 years ago.
I have another problem again :(
The error I encountered with this one is that it does not create a table named contacts but I have the code to create database and yet it does not create it.How to solve this? Thank you again for answering.
package com.mobilebasedsignlanguage;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
public class alphaconv extends Activity {
ArrayList<Contact> imageArry = new ArrayList<Contact>();
ContactImageAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.alphabetview);
DataBaseHandler db = new DataBaseHandler(this);
//get image from drawable..
Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.a);
//convert bitmap to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte imageInByte[] = stream.toByteArray();
//Inserting Contacts
Log.d("Insert: ", "Inserting ..");
db.addContact(new Contact("A", imageInByte));
//Read all contacts from db
List<Contact> contacts = db.getAllContacts();
for(Contact cn: contacts) {
String log = "ID: " + cn.getID() + "Name: " + cn.getName() + ", Image: " + cn.getImage();
Log.d("Result: ", log);
imageArry.add(cn);
}
adapter = new ContactImageAdapter(this, R.layout.screen_list, imageArry);
ListView dataList = (ListView)findViewById(R.id.list);
dataList.setAdapter(adapter);
}
}
here is the other java classes:
Contact.java
package com.mobilebasedsignlanguage;
public class Contact {
int _id;
String _name;
byte[] _image;
public Contact() {
}
public Contact(int keyId, String name, byte[] image) {
this._id = keyId;
this._name = name;
this._image = image;
}
public Contact(String contactID, String name, byte[] image) {
this._name = name;
this._image = image;
}
public Contact(String name, byte[] image) {
this._name = name;
this._image = image;
}
public int getID() {
return this._id;
}
public void setID(int keyId ) {
this._id = keyId;
}
public String getName() {
return this._name;
}
public void setName(String name) {
this._name = name;
}
public byte[] getImage() {
return this._image;
}
public void setImage(byte[] image) {
this._image = image;
}
}
ContactImageAdapter.java
package com.mobilebasedsignlanguage;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class ContactImageAdapter extends ArrayAdapter<Contact>{
Context context;
int layoutResourceId;
ArrayList<Contact> data=new ArrayList<Contact>();
public ContactImageAdapter(Context context, int layoutResourceId, ArrayList<Contact> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ImageHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ImageHolder();
holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
row.setTag(holder);
}
else
{
holder = (ImageHolder)row.getTag();
}
Contact picture = data.get(position);
holder.txtTitle.setText(picture._name);
byte[] outImage = picture._image;
ByteArrayInputStream imageStream = new ByteArrayInputStream(outImage);
Bitmap theImage = BitmapFactory.decodeStream(imageStream);
holder.imgIcon.setImageBitmap(theImage);
return row;
}
static class ImageHolder
{
ImageView imgIcon;
TextView txtTitle;
}
}
DbHandler.java
package com.mobilebasedsignlanguage;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DataBaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "SLdb";
private static final String TABLE_CONTACTS = "contacts";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_IMAGE = "image";
public DataBaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_IMAGE + " BLOB" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
onCreate(db);
}
public void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact._name);
values.put(KEY_IMAGE, contact._image);
db.insert(TABLE_CONTACTS, null, values);
db.close();
}
Contact getContact(int id) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_IMAGE }, 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.getBlob(1));
return contact;
}
public List<Contact> getAllContacts() {
List<Contact> contactlist = new ArrayList<Contact>();
String selectQuery = "SELECT * FROM contacts ORDER BY name";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if(cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setImage(cursor.getBlob(2));
contactlist.add(contact);
}while (cursor.moveToNext());
}
db.close();
return contactlist;
}
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_IMAGE, contact.getImage());
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] {String.valueOf(contact.getID()) });
db.close();
}
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
return cursor.getCount();
}
}
the error at the log cat is this:
02-18 11:49:25.938: E/SQLiteLog(6044): (1) no such table: contacts
02-18 11:49:26.078: E/SQLiteDatabase(6044): Error inserting image=[B#40e29b40 name=A
02-18 11:49:26.078: E/SQLiteDatabase(6044): android.database.sqlite.SQLiteException: no such table: contacts (code 1): , while compiling: INSERT INTO contacts(image,name) VALUES (?,?)

Do a log or toast in the onCreate method to see if it's called and if yes then delete your old table as this is called only once and if the table already exists it will not be executed again.
Also, please try using the below query, sometimes spaces in the create statement cause the issue.
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + " ("
+ KEY_ID + " INTEGER PRIMARY KEY, " + KEY_NAME + " TEXT, "
+ KEY_IMAGE + " BLOB" + ");";

The problem is that you are not overriding the SQLiteOpenHelper onCreate method, so it is not being called.
Try to put override annotation on the onCreate and onUpgrade methods:
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_IMAGE + " BLOB" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
onCreate(db);
}

Related

Data doesn't get saved in database, which it did before, but after I updated the database version it doesn't

Thanks for helping me fix my problem!
Issue
The issue is that the data never gets saved into the database, which it did before, but then i updated the database version and now it does not.
Is there an error thrown? Yes there is and its right down below.
E/SQLiteLog: (1) near "0": syntax error
E/SQLiteDatabase: Error inserting 0=20 id=csdfergeg userid=csdfergeg email=erregegergr
android.database.sqlite.SQLiteException: near "0": syntax error (code 1): , while compiling: INSERT INTO Info(0,id,userid,email) VALUES (?,?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:890)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:501)
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:1546)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1417)
at com.vikkivuk.mxelevator.Database.addUserInfo(Database.java:50)
at com.vikkivuk.mxelevator.finishScene$1.onClick(finishScene.java:61)
at android.view.View.performClick(View.java:6294)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
My code:
Database Class:
package com.vikkivuk.mxelevator;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
public class Database extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 5;
private static final String DATABASE_NAME = "UserInfo";
private static final String TABLE_NAME = "Info";
private static final String KEY_ID = "id";
private static final String KEY_USERID = "userid";
private static final String KEY_EMAIL = "email";
private static final String KEY_CODE = "code";
public Database(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_USERID + " TEXT," + KEY_EMAIL + " TEXT," + Integer.parseInt(KEY_CODE) + " TEXT" + ")";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public void addUserInfo(UserInfo info){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_ID, info.UserId);
contentValues.put(KEY_EMAIL, info.Email);
contentValues.put(KEY_USERID, info.UserId);
contentValues.put(KEY_CODE, info.CODE);
db.insert(TABLE_NAME, null, contentValues);
db.close();
}
public List<UserInfo> getUserInfo(){
List<UserInfo> results = new ArrayList<UserInfo>();
String GET_ALL = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(GET_ALL, null);
if (cursor.moveToFirst()) {
do {
UserInfo userInfo = new UserInfo(cursor.getString(0), cursor.getString(1), cursor.getString(2), cursor.getString(3));
results.add(userInfo);
} while (cursor.moveToNext());
}
db.close();
return results;
}
public void deleteUserInfo(UserInfo info){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, KEY_ID + " = ? ", new String[] {String.valueOf(info.ID)});
db.close();
}
}
UserInfo:
package com.vikkivuk.mxelevator;
public class UserInfo {
public String ID;
public String UserId;
public String Email;
public String CODE;
public UserInfo(String uid, String mail, String el_code){
UserId = uid;
Email = mail;
CODE = el_code;
}
public UserInfo(String userId, String uid, String mail, String el_code){
UserId = uid;
Email = mail;
ID = userId;
CODE = el_code;
}
}
UserInfoAdapter:
package com.vikkivuk.mxelevator;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.List;
public class UserInfoAdapter extends ArrayAdapter<UserInfo> {
public UserInfoAdapter(Context context, List<UserInfo> info) {
super(context, 0, info);
}
public View getView(int position, View convertView, ViewGroup parent){
UserInfo info = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.user_info_item_row, parent, false);
}
TextView uid = convertView.findViewById(R.id.textview_userid);
TextView email = convertView.findViewById(R.id.textview_email);
TextView textcode = convertView.findViewById(R.id.codetext);
uid.setText(info.UserId);
email.setText(info.Email);
textcode.setText(info.CODE);
return convertView;
}
}
Finish scene:
package com.vikkivuk.mxelevator;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.material.snackbar.BaseTransientBottomBar;
import com.google.android.material.snackbar.Snackbar;
import java.util.Random;
public class finishScene extends AppCompatActivity {
EditText userId, email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_finish_scene);
userId = findViewById(R.id.userid);
email = findViewById(R.id.email);
CheckBox agreeCheck = findViewById(R.id.agreeCheck1);
Boolean checked = agreeCheck.isChecked();
Button submit = findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (userId.length() < 5) {
Toast.makeText(getApplicationContext(), "Your UID is too short!", Toast.LENGTH_SHORT).show();
return;
} else if (email.length() < 6) {
Toast.makeText(getApplicationContext(), "Your EMAIL is too short!", Toast.LENGTH_SHORT).show();
return;
} else if (!agreeCheck.isChecked()) {
Toast.makeText(getApplicationContext(), "Please check the agree box!", Toast.LENGTH_SHORT).show();
return;
} else {
Random rand = new Random();
int int_random1 = rand.nextInt(10000);
int int_random2 = rand.nextInt(10);
int int_random3 = rand.nextInt(10);
int int_random4 = rand.nextInt(15);
int int_random5 = rand.nextInt(25);
int random_code = int_random1 + int_random2 + int_random3 + int_random4 + int_random5;
Database db = new Database(finishScene.this);
UserInfo info = new UserInfo(userId.getText().toString(), email.getText().toString(), String.valueOf(random_code));
db.addUserInfo(info);
db.close();
userId.setText("");
email.setText("");
Toast.makeText(getApplicationContext(), "Data saved! Pending approval...", Toast.LENGTH_LONG).show();
Intent intent = new Intent(userId.getContext(), Success.class);
startActivity(intent);
}
}
});
}
}
ShowData:
package com.vikkivuk.mxelevator;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import java.util.List;
public class ShowData extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_data);
List<UserInfo> info = new Database(this).getUserInfo();
UserInfoAdapter adapter = new UserInfoAdapter(this, info);
ListView listView = findViewById(R.id.userInfoList);
listView.setAdapter(adapter);
Button goback = findViewById(R.id.goback1);
goback.setOnClickListener(v -> {
Intent intent = new Intent(goback.getContext(), MainActivity.class);
startActivity(intent);
});
}
}
That's all of my classes. Also, I would like to specify that I don't actually know what database versions are since I started with the android studio 3 days ago.
please try this I implemented some change on the UserInfo class
the Id must be an integer and you add a String
database.java
public class MyBase extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 5;
private static final String DATABASE_NAME = "UserInfo";
private static final String TABLE_NAME = "Info";
private static final String KEY_ID = "id";
private static final String KEY_USERID = "userid";
private static final String KEY_EMAIL = "email";
private static final String KEY_CODE = "code";
public MyBase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_USERID + " INTEGER," + KEY_EMAIL + " TEXT," + KEY_CODE + " TEXT" + ")";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public void addUserInfo(UserInfo info) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
// contentValues.put(KEY_ID, info.UserId); i removed this
contentValues.put(KEY_EMAIL, info.Email);
contentValues.put(KEY_USERID, info.UserId);
contentValues.put(KEY_CODE, info.CODE);
db.insert(TABLE_NAME, null, contentValues);
db.close();
}
public List<UserInfo> getUserInfo() {
List<UserInfo> results = new ArrayList<>();
String GET_ALL = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(GET_ALL, null);
if (cursor.moveToFirst()) {
do {
UserInfo userInfo = new UserInfo(cursor.getInt(0), cursor.getInt(1), cursor.getString(2), cursor.getInt(3));
results.add(userInfo);
} while (cursor.moveToNext());
}
db.close();
return results;
}
public void deleteUserInfo(UserInfo info) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, KEY_ID + " = ? ", new String[]{String.valueOf(info.ID)});
db.close();
}
}
and UserInfo :
public class UserInfo {
public int ID;
public int UserId;
public String Email;
public int CODE;
public UserInfo(int uid, String mail, int el_code) {
UserId = uid;
Email = mail;
CODE = el_code;
}
public UserInfo(int userId, int uid, String mail, int el_code) {
UserId = uid;
Email = mail;
ID = userId;
CODE = el_code;
}
}
i hope that's help you

Android app stalls when implementing SQLite database

At first the app would just crash when I started it with an emulator, Not sure what I changed to get it to run but now it will run the onCreate method however, when I implement the addButtonClicked method the app just stalls and the Android Monitor displays "Suspending all threads" every few seconds and I'm not sure where to even begin debugging. Any pointers in the right direction would be greatly appreciated as I'm fairly new to Android development.
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText testInput;
TextView testText;
MyDBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
testInput = (EditText) findViewById(R.id.testInput);
testText = (TextView) findViewById(R.id.testText);
dbHandler = new MyDBHandler(this, null, null, 1);
printDatabase();
}
//Add product to database
public void addButtonClicked(View view){
Products product = new Products((testInput.getText().toString()));
dbHandler.addProduct(product);
printDatabase();
}
// Delete Items
public void deleteButtonClicked(View view){
String inputText = testText.getText().toString();
dbHandler.deleteProduct(inputText);
printDatabase();
}
public void printDatabase(){
String dbString = dbHandler.databaseToString();
testText.setText(dbString);
testInput.setText("");
}
}
Products.java
public class Products {
private int _id;
private String _productname;
public Products(){
}
public Products(String productname) {
this._productname = productname;
}
public void set_id(int _id) {
this._id = _id;
}
public void set_productname(String _productname) {
this._productname = _productname;
}
public int get_id() {
return _id;
}
public String get_productname() {
return _productname;
}
}
MyDBHandler.java
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.Cursor;
import android.content.Context;
import android.content.ContentValues;
public class MyDBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 15;
private static final String DATABASE_NAME = "products.db";
public static final String TABLE_PRODUCTS = "products";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_PRODUCTNAME = "productname";
public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_PRODUCTS +"(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT ," +
COLUMN_PRODUCTNAME +" TEXT " +
");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUCTS);
onCreate(db);
}
//Add new row to the database
public void addProduct(Products product){
ContentValues values = new ContentValues();
values.put(COLUMN_PRODUCTNAME, product.get_productname());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_PRODUCTS, null, values);
db.close();
}
//Delete product from database
public void deleteProduct(String productName){
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_PRODUCTS + " WHERE " + COLUMN_PRODUCTNAME + "=\"" + productName + "\";" );
}
//Print of DB as sting
public String databaseToString(){
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";
//Cursor point to a location in your results
Cursor c = db.rawQuery(query, null);
//Move to the first row in your results
c.moveToFirst();
while (!c.isAfterLast()){
if(c.getString(c.getColumnIndex("productname"))!= null){
dbString += c.getString(c.getColumnIndex("productname"));
dbString += "\n";
}
}
db.close();
return dbString;
}
}
for your databaseToString method you are performing a retrieve operation. You should be doing a read operation in a thread other than UI thread. Try fetching in AsyncTask. It should work. Implementation for your databaseToString should be handled by AsyncTask.
Happy Coding..

add more fields to DBAdapter class

i try to save current date values when button get clicked....i use DBAdapter for save parameters to sqlite and it was fine when used for 2 fields like example of DBAdapter but when i edited DBAdapter for 6 fields this doesnt work.where is my problem?
DBAdapter.java
import java.io.StringReader;
import java.util.ArrayList;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter {
private static final String TAG = "DBAdapter"; //used for logging database version changes
// Field Names:
public static final String KEY_ROWID = "_id";
public static final String KEY_YEAR = "year";
public static final String KEY_MONTH = "month";
public static final String KEY_DAY = "day";
public static final String KEY_HOUR = "hour";
public static final String KEY_MINUTE = "minute";
public static final String KEY_SECOND = "second";
public static final String[] ALL_KEYS = new String[] { KEY_ROWID, KEY_YEAR, KEY_MONTH, KEY_DAY, KEY_HOUR, KEY_MINUTE, KEY_SECOND};
// Column Numbers for each Field Name:
public static final int COL_ROWID = 0;
public static final int COL_TASK = 1;
public static final int COL_DATE = 2;
// DataBase info:
public static final String DATABASE_NAME = "dbToDo12";
public static final String DATABASE_TABLE = "mainToDo12";
public static final int DATABASE_VERSION = 2; // The version number must be incremented each time a change to DB structure occurs.
//SQL statement to create database
private static final String DATABASE_CREATE_SQL =
"CREATE TABLE " + DATABASE_TABLE
+ " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_YEAR + " TEXT NOT NULL, "
+ KEY_MONTH + " TEXT"
+ KEY_DAY + " TEXT"
+ KEY_HOUR + " TEXT"
+ KEY_MINUTE + " TEXT"
+ KEY_SECOND + " TEXT"
+ ");";
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to be inserted into the database.
public long insertRow(String year, String month,String day, String hour,String minute,String second) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_YEAR, year);
initialValues.put(KEY_MONTH, month);
initialValues.put(KEY_DAY, day);
initialValues.put(KEY_HOUR, hour);
initialValues.put(KEY_MINUTE, minute);
initialValues.put(KEY_SECOND, second);
// Insert the data into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String year, String month,long day, String hour, String minute,long second) {
String where = KEY_ROWID + "=" + rowId;
ContentValues newValues = new ContentValues();
newValues.put(KEY_YEAR, year);
newValues.put(KEY_MONTH, month);
newValues.put(KEY_DAY, day);
newValues.put(KEY_HOUR, hour);
newValues.put(KEY_YEAR, year);
newValues.put(KEY_MINUTE, minute);
newValues.put(KEY_SECOND, second);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading application's database from version " + oldVersion
+ " to " + newVersion + ", which will destroy all old data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
}
MainActivity.java
import android.content.Context;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.view.View;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
Button plus;
int second,minute,houre,day,mounth,year;
DBAdapter mDb = new DBAdapter(this);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
ViewGroup.LayoutParams superparams =
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.MATCH_PARENT);
LinearLayout table = new LinearLayout(this);
plus = new Button(this);
plus.setText("+");
table.addView(plus);
setContentView(table);
plus.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Calendar c = Calendar.getInstance();
second = c.get(Calendar.SECOND);
minute = c.get(Calendar.MINUTE);
houre = c.get(Calendar.HOUR);
day = c.get(Calendar.DAY_OF_MONTH);
mounth = c.get(Calendar.MONTH);
year = c.get(Calendar.YEAR);
mDb.open();
mDb.insertRow(Integer.toString(year), Integer.toString (mounth),Integer.toString(day), Integer.toString(houre),Integer.toString(minute), Integer.toString(second));
mDb.close();
mDb.open();
Cursor g=mDb.getRow(2);
DisplayContact(g);
mDb.close();
}
});
}
public void DisplayContact(Cursor c)
{
Toast.makeText(this,"id: "+c.getString(0)+"\n"+
"year: "+c.getString(1)+"\n"+
"month: "+c.getString(2),
Toast.LENGTH_LONG).show();
}
}
You're missing commas , between your column specifications here:
+ KEY_MONTH + " TEXT"
+ KEY_DAY + " TEXT"
+ KEY_HOUR + " TEXT"
+ KEY_MINUTE + " TEXT"
After adding the missing commas, either uninstall your app or increment the schema version to get the table recreated.

android getWritableDatabase

package ru.phonebook;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.SyncStateContract;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
// Класс для работы БД
public class DatabaseHandler extends SQLiteOpenHelper
{
// Версия базы данных
private static final int _DatabaseVersion = 3;
// Название базы
private static final String _DatabaseName = "ContaсtDatabase";
// Таблица
private static final String _TableName = "subscribers";
// Поля в таблице
private static final String _Field_ID = "id_subscribers";
private static final String _Field_Name = "name_subscribers";
private static final String _Field_Phone = "phone_subscribers";
// Запрос создания таблицы
private static final String _Query_CreateTable = "CREATE TABLE " + _TableName + "("
+ _Field_ID + " INTEGER PRIMARY KEY,"
+ _Field_Name + " TEXT,"
+ _Field_Phone + " TEXT);";
// Запрос вывода всех контактов
private static final String _Query_SelectTable = "SELECT * FROM " + _TableName;
// Запрос на вывода количества контактов
private static final String _Query_CountRows_Table = "SELECT COUNT(*) FROM " + _TableName;
// Конструктор
public DatabaseHandler(Context context)
{
super(context, _DatabaseName, null, _DatabaseVersion);
Log.e("n", "Call constructor");
}
// Добавление абонента в базу данных
public void AddSubcriber(Subscriber contact)
{
SQLiteDatabase db = this.getWritableDatabase();
/*ContentValues values = new ContentValues();
values.put(_Field_Name, contact.getName());
values.put(_Field_Phone, contact.getPhone());
db.insert(_TableName, null, values);
db.close();
*/
Log.d("n", "Insert rows: " + contact.getName());
}
// Вывод всех абонентов
public List<Subscriber> getAllSubscriber()
{
List<Subscriber> allSubscriber = new ArrayList<Subscriber>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(_Query_SelectTable, null);
if(cursor.getCount() != 0)
{
do
{
Subscriber tmpSub = new Subscriber(cursor.getInt(0), cursor.getString(1), cursor.getString(2));
allSubscriber.add(tmpSub);
} while(cursor.moveToNext());
}
cursor.close();
db.close();
return allSubscriber;
}
// Вывод количества абонентов
public int getSubscriberCount()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(_Query_CountRows_Table, null);
db.close();
cursor.close();
return cursor.getCount();
}
// Удаление всех контактов
public void deleteAllSubscriber()
{
SQLiteDatabase db = this.getWritableDatabase();
db.delete(_TableName, null, null);
db.close();
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(_Query_CreateTable);
Log.e("n", "Database create");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE IF EXISTS " + _TableName);
onCreate(db);
Log.e("n", "Database onUpgrade");
}
}
This is my class for communicate with database, and after in main programm i add new rows:
DatabaseHandler dbConnect = new DatabaseHandler(this);
dbConnect.AddSubcriber(new Subscriber("Petr Umine", "19234234432"));
In my logCat i view error:
"02-24 19:12:41.440 17415-17415/ru.phonebook W/System.err﹕ Invalid int: "" "
i am debuging method "AddSubcriber", and this error crush after this line SQLiteDatabase db = this.getWritableDatabase();
what is it?

How I can start my Android SQLite Application without a Error

I want built a Android Application with a SQLite Database. I have two Java Classes. The First is the Contact Class ans the second the DatabaseHandle class for the operations how add, update etc...
I don't get a error but if I start my Application I become this message ...
Here is my Contact Class
package de.linde.sqlite;
public class Contact {
int _id;
String _name;
String _phone_number;
public Contact(){}
public Contact(int id,String name,String _phone_number){
this._id = id;
this._name = name;
this._phone_number = _phone_number;
}
public Contact(String name,String _phone_number){
this._name = name;
this._phone_number = _phone_number;
}
public int getID(){
return this._id;
}
public void setID(int id){
this._id = id;
}
public String getName(){
return this._name;
}
public void setName(String name){
this._name = name;
}
public String getPhoneNumber(){
return this._phone_number;
}
public void setPhoneNumber(String phone_number){
this._phone_number = phone_number;
}
}
Here is my DatabaseHandler Class
package de.linde.sqlite;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHandler extends SQLiteOpenHelper {
//Datenbank version
private static final int DATABASE_VERSION = 1;
//Datenbankname
private static final String DATABASE_NAME = "contactsManager";
//Tabellenname
private static final String TABLE_CONTACTS = "contacts";
//Tabellenspalten
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";
public DatabaseHandler(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
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" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
db.execSQL("DROP TABLE IF EXISTS" + TABLE_CONTACTS);
onCreate(db);
}
public void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone Number
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
public Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, 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));
// return contact
return contact;
}
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.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
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();
}
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
}
}
Here is my MainActivity
package de.linde.sqlite;
import java.util.List;
import android.os.Bundle;
import android.util.Log;
import android.app.Activity;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DatabaseHandler db = new DatabaseHandler(this);
Log.d("Insert: ", "Inserting ..");
db.addContact(new Contact("Wladimir","024324324"));
db.addContact(new Contact("Max","0324324324"));
db.addContact(new Contact("Benny","0324324"));
db.addContact(new Contact("derSchwarze","051324324"));
Log.d("Reading: ","Reading all Contacts..");
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
String log = "Id: " + cn.getID() + " ,Name: " + cn.getName() + " ,Phone: " + cn.getPhoneNumber();
Log.d("Name: ", log);
}
}
}
My activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</RelativeLayout>
What I make wrong :(
Add spaces between the values that you add to CREATE_CONTACTS_TABLE and the concatenated string, so you build a valid table creation string:
"CREATE TABLE " + TABLE_CONTACTS + " (" + KEY_ID + " INTEGER PRIMARY KEY, " + KEY_NAME + " TEXT, " + KEY_PH_NO + " TEXT)";
You'll need to uninstall the app from the phone/emulator and then run it again to make the database to be recreated again.
The same thing is valid for the String in the onUpgrade method:
"DROP TABLE IF EXISTS " + TABLE_CONTACTS

Categories