I'm a beginner with android studio, so I'm stumbling my way through building my first app. I've come up with and error when attempting to save my data to a database. Whenever I try to save any digits, the app crashes.
Database Java file:
package com.miahollins.basketballfinal;
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;
/**
* Created by pumpkin on 6/17/16.
*/
public class DataHandler {
public static final String GAMES = "games_played";
public static final String GAMES2 = "games_started";
public static final String GAMES3 = "points";
public static final String TABLE_NAME = "statstable";
public static final String DATA_BASE_NAME = "mydatabase.sqlite";
public static final int DATABASE_VERSION = 2;
public static final String TABLE_CREATE = "create table statstable (games_played VARCHAR not null, games_started VARCHAR not null, points VARCHAR not null)";
DatabaseHelper dbhelper;
Context ctx;
SQLiteDatabase db;
public DataHandler(Context ctx){
this.ctx = ctx;
dbhelper = new DatabaseHelper(ctx);
}
private static class DatabaseHelper extends SQLiteOpenHelper{
public DatabaseHelper(Context ctx){
super(ctx, DATA_BASE_NAME,null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(TABLE_CREATE);
} catch(SQLException e){
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS statstable");
onCreate(db);
}
}
public DataHandler open(){
db = dbhelper.getWritableDatabase();
return this;
}
public void close(){
dbhelper.close();
}
public long insertData(String games_played, String games_started, String points){
ContentValues content = new ContentValues();
content.put(GAMES, games_played);
content.put(GAMES2, games_started);
content.put(GAMES3, points);
return db.insertOrThrow(TABLE_NAME, null, content);
}
public Cursor returnData(){
return db.query(TABLE_NAME, new String[]{GAMES, GAMES2, GAMES3},null, null, null, null, null);
}
}
In my logcat I get an error saying that columns cannot be found. Any help is appreciated!
Related
The onCreate void of my SQLiteOpenHelper is not called even when get a database with "database = helper.getWritableDatabase();". I read lots of posts on this page here but I didn't find any solution that worked for me.
SQLiteOpenHelper:
package eu.michael1011.currencies.sql;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class Helper extends SQLiteOpenHelper {
public static final String database_name = "currencies.db";
public static final String col1 = "id";
public static final String col2 = "value";
public Helper(Context context) {
super(context, database_name, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.d("database", "started");
db.execSQL("create table EUR ("+col1+" TEXT, "+col2+" TEXT)");
Log.d("database", "finished");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("drop table if exists EUR");
onCreate(db);
}
}
I call it in my main activity like this:
helper = new Helper(getBaseContext());
database = helper.getWritableDatabase();
SQLite database is not creating.
I have used a method getwritabledatabase(); in main class, but only the log appears "Constructor is called" and then the application is closed.
Here is my code
table extends SQLiteOpenHelper class
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;
import java.sql.SQLDataException;
import java.sql.SQLException;
public class Table extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "Hammas's Database";
private static final String TABLE_NAME = "Hammas's Table";
private static final int DATABASE_VERSION = 1;
private static final String ID = "_id";
private static final String COLNAME = "Names";
private static final String CREATE_TABLE = "CREATE TABLE "+TABLE_NAME+" ("+ID+" INTEGER PRIMARY KEY AUTOINCREMENT,"+COLNAME+" VARCHAR(255));";
private static final String DROP_TABLE = "DROP TABLE IF EXIST "+TABLE_NAME+"";
private static final String TAG = "Hammas";
private Context context;
public Table(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
Message.message(context,"Constructor is called");
Log.i(TAG,"CONSTRUCTOR IS CALLED");
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
Message.message(context, "onCreate is called");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DROP_TABLE);
onCreate(db);
Message.message(context,"onUpgrade is called");
}
}
Message class is just for toast.
Here is mainClass
enter code here
public class MainActivity extends ActionBarActivity {
Table table;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view);
table = new Table(this);
SQLiteDatabase sql= table.getReadableDatabase();
}
This string can't be processed as is
private static final String TABLE_NAME = "Hammas's Table";
It needs to be modified as
private static final String TABLE_NAME = "[Hammas''s Table]";
Because
The apostrophe is a string delimiter, so it has to be doubled.
The space would break the table name, so it needs to be enclosed in square brackets ([]).
This is also true for column names.
To insert apostrophes in string values, it has to be doubled, too.
Check the file system to ensure:
//data/data/<Your-Application-Package-Name>/databases/Hammas's Database.db
is created and located there. It won't create again if it already exists.
I have two files which both utilise a specific symbol class "Car". I have chosen this as a recurring pattern throughout the project.
My error:
DBhelper.java:
package com.example.brad.myapplication;
/**
* Created by Brad on 21/07/2014.
*/
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;
import android.graphics.Bitmap;
import android.view.View;
import android.view.TextureView;
public class DBhelper {
public static final String CAR_ID = "id";
public static final String CAR_PHOTO = "photo";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_NAME = "CarDB.db";
private static final int DATABASE_VERSION = 1;
private static final String CARS_TABLE = "Cars";
private static final String CREATE_CARS_TABLE = "create table "
+ CARS_TABLE + " (" + CAR_ID
+ " integer primary key autoincrement, " + CAR_PHOTO
+ " blob not null);";
private final Context mCtx;
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_CARS_TABLE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + CARS_TABLE);
onCreate(db);
}
}
public void Reset() {
mDbHelper.onUpgrade(this.mDb, 1, 1);
}
public DBhelper(Context ctx) {
mCtx = ctx;
mDbHelper = new DatabaseHelper(mCtx);
}
public DBhelper open() throws SQLException {
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public void insertCarDetails(**Car** car) {
ContentValues cv = new ContentValues();
cv.put(CAR_PHOTO, Utility.getBytes(car.getBitmap()));
mDb.insert(CARS_TABLE, null, cv);
}
public **Car** retriveCarDetails() throws SQLException {
Cursor cur = mDb.query(true, CARS_TABLE, new String[] { CAR_PHOTO}, null, null, null, null, null, null);
if (cur.moveToFirst()) {
byte[] blob = cur.getBlob(cur.getColumnIndex(CAR_PHOTO));
cur.close();
return new Car(Utility.getPhoto(blob));
}
cur.close();
return null;
}
}
InsertandRetriveBlobData:
package com.example.brad.myapplication;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
/**
* Created by Brad on 20/07/2014.
*/
public class InsertandRetriveBlobData extends MyActivity {
private DBhelper DbHelper;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
DbHelper = new DBhelper(this);
**Car** car_One = new Car(BitmapFactory.decodeResource(
getResources(), R.drawable.photo), 1);
DbHelper.open();
DbHelper.insertCarDetails(car_One);
DbHelper.close();
car_One = null;
DbHelper.open();
car_One = DbHelper.retriveCarDetails();
DbHelper.close();
ImageView carphoto = (ImageView) findViewById(R.id.photo);
carphoto.setImageBitmap(car_One.getBitmap());
}
}
I have a feeling it is a slight bug as I am also having errors with any use of getBitmap() "Cannot resolve method getBitmap()" despite importing it's library.
Check whether your Car class is in myapplication directory along with the other two classes you mentioned here.
And then compile from myapplication directory.
I have some troubles with my Database activity.
I have my database (Voedsel.rar), in assets-databases-Voedsel.rar.
I also have one SQLView activity, which should be able to view the database. Also, I have the SQLite activity (for writing new products to it.), and my regular Database activty. I want to write to the database, and to view the database.
There are 3 columns, Product, Eenheid (translated it means 'unit'), and Kcal (the amount of kilocalories in that specific units of that specific food-product.). Hopefully you all understand me. :)
I'll add my activities. If there is need of the layout files, don't hesitate to ask.
So, the first question is:
How can I fix my error in line 46, (see comment!)...?
Is there someting wrong with the Context?
my Database activity:
package com.jacob.eindproject;
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;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import java.sql.*;
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;
public class Database extends SQLiteAssetHelper {
public static final String KEY_PRODUCT = "Product";
public static final String KEY_EENHEID = "Eenheid";
public static final String KEY_KCAL = "Kcal";
private static final String DATABASE_NAME = "Voedsel";
private static final String DATABASE_TABLE = "Voeding";
private static final int DATABASE_VERSION = 1;
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteAssetHelper{
public DbHelper(Context context) {
super(context, DATABASE_NAME, context.getExternalFilesDir(null).getAbsolutePath(), null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
}
#Override
public void onUpgrade(SQLiteDatabase Voedsel, int oldVersion, int newVersion) {
Voedsel.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(Voedsel);
}
public Database(Context ourContext){
//Here is my error. It says:
//Implicit super constructor
//SQLiteAssetHelper() is undefined. Must explicitly invoke another constructor
Context = ourContext;
}
public Database open() throws SQLException{
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
public long createEntry(String product, String kcal, String eenheid) {
ContentValues cv = new ContentValues();
cv.put(KEY_PRODUCT, product);
cv.put(KEY_EENHEID, eenheid);
cv.put(KEY_KCAL, kcal);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData() {
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_PRODUCT, KEY_EENHEID, KEY_KCAL};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iProduct = c.getColumnIndex(KEY_PRODUCT);
int iEenheid = c.getColumnIndex(KEY_EENHEID);
int iKcal = c.getColumnIndex(KEY_KCAL);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iProduct) + " " + c.getString(iEenheid) + " " + c.getString(iKcal) + "\n";
}
return result;
}
public void close(Database database) {
// TODO Auto-generated method stub
}
}
You need to call the super constructor. An example from this site is the following:
super(context, DATABASE_NAME, null, DATABASE_VERSION);
It looks like the addition of this line as the first line in your constructor should remove the error.
public Database(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
Secondly, you seem to have an inner SQLiteHelp. I can't imagine why that's needed, so I would just remove it.
private static class DbHelper extends SQLiteAssetHelper{
public DbHelper(Context context) {
super(context, DATABASE_NAME, context.getExternalFilesDir(null).getAbsolutePath(), null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
}
Lastly, I would call your class something different than Database. I think you might be confusing classes somewhere, which could be responsible for your issue.
I have Created a database in Sqllite Android Application and I tried to add two tables in my Database, but I have problem to create that Database. First Table only Created. Can anyBody help me?
package com.android.cdtech;
import java.sql.SQLException;
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 saveData {
public static final String KEY_ROWID = "rowid"; public static final String KEY_DATE = "Date";public static final String KEY_NAME = "CustomerName";public static final String KEY_AMOUNT = "Amount";public static final String KEY_BANK = "Banks";
private static final String TAG = "DBAdapter";
public static final String KEY_BUSNAME="BusinessName";public static final String KEY_ADD="Address";public static final String KEY_CPERSON="ContactPerson";;
private static final String DATABASE_NAME = "EXPORTDETAILS";
private static final String DATABASE_TABLE = "Payment";
private static final String DATABASE_TABLE2 = "Customer";
private static final int DATABASE_VERSION = 1;
private static String DATABASE_CREATE =
"create table Payment (_id integer primary key autoincrement, "
+ "Date text not null,"+"CustomerName text not null,"+"Amount text not null,"+"Banks text not null);";
private static final String DATABASE_CREATECUS =
"create table Customer (_id integer primary key autoincrement, "
+ "BusinessName text not null,"+"Address text not null,"+"ContactPerson text not null,"+"PhoneNumber text not null,);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public saveData(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
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);
db.execSQL(DATABASE_CREATECUS);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion
+ " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS titles");
onCreate(db);
}
}
public saveData open()throws SQLException
{
db=DBHelper.getWritableDatabase();
return this;
}
public void close()
{
DBHelper.close();
}
public long insert(String Date,String CustomerName,String Amount,String Banks) {
// TODO Auto-generated method stub
ContentValues cv=new ContentValues();
cv.put(KEY_DATE,Date);
cv.put(KEY_NAME,CustomerName);
cv.put(KEY_AMOUNT,Amount);
cv.put(KEY_BANK,Banks);
return db.insert(DATABASE_TABLE, null,cv);
}
public long insertForm(String BusinessName ,String Address ,String ContactPerson) {
// TODO Auto-generated method stub
ContentValues cv=new ContentValues();
cv.put(KEY_BUSNAME,BusinessName);
cv.put(KEY_ADD,Address);
cv.put(KEY_CPERSON,ContactPerson);
}
public Cursor getlatlng()
{
Cursor latlngCursor = db.rawQuery("select * from " + DATABASE_TABLE,null);
if (latlngCursor != null)
{
latlngCursor.moveToFirst();
}
db.close();
return latlngCursor;
}
public Cursor order()
{
Cursor latlngCursor = db.rawQuery("select * from " + DATABASE_TABLE2,null);
if (latlngCursor != null)
{
latlngCursor.moveToFirst();
}
db.close();
return latlngCursor;
}
}
Error Code =1 No Such table for Customer
use below two class
package Your 'packagename';
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "BistroDB";
private static final int DATABASE_VERSION =1;
// Database creation sql statement
public static final String Table1= "create table table1name ("Your cloumns");";
public static final String Table2 = "create table table2name ("Your cloumns");";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Method is called during creation of the database
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(table1);
database.execSQL(table2);
}
// Method is called during an upgrade of the database, e.g. if you increase
// the database version
#Override
public void onUpgrade(SQLiteDatabase database, int oldVersion,
int newVersion) {
Log.w(DBHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
database.execSQL("DROP TABLE IF EXISTS table1");
database.execSQL("DROP TABLE IF EXISTS table2");
onCreate(database);
}
public boolean deleteDatabase(Context context) {
return context.deleteDatabase(DATABASE_NAME);
}
}
Use below class to insert values into table
package 'Your package name';
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class DataBaseAdapter {
// Database fields
private Context context;
private SQLiteDatabase database;
private DBHelper dbHelper;
public DataBaseAdapter(Context context) {
this.context = context;
}
public DataBaseAdapter open() throws SQLException {
dbHelper = new DBHelper(context);
database = dbHelper.getWritableDatabase();
return this;
}
public void close() {
dbHelper.close();
}
public Cursor fetchAllTAble1data() {
return database.query("MenuData", new String[] { "id", "Title",
"Image", "Description" }, null, null, null, null, null);
}
public Cursor fetchAllTable2data() {
return database.query("RestaurantsData", new String[] {
"restaurant_id", "name", "phone", "email", "open_days",
"timing", "website", "loc_name", "street", "city", "longitude",
"latitude", "zip" }, null, null, null, null, null);
}
public void deleteTable(String tablename){
database.execSQL("drop table if exists "+tablename+';');
}
public void createIndividualTable(String query){
database.execSQL(query);
}
public void InsertTable1Data(TAble1 review) {
ContentValues values = new ContentValues();
values.put("Name", review.Name);
values.put("Email", review.Email);
values.put("Comment", review.Comment);
values.put("Rating", review.Rating);
database.insert("ReviewsData", null, values);
}
public void InsertTable2Data(TAble2 photos) {
ContentValues values = new ContentValues();
values.put("photo", photos.Photos);
database.insert("PhotosData", null, values);
}
public ContentValues createContentValues(String category, String summary,
String description) {
ContentValues values = new ContentValues();
return values;
}
}
Try removing the "," at the end of DATABASE_CREATECUS