Hello as the title says I cannot get the app to construct a small local sqlite database. I would appreciate some help as I m an amateur. Thanks in advance.
Below there are some pictures of my source code.
I tested this code on level 24 API device, but the database does not appear in the data/data/the_package/databases/ folder
Edited to include code
MainActivity.java
public class MainActivity extends AppCompatActivity {
private CrdDBHelper mydb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mydb = new CrdDBHelper(this);
boolean p1 = true;
int p11sc = 0;
int p12sc = 0;
Button btnMenu = (Button) findViewById(R.id.btnMenu);
Button btntrue = (Button) findViewById(R.id.btnTrue);
Button btnFalse = (Button) findViewById(R.id.btnFalse);
// All other available code commented out
}
#Override
protected void onDestroy() {
mydb.close();
super.onDestroy();
}
}
CrdDBContract.java
public final class CrdDBContract {
private CrdDBContract(){}
public static final class GameEntry implements BaseColumns {
public static final String TABLE_NAME = "Game";
public static final String COLUMN_KNOWN = "Known";
public static final String COLUMN_TBF = "TBF";
public static final String SQL_CREATE_TABLE =
"CREATE TABLE " + TABLE_NAME + "("
+ _ID + " INTEGER PRIMARY KEY, "
+ COLUMN_KNOWN + " TEXT NOT NULL, "
+ COLUMN_TBF + " TEXT NOT NULL)";
}
}
CrdDBHelper.java
public class CrdDBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "CardGame.db";
public static final int DATABASE_VERSION = 1;
public CrdDBHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CrdDBContract.GameEntry.SQL_CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
CrdDBDataInsertion.java
public class CrdDBDataInsertion {
//??????????? Code not available from images
SQLiteDatabase mDB;
private void contentvalues(String Known, String TBF) {
ContentValues values = new ContentValues();
values.put(CrdDBContract.GameEntry.COLUMN_KNOWN,Known);
values.put(CrdDBContract.GameEntry.COLUMN_TBF,TBF);
long newid = mDB.insert(CrdDBContract.GameEntry.TABLE_NAME,null,values);
}
}
Main Activity part1Main Activity part2
Main Activity part3(final)
DB Contract class
DB Helper class
DB insert class part1
DB insert class part2 (final)
You aren't, according to the code, acessing(opening) the database. You are just instantiating the DatabseHelper in MainActivity i.e. mydb = new CrdDBHelper(this);
It is not until an attempt is made to open the database (which is frequently implicit) that the database is actually created.
A simple way would be to force an open when instantiating the database. e.g. call the getWritableDatabase() method in the constructor, like :-
public CrdDBHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
getWritableDatabase();
}
Perhaps at that time set an SQLiteDatabase object with the returned SQLiteDatabase, so your Database Helper (CrdDBHelper.java) could be :-
public class CrdDBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "CardGame.db";
public static final int DATABASE_VERSION = 1;
SQLiteDatabase mDB;
public CrdDBHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
mDB = this.getWriteableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CrdDBContract.GameEntry.SQL_CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
as the onCreate method is called when (and ONLY when) the database is created the Game table will then be created.
Related
Hello I want to implement a simple survey. I successfully added the questions with an insert query. The Questions however get added every time when I run the application.
I tried to use "Drop table if exists" but nothing happens.
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DBNAME= "Questionpool.db";
public static final String createdb = "Create table dtaquestions( questionId Integer Primary Key Autoincrement, dtaQuestion Varchar(100), dtaDepartment Varchar(100))";
public static final String dropdb = "Drop table if exists dtaquestions";
Context context;
public DatabaseHelper(Context context) {
super(context, DBNAME , null, 1);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(createdb);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(dropdb);
}
And in the Survey class I have this,
myDb = new DatabaseHelper(this);
SQLiteDatabase DB2=myDb.getWritableDatabase();
insertQuestions(DB2);
final Cursor res = getAllData(DB2);
bViewAll = (Button) findViewById(R.id.bViewAll);
bViewAll.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
#Override
public void onClick(View v) {
if(res.getCount()== 0){
tv.setText("nooo");
}else{
int counter = 0;
while(res.moveToNext()){
//show on screen
}
}
}
});
public void insertQuestions(SQLiteDatabase db){
String [] dtaQuestions = fillArray();
String [] dtaQuestionsDep = fillDepartment();
for (int i = 0 ; i < 18 ; i++ ){
ContentValues cv = new ContentValues();
cv.put("dtaQuestion", dtaQuestions[i]);
cv.put("dtaDepartment", dtaQuestionsDep[i]);
db.insert("dtaquestions", null, cv);
}
}
public Cursor getAllData(SQLiteDatabase db){
Cursor res = db.rawQuery("Select * from dtaquestions", null);
return res;
}
I have no idea why the drop query isn't working and the query keeps repeating itself.
Read de cocumentation: https://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper
onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
Called when the database needs to be upgraded.
When you create the helper the version is always 1.
super(context, DBNAME , null, 1);
You need to change the version.
You can declare the version and then use it:
private static final int VERSION=2;
public DatabaseHelper(Context context) {
super(context, DBNAME , null,VERSION);
this.context = context;
}
I would like to ask anyone to please help me to modify my database connection code. What I have now is it's a part of one of my method class and it will make a connection every time I call it ( which I know its very inefficient). But when I try to move the connection part out from the method it breaks the code. I just wonder if I could make a static class somewhere so I can reuse it in other method as well.
Thanks so much for any help in advance, it is really appreciated.
Here is the method code:
public void getListDetail(){
//listDetailData.clear();
ShoppingListDatabase databaseConnection = new ShoppingListDatabase(this);
final SQLiteDatabase db = databaseConnection.open();
final ArrayList<ShoppingItem> lists = ShoppingListItemTable.selectAllItems(db, selectedID);
databaseConnection.close();
//create a list adapter and set adapter
ShoppingListItemAdapter adapter = new ShoppingListItemAdapter(this, R.layout.activity_item_detail_list, lists);
ListView_ListDetail = findViewById(R.id.ListView_ListDetail);
ListView_ListDetail.setAdapter(adapter);
adapter.notifyDataSetChanged();
// ((ArrayAdapter<String>)ListView_ListDetail.getAdapter()).notifyDataSetChanged();
}
Database class:
package com.puyakul.prin.psychic_shopping;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.ContactsContract;
import android.util.Log;
public class ShoppingListDatabase {
private static final String TAG = "ShoppingListDatabase";
private static final String DATABASE_NAME = "ShoppingListDatabase";
private static final int DATABASE_VERSION = 3;
private SQLiteDatabase mDb;
private DatabaseHelper mDbHealper;
private final Context mCtx;
public ShoppingListDatabase(Context ctx){
this.mCtx = ctx;
}
/**
* DatabaseHelper class.
*
* Database helper class to manage connections with the database.
*/
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.d(TAG, "DatabaseHelper onCreate");
db.execSQL(ShoppingListItemTable.CREATE_STATEMENT);
db.execSQL(ShoppingListTable.CREATE_STATEMENT);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d(TAG, "DatabaseHelper onUpgrade");
db.execSQL("DROP TABLE IF EXISTS " + ShoppingListItemTable.TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + ShoppingListTable.TABLE_NAME);
onCreate(db); //this will recreate the database as if it were new
}
}
public SQLiteDatabase open(){
mDbHealper = new DatabaseHelper(mCtx);
mDb = mDbHealper.getReadableDatabase();
return mDb;
}
public void close(){
mDb = null;
}
}
I have tried to declare variables within onCreate so I can use with other methods in the class like this
//================DATABASE CONNECTION=====================//
private ShoppingListDatabase databaseConnection;
private SQLiteDatabase db = databaseConnection.open();
private String selectedList;
private int selectedID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
setContentView(R.layout.activity_main_lists_detail);
ShoppingListDatabase databaseConnection = new ShoppingListDatabase(this);
SQLiteDatabase db = databaseConnection.open();
lists = ShoppingListItemTable.selectAllItems(db, selectedID);
and this is the error
Process: com.puyakul.prin.psychic_shopping, PID: 5635
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.puyakul.prin.psychic_shopping/com.puyakul.prin.psychic_shopping.MainListsDetail}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase com.puyakul.prin.psychic_shopping.ShoppingListDatabase.open()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2548)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase com.puyakul.prin.psychic_shopping.ShoppingListDatabase.open()' on a null object reference
at com.puyakul.prin.psychic_shopping.MainListsDetail.<init>(MainListsDetail.java:46)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2538)
Opening and closing the connection can be inefficient/costly so perhaps introduce/use the following :-
public SQLiteDatabase open(){
if (mDb == null) {
mDbHealper = new DatabaseHelper(mCtx);
mDb = mDbHealper.getReadableDatabase();
}
return mDb;
}
or alternately :-
public synchronized SQLiteDatabase open(){
if (mDb == null) {
mDbHealper = new DatabaseHelper(mCtx);
mDb = mDbHealper.getReadableDatabase();
}
return mDb;
}
and never call the close, except when the main activity is being destroyed. Then you will retrieve the one connection.
Here's some example uses based upon your ShoppingListDatabase class.
First a modified class with a few extra methods inside (addShoppingList, getAllShoppingListsAsCursor and logDBTables) and just a very simple shoppinglist table :-
public class ShoppingListDatabase {
private static final String TAG = "ShoppingListDatabase";
private static final String DATABASE_NAME = "ShoppingListDatabase";
private static final int DATABASE_VERSION = 3;
private static final String TBNAME = "shoppinglist";
public static final String COL_SHOPPINGLIST_NAME = "shoppinglist_name";
private SQLiteDatabase mDb;
private DatabaseHelper mDbHealper;
private final Context mCtx;
public ShoppingListDatabase(Context ctx){
this.mCtx = ctx;
}
/**
* DatabaseHelper class.
*
* Database helper class to manage connections with the database.
*/
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.d(TAG, "DatabaseHelper onCreate");
//db.execSQL(ShoppingListItemTable.CREATE_STATEMENT);
//db.execSQL(ShoppingListTable.CREATE_STATEMENT);
String crtsql = "CREATE TABLE If NOT EXISTS " + TBNAME + "(" +
COL_SHOPPINGLIST_NAME + " TEXT " +
")";
db.execSQL(crtsql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d(TAG, "DatabaseHelper onUpgrade");
//db.execSQL("DROP TABLE IF EXISTS " + ShoppingListItemTable.TABLE_NAME);
//db.execSQL("DROP TABLE IF EXISTS " + ShoppingListTable.TABLE_NAME);
onCreate(db); //this will recreate the database as if it were new
}
}
public synchronized SQLiteDatabase open(){
if (mDb == null) {
mDbHealper = new DatabaseHelper(mCtx);
mDb = mDbHealper.getReadableDatabase();
}
return mDb;
}
public void close(){
mDb = null;
}
public long addShoppingList(String name) {
ContentValues cv = new ContentValues();
cv.put(COL_SHOPPINGLIST_NAME,name);
return mDb.insert(TBNAME,null,cv);
}
public Cursor getAllShoppingListAsCursor() {
return mDb.query(TBNAME,
null,
null,
null,
null,null,
null
);
}
public void logDBTables() {
Cursor csr = mDb.query("sqlite_master",null,null,null,null,null,null);
while (csr.moveToNext()) {
Log.d(TAG,"Item " +
csr.getString(csr.getColumnIndex("name")) +
" was created using " +
csr.getString(csr.getColumnIndex("sql"))
);
}
}
}
Here's code from an Activity (that uses the Database connection in various ways) :-
public class MainActivity extends AppCompatActivity {
ShoppingListDatabase mSL;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSL = new ShoppingListDatabase(this);
mSL.open();
SO50312618();
SO50312618_other();
Cursor csr = mSL.getAllShoppingListAsCursor();
while(csr.moveToNext()) {
Log.d("SL INFO","Shopping List " + String.valueOf(csr.getPosition() + 1) +
" is " +
csr.getString(csr.getColumnIndex(ShoppingListDatabase.COL_SHOPPINGLIST_NAME))
);
}
}
private void SO50312618() {
ShoppingListDatabase databaseConnection = new ShoppingListDatabase(this);
SQLiteDatabase db = databaseConnection.open();
databaseConnection.logDBTables();
}
private void SO50312618_other() {
mSL.addShoppingList("List001");
mSL.addShoppingList("List002");
}
}
The results being :-
05-13 05:36:24.290 4245-4245/soanswers.soanswers D/ShoppingListDatabase: Item android_metadata was created using CREATE TABLE android_metadata (locale TEXT)
Item shoppinglist was created using CREATE TABLE shoppinglist(shoppinglist_name TEXT )
05-13 05:36:24.302 4245-4245/soanswers.soanswers D/SLĀ INFO: Shopping List 1 is List001
Shopping List 2 is List002
All the various uses will use the same single connection.
I tried to create a database and create one table in it. The database is being created but not the table.it doesn't show any error and also am not able to insert the value into it.I want to create a table and insert the data recieved from the user but the data is not able to add to database, neither it shows any errors.The code is as follows:
public DataBaseHelper(Context context) {
super(context, DATABASE_NAME, null, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
String q = "CREATE TABLE IF NOT EXISTS " + TABLE_NAMETRY + "(" +
COL_ID + " INTEGER PRIMARY KEY, " + COL_NAME + " TEXT, " + COL_PHONE + " TEXT " + ")";`enter code here`
db.execSQL(q);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP table if exist "+TABLE_NAMETRY);
onCreate(db);
}
public boolean insertData(String name,String no)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentvalue = new ContentValues();
contentvalue.put(COL_NAME,name);
contentvalue.put(COL_PHONE,no);
long result = db.insert(TABLE_NAMETRY,null,contentvalue);
if(result==-1)
return false;
else
return true;
}
public class MainActivity extends AppCompatActivity {
DataBaseHelper mydb;
EditText name,no;
Button b1;
TextView t1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mydb=new DataBaseHelper(this);
name=(EditText)findViewById(R.id.name);
no=(EditText)findViewById(R.id.no);
t1=(TextView)findViewById(R.id.t1);
b1=(Button)findViewById(R.id.b1);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "Adding Data", Toast.LENGTH_SHORT).show();
AddData();
}
});
}
public void AddData()
{
boolean check= mydb.insertData(name.getText().toString(),no.getText().toString());
if(check==true)
t1.setText("data submitted");
else
t1.setText("data not submitted");
}
}
Most probably the helper is creating the table (onCreate) and then delete it (onUpgrade).
Here how I create my helper, take notice of the databaseVersion, as it is important when the (onUpgrade) is executed
public class DatabaseOpenHelper extends SQLiteOpenHelper {
private final static String databaseName = "Your_DB_Name";
private final static int databaseVersion = 13;
DatabaseOpenHelper(Context context) {
super(context, databaseName, null, databaseVersion);
}
#Override
public void onCreate(SQLiteDatabase db) { // Do Create Your Table Here }
#Override
public void onUpgrade(SQLiteDatabase db, int Old_Version, int New_Version) { //Delete Your tables here if they exists}
I am not getting the add string returned back.
The android app takes input as food item and prints its respective calories.
here is the code for creating table:
public class dietclass extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "diet7.db";
public static final String TABLE_NAME = "Cal_val";
public static final String COL1 = "ID";
public static final String COL2 = "ITEM";
public static final String COL3 = "QUANTITY";
public static final String COL4 = "CALORIES";
public dietclass(Context context) {
super(context,DATABASE_NAME,null,1);
SQLiteDatabase db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,ITEM TEXT,QUANTITY VARCHAR,CALORIES INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " +TABLE_NAME);
onCreate(db);
}
}
And here is the code for retrieving data from my activity which is taking item and calories as input.
public class foodcal extends AppCompatActivity {
EditText item;
EditText quantity;
TextView calories;
Button calculate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_foodcal);
item = (EditText)findViewById(R.id.etitem);
quantity = (EditText)findViewById(R.id.etquantity);
calories = (TextView)findViewById(R.id.calories);
calculate = (Button)findViewById(R.id.calculate);
calculate.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String itemstr = item.getText().toString();
printDatabase(itemstr);
//String dbstring = dietclass.databaseToString(itemstr);
//calories.setText(String.valueOf(dbstring));
}
});
}
public void printDatabase(String item){
String dbstring = dietclass.databaseToString(this,item);
//String label;
//label = dbstring + "calories";
calories.setText(String.valueOf(dbstring));
}
private static class dietclass extends SQLiteOpenHelper {
private static String DB_PATH = "/data/data/com.example.janhvik.dietapp/databases/";
private static String DB_NAME = "diet7.db";
private static String TABLE_NAME = "Cal_val";
private static SQLiteDatabase myDataBase;
private Context myContext;
public dietclass(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
private static String databaseToString(Context ctx, String item_name) {
String myDbPath;
int cal = 0 ;
String add="";
myDbPath = DB_PATH+DB_NAME;
myDataBase = SQLiteDatabase.openOrCreateDatabase(myDbPath, null);
String query = "SELECT * FROM "+TABLE_NAME+" WHERE ITEM='"+item_name+"'";
Cursor c = myDataBase.rawQuery(query,null);
if(c!= null && c.moveToFirst()){
add = c.getString(c.getColumnIndex("CALORIES"));
c.close();
}
add = add + " calories";
//Toast.makeText(ctx,add, Toast.LENGTH_LONG).show();
return add;
}
I am not getting any error but the code is not taking the value from the select query, can anyone help in this.
I think you've got rather mixed up and complicated matters by appearing to use multiple database helpers/methods to open the same database when you only need to use the database helper. I'm unsure what the exact issue was, there was insufficient code to build an exact replica.
Instead a created simplified working code.
Here's a rewrite/simplification based upon your code :-
First ONE databasehelper class namely dietclass :-
public class dietclass extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "diet7.db";
public static final String TABLE_NAME = "Cal_val";
public static final String COL1 = "ID";
public static final String COL2 = "ITEM";
public static final String COL3 = "QUANTITY";
public static final String COL4 = "CALORIES";
//private static String DB_PATH = "/data/data/com.example.janhvik.dietapp/databases/";
//private static String DB_NAME = "diet7.db";
SQLiteDatabase myDataBase;
private Context myContext;
public dietclass(Context context) {
super(context,DATABASE_NAME,null,1);
myDataBase = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,ITEM TEXT,QUANTITY VARCHAR,CALORIES INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " +TABLE_NAME);
onCreate(db);
}
public long insertCal_ValEntry(String item, String quantity, int calories) {
ContentValues cv = new ContentValues();
cv.put(COL2,item);
cv.put(COL3,quantity);
cv.put(COL4,calories);
return myDataBase.insert(TABLE_NAME,null,cv);
}
public String databaseToString(String item_name) {
//String myDbPath;
int cal = 0 ;
String add="";
//myDbPath = DB_PATH+DB_NAME;
//myDataBase = SQLiteDatabase.openOrCreateDatabase(myDbPath, null);
String query = "SELECT * FROM "+TABLE_NAME+" WHERE ITEM='"+item_name+"'";
Cursor c = myDataBase.rawQuery(query,null);
if(c.moveToFirst()){
add = c.getString(c.getColumnIndex("CALORIES"));
c.close();
}
add = add + " calories";
//Toast.makeText(ctx,add, Toast.LENGTH_LONG).show();
return add;
}
}
Notes
For testing purposes, method insertCal_ValEntry has been added.
Done away with any attempt to open Database rather this is done by the helper.
The check to see if the cursor is null has been removed, it is basically useless as SQLite will not return a null, it will always return a cursor, which may be empty. the Cursor move??? methods, such as moveToFirst return false if the move cannot be made.
Context isn't required by the databaseToString method so removed it.
databaseToString method made to be an instance method rather than class method (i.e not static) and made it public.
The activity in this case I've used MainActivity
public class MainActivity extends AppCompatActivity {
EditText item;
EditText quantity;
TextView calories;
Button calculate;
dietclass dbhelper; //<<<< we want an instance of the database helper
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_foodcal);
item = (EditText)findViewById(R.id.etitem);
quantity = (EditText)findViewById(R.id.etquantity);
calories = (TextView)findViewById(R.id.calories);
calculate = (Button)findViewById(R.id.calculate);
dbhelper = new dietclass(this); //<<<< get the instance of the database helper
dbhelper.insertCal_ValEntry("Porridge", "100g",5000); //<<<< For testing
dbhelper.insertCal_ValEntry("Cake","500g", 20000); //<<<< For testing
calculate.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String itemstr = item.getText().toString();
printDatabase(itemstr);
//String dbstring = dietclass.databaseToString(itemstr);
//calories.setText(String.valueOf(dbstring));
}
});
}
public void printDatabase(String item){
String dbstring = dbhelper.databaseToString(item); //<<<<
//String label;wr
//label = dbstring + "calories";
calories.setText(String.valueOf(dbstring));
}
}
Notes
The principle used above could be used in any activity. That is get an instance of the database helper and then invoked methods within the helper to get/add/alter data in the database.
Results from the above:-
1) When App is started:-
2) Clicking without input (or inputting item not in table) :-
3) Clicking after inputting valid item :-
Additional Info
If you really want to get the database path the following is less prone to errors:-
String databasepath = getDatabasePath(dietclass.DATABASE_NAME).getPath();
((TextView) findViewById(R.id.dbpath)).setText(databasepath);
With the dbpath TextView (note run on 7.0.0 device):-
On a 4.1.1 device :-
I read several tutorials and the sqlite section in a book and applied it which works great. Now I messed with it to try and understand it but now it will just force close every single time and i'm not sure why. I've been over my code again and again but maybe I can't find the problem because i'm new to sqlite/databases in general. Any help would be appreciated:
public class Events extends Activity {
private TextView tv;
private DataHelper dh;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tv = new TextView(this);
dh = new DataHelper(this);
dh.deleteAll();
//dh.addEvent("James");
//Cursor c = dh.getEvent();
//startManagingCursor(c);
//tv.setText(dh.showEvent(c));
setContentView(tv);
}
}
public class EventsData extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "events.db";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE = "CREATE TABLE" + TABLE_NAME + "(" + TITLE + " TEXT)";
private static final String DATABASE_UPGRADE = "DROP TABLE IF EXISTS " + TABLE_NAME;
public EventsData(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL(DATABASE_UPGRADE);
onCreate(db);
}
}
public class DataHelper {
private Context context;
private SQLiteDatabase db;
private EventsData eventsData;
public DataHelper(Context context) {
this.context = context;
eventsData = new EventsData(this.context);
}
public void addEvent(String name) {
db = eventsData.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(TITLE, name);
db.insertOrThrow(TABLE_NAME, null, cv);
}
}
Commenting out addEvent() will run the app fine but once I uncomment it, it force closes.
Fast shot: There's no space after CREATE TABLE.
You can check the logcat for the error message. It will tell you what is causing the force close. Link to debugging using logcat Debugging in Android using Eclipse