Passing the right App Context to the Database Handler fails - java

I am working on an Android App with a Database and I am having troubles in passing the right context to my Database Handler, as the instance of the App Context that I am passing to the Database Handler seems to be always null;
as I have been working on this for hours to make it work, I would appreciate any hints or constructive Feedback to make this work.
The app crashes always with the same Null Pointer Exception:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.Cursor android.database.sqlite.SQLiteDatabase.rawQuery(java.lang.String, java.lang.String[])' on a null object reference
in the method DatabaseHandler.getAllItems, at this part:
try (SQLiteDatabase db = this.getWritableDatabase(GoldbekStorageApp.getInstance())) {
cursor = db.rawQuery(selectQuery, null);
}
This is my Database Handler:
enter code herepackage com.example.xxx;
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;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.jetbrains.annotations.NotNull;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_NAME = "itemsManager";
private static final String TABLE_ITEMS = "items";
private static final String KEY_NO = "number";
private static final String TAG = "Database values";
private static final String KEY_NAME = "name";
private static final String KEY_EAN = "ean";
private static final String KEY_TYPE = "type";
private static final String KEY_ITEMGROUPNAME = "itemgroupname";
private static final String KEY_DESTRUCTION = "destruction";
private static final String KEY_ARCHIVED = "archived";
public static final String TAGGGG = "Datenbank" ;
private String No;
private String Ean;
private String Name;
private String Itemgroupname;
private String Type;
private Boolean Destruction;
private Boolean Archived;
public Context context;
public String uname;
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
//3rd argument to be passed is CursorFactory instance
this.context = context; // add this line to initialize your context.
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_ITEMS_TABLE = "CREATE TABLE " + TABLE_ITEMS + "("
+ KEY_NO + " TEXT ," + KEY_NAME + " TEXT,"
+ KEY_ITEMGROUPNAME + " TEXT,"
+ KEY_TYPE + " TEXT,"
+ KEY_EAN + " TEXT,"
+ KEY_DESTRUCTION + " BOOLEAN,"
+ KEY_ARCHIVED + " BOOLEAN" +")";
Log.d(TAG, CREATE_ITEMS_TABLE);
db.execSQL(CREATE_ITEMS_TABLE);
}
public boolean getItemByEAN(String code) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor mCursor = db.rawQuery("SELECT * FROM items WHERE ean =?", new String[]{ Ean });
if (mCursor != null)
{
Log.d(TAGGGG, "Worked");
return true;
/* record exist */
}
else
{
Log.d(TAGGGG, "Did not worked");
return false;
/* record not exist */
}
}
public void checkItemAgainstDatabase(String code)
{
String selectQuery = "SELECT * FROM " + TABLE_ITEMS + " WHERE " + KEY_EAN + "='" + code + "'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if(cursor == null)
{
Log.d(TAGGGG, "Cursor ist Null, Item not present");
return;
}
if (cursor.getCount() == 0) {
Log.d(TAGGGG, " Item not present");
} else {
Log.d(TAGGGG, " Item present");
}
db.close();
return;
/*
for (Item item : itemList) {
String itemEanToBeMatched = item.getEan();
if (itemEanToBeMatched.equals(code)) {
Toast.makeText(Context, code, Toast.LENGTH_LONG).show();
//ScanService.checkEnteredCode(code, code, content, mContext.getApplicationContext());
}
String itemNoToBeMatched = item.getNo();
if (itemNoToBeMatched.equals(code)) {
Toast.makeText(mContext, code, Toast.LENGTH_LONG).show();
//ScanService.checkEnteredCode(code, code, content, mContext.getApplicationContext());
}
else {
Toast.makeText(mContext, R.string.not_in_database, Toast.LENGTH_LONG).show();
Vibrator vibrator;
vibrator = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(3000);
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(mContext.getApplicationContext(), notification);
r.play();
break;
}
} */
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ITEMS);
// Create tables again
onCreate(db);
}
// code to add the new item
public void addItem(Item items) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NO, ""+items.getNo()); // Item Ean
values.put(KEY_EAN, ""+items.getEan()); // Item Ean
values.put(KEY_NAME, items.getName()); // Item Name
values.put(KEY_TYPE, items.getType());
//values.put(KEY_ITEMGROUPNAM, item.getItemgroupname()); // Item Groupname
values.put(String.valueOf(KEY_ARCHIVED), items.getArchived());
values.put(String.valueOf(KEY_DESTRUCTION), items.getDestruction());
// Inserting Row
db.insert(TABLE_ITEMS, null, values);
//2nd argument is String containing nullColumnHack
db.close(); // Closing database connection
}
// code to get the single contact
public Item getItem(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_ITEMS, new String[] { KEY_NO,
KEY_NAME, KEY_EAN,KEY_TYPE, String.valueOf(KEY_ARCHIVED),
String.valueOf(KEY_DESTRUCTION)}, KEY_NO + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Item item = new Item(cursor.getString(0),
cursor.getString(1), cursor.getString(2),
cursor.getString(3),cursor.getString(4),cursor.getExtras().getBoolean(String.valueOf(5)),
Boolean.getBoolean(String.valueOf(6)));
Log.d(TAGGGG, String.valueOf(item));
// return contact
return item;
}
// code to get all contacts in a list view
public List<Item> getAllItems(Context context) {
List<Item> itemList = new List<Item>() {
#Override
public int size() {
return 0;
}
#Override
public boolean isEmpty() {
return false;
}
#Override
public boolean contains(#Nullable #org.jetbrains.annotations.Nullable Object o) {
return false;
}
#NonNull
#NotNull
#Override
public Iterator<Item> iterator() {
return null;
}
#NonNull
#NotNull
#Override
public Object[] toArray() {
return new Object[0];
}
#NonNull
#NotNull
#Override
public <T> T[] toArray(#NonNull #NotNull T[] a) {
return null;
}
#Override
public boolean add(Item item) {
return false;
}
#Override
public boolean remove(#Nullable #org.jetbrains.annotations.Nullable Object o) {
return false;
}
#Override
public boolean containsAll(#NonNull #NotNull Collection<?> c) {
return false;
}
#Override
public boolean addAll(#NonNull #NotNull Collection<? extends Item> c) {
return false;
}
#Override
public boolean addAll(int index, #NonNull #NotNull Collection<? extends Item> c) {
return false;
}
#Override
public boolean removeAll(#NonNull #NotNull Collection<?> c) {
return false;
}
#Override
public boolean retainAll(#NonNull #NotNull Collection<?> c) {
return false;
}
#Override
public void clear() {
}
#Override
public boolean equals(#Nullable #org.jetbrains.annotations.Nullable Object o) {
return false;
}
#Override
public int hashCode() {
return 0;
}
#Override
public Item get(int index) {
return null;
}
#Override
public Item set(int index, Item element) {
return null;
}
#Override
public void add(int index, Item element) {
}
#Override
public Item remove(int index) {
return null;
}
#Override
public int indexOf(#Nullable #org.jetbrains.annotations.Nullable Object o) {
return 0;
}
#Override
public int lastIndexOf(#Nullable #org.jetbrains.annotations.Nullable Object o) {
return 0;
}
#NonNull
#NotNull
#Override
public ListIterator<Item> listIterator() {
return null;
}
#NonNull
#NotNull
#Override
public ListIterator<Item> listIterator(int index) {
return null;
}
#NonNull
#NotNull
#Override
public List<Item> subList(int fromIndex, int toIndex) {
return null;
}
};
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_ITEMS;
Cursor cursor;
try (SQLiteDatabase db = this.getWritableDatabase(GoldbekStorageApp.getInstance())) {
cursor = db.rawQuery(selectQuery, null);
}
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Item item = new Item(No, Name, Itemgroupname, Ean, Type, Destruction, Archived);
item.setNo(cursor.getString(0));
item.setName(cursor.getString(1));
item.setEan(cursor.getString(2));
item.setType(cursor.getString(2));
// Adding items to list
itemList.add(item);
} while (cursor.moveToNext());
}
// return contact list
return itemList;
}
private SQLiteDatabase getWritableDatabase(GoldbekStorageApp context) {
return null;
}
// code to update the single item
public int updateItem(Item item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NO, item.getNo());
values.put(KEY_NAME, item.getName());
values.put(KEY_EAN, item.getEan());
values.put(KEY_ITEMGROUPNAME, item.getItemgroupname());
values.put(KEY_TYPE, item.getType());
values.put(String.valueOf(KEY_DESTRUCTION), item.getDestruction());
values.put(String.valueOf(KEY_ARCHIVED), item.getArchived());
// updating row
return db.update(TABLE_ITEMS, values, KEY_NO + " = ?",
new String[] { String.valueOf(item.getNo()) });
}
// Deleting single item
public void deleteItem(Item item) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_ITEMS, KEY_NO + " = ?",
new String[] { String.valueOf(item.getNo()) });
db.close();
}
// Getting items Count
public int getItemsCount() {
String itemQuery = "SELECT * FROM " + TABLE_ITEMS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(itemQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
This is my onCreate-Method in the MainActivity, where I am calling the
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Sentry.captureMessage("testing SDK setup");
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getPosts();
//In the following lines, I am initializing the Context of my App and passing it //to the Database Handler and the Method Call of the method in the Database //Handler
*mContext = GoldbekStorageApp.getInstance();
DatabaseHandler db = new DatabaseHandler(mContext);
List<Item> items = db.getAllItems(mContext);*
new LongOperation().execute();
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(R.id.nav_palette,
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
This is how I define the context of the App:
import android.app.Application;
import android.content.Context;
public class GoldbekStorageApp extends Application {
private static Context mContext;
public static GoldbekStorageApp mInstance= null;
public String palNo;
public String getPalNo() {
return palNo;
}
public void setPalNo(String palNo) {
this.palNo = palNo;
}
public GoldbekStorageApp(){}
public static synchronized GoldbekStorageApp getInstance() {
if(null == mInstance){
mInstance = new GoldbekStorageApp();
}
return mInstance;
}
}
I have the slight feeling that I am failing to initialize and pass the App Context to the Database Handler, but I don´t have the slightest idea where I am failing and what´s going wrong, as I am not an expert in handling the Context in Android; hence, any hints or help would be appreciated, thanks!

It's not the Context.
Instead you should remove this method:
private SQLiteDatabase getWritableDatabase(GoldbekStorageApp context) {
return null;
}
and just use SQLiteOpenHelper#getWritableDatabase() - it does not return nulls, and you pass a Context to it in the class's constructor.
There are a number of other problems with the code, this is a reason for the NPE when trying to invoke rawQuery() on null.

First, don't create Application object. This is done by Android.
Static way to get 'Context' in Android?
Second, do you really need it? Activity has context. It is Context, in fact. If you need application context, then activity has getApplicationContext() method

You need to change your getInstance method and Ctor in GoldbekStorageApp to:
public static synchronized GoldbekStorageApp getInstance(Context con) {
if(null == mInstance){
mInstance = new GoldbekStorageApp(con);
}
return mInstance;
}
public GoldbekStorageApp(Context con){mContext = con}
Do note, I am not sure why, I just know I've read in several places that holding a static reference to the app Context is not recommended.
The first time you are calling getInstance you need to make sure you are passing a valid context (i.e getApplicationContext() or MainActivity.this or something of the sort) later calls can be made with passing null as parameter since it will be ignored anyway

Related

How to Retrieve Multiple data when clicked on listview?

I want all edit text content that I have saved in SQL to be displayed on the edit bills activity when I click on the list item, but I am only able to retrieve the name and display it again in the intent. Rather than saving another data it should update the record with the new data if I save the existing record another time in the editbills_activity.
Here is my DBAdapter.java
package com.example.dhruv.bills;
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.util.Log;
public class DBAdapter {
public static final String KEY_ROWID = "id";
public static final String KEY_NAME = "name";
public static final String KEY_AMOUNT = "amount";
public static final String KEY_DUEDATE = "duedate";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "billsdb";
private static final String DATABASE_TABLE = "bills";
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE =
"create table if not exists assignments (id integer primary key autoincrement, "
+ "name VARCHAR not null, amount VARCHAR, duedate date );";
// Replaces DATABASE_CREATE using the one source definition
private static final String TABLE_CREATE =
"CREATE TABLE IF NOT EXISTS " + DATABASE_TABLE + "(" +
KEY_ROWID + " INTEGER PRIMARY KEY, " + // AUTOINCREMENT NOT REQD
KEY_NAME + " DATE NOT NULL, " +
KEY_AMOUNT + " VARCHAR ," +
KEY_DUEDATE + " DATE " +
")";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(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(TABLE_CREATE); // NO need to encapsulate in try clause
}
#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 contacts"); //????????
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
//---insert a record into the database---
public long insertRecord(String name, String amount, String duedate)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_AMOUNT, amount);
initialValues.put(KEY_DUEDATE, duedate);
//return db.insert(DATABASE_TABLE, null, initialValues);
// Will return NULL POINTER EXCEPTION as db isn't set
// Replaces commented out line
return DBHelper.getWritableDatabase().insert(DATABASE_TABLE,
null,
initialValues
);
}
//---deletes a particular record---
public boolean deleteContact(long rowId)
{
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
//---retrieves all the records--- SEE FOLLOWING METHOD
public Cursor getAllRecords()
{SQLiteDatabase db = DBHelper.getWritableDatabase();
String query ="SELECT * FROM " + DATABASE_TABLE;
Cursor data = db.rawQuery(query,null);
return data;
}
//As per getAllRecords but using query convenience method
public Cursor getAllAsCursor() {
return DBHelper.getWritableDatabase().query(
DATABASE_TABLE,
null,null,null,null,null,null
);
}
public Cursor getItemID(String name) {
SQLiteDatabase db = DBHelper.getWritableDatabase();
String query = "SELECT " + KEY_ROWID + " FROM " + DATABASE_TABLE +
" WHERE " + KEY_NAME + " = '" + name + "'";
Cursor data = db.rawQuery(query, null);
return data;
}
//---retrieves a particular record--- THIS WILL NOT WORK - NO SUCH TABLE
/* public Cursor getRecord()
{String query1 ="SELECT * FROM" + KEY_TITLE;
Cursor mCursor = db.rawQuery(query1,null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}*/
// Retrieve a row (single) according to id
public Cursor getRecordById(long id) {
return DBHelper.getWritableDatabase().query(
DATABASE_TABLE,
null,
KEY_ROWID + "=?",
new String[]{String.valueOf(id)},
null,null,null
);
}
//---updates a record---
/* public boolean updateRecord(long rowId, String name, String amount, String duedate)
{
ContentValues args = new ContentValues();
args.put(KEY_NAME, name);
args.put(KEY_AMOUNT, amount);
args.put(KEY_DUEDATE, duedate);
String whereclause = KEY_ROWID + "=?";
String[] whereargs = new String[]{String.valueOf(rowId)};
// Will return NULL POINTER EXCEPTION as db isn't set
//return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
// Replaces commented out line
return DBHelper.getWritableDatabase().update(DATABASE_TABLE,
args,
whereclause,
whereargs
) > 0;
}*/
}
Here is my Bills.java
(MainActivity)
Problem: Bills.java has the list view that shows the intent whenever the item in list view is clicked, but it does not put the amount and date or update the record. Instead it saves another record.
Solution: I want to retrieve it and display all (name ,amount,duedate) and instead of saving another record it should update it.
package com.example.dhruv.bills;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class bills extends AppCompatActivity {
DBAdapter dbAdapter;
ListView mrecycleview;
private static final String TAG ="assignments";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bills);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mrecycleview =(ListView) findViewById(R.id.mRecycleView);
dbAdapter = new DBAdapter(this);
// mlistview();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),Editbills.class);
startActivity(i);
}
});
mlistview();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_bills, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void mlistview(){
Log.d(TAG,"mlistview:Display data in listview");
Cursor mCursor = dbAdapter.getAllRecords();
ArrayList<String> listData = new ArrayList<>();
while (mCursor.moveToNext()){
listData.add(mCursor.getString(1));
}
ListAdapter adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,listData);
mrecycleview.setAdapter(adapter);
mrecycleview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String name = adapterView.getItemAtPosition(i).toString();
Log.d(TAG, "onItemClick: You Clicked on " + name);
Cursor data = dbAdapter.getItemID(name); //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 editScreenIntent = new Intent(bills.this, Editbills.class);
editScreenIntent.putExtra("id",itemID);
editScreenIntent.putExtra("name",name);
startActivity(editScreenIntent);
}
else{
}
}
});
}
}
here is my editbills.java code
package com.example.dhruv.bills;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class Editbills extends AppCompatActivity {
Button button;
private static final String Tag= "assignments";
DBAdapter db = new DBAdapter(this);
private String selectedName;
private int selectedID;
DBAdapter dbAdapter;
private EditText editText,editText2,editText3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editbills);
button=(Button)findViewById(R.id.button);
editText =(EditText)findViewById(R.id.editText);
editText2=(EditText)findViewById(R.id.editText2);
editText3 =(EditText)findViewById(R.id.editText3);
//get the intent extra from the ListDataActivity
Intent receivedIntent = getIntent();
//now get the itemID we passed as an extra
selectedID = receivedIntent.getIntExtra("id",-1); //NOTE: -1 is just the default value
//now get the name we passed as an extra
selectedName = receivedIntent.getStringExtra("name");
//set the text to show the current selected name
editText.setText(selectedName);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("test", "adding");
db.open();
long id = db.insertRecord(editText.getText().toString(), editText2.getText().toString(), editText3.getText().toString());
db.close();
Toast.makeText(Editbills.this," Added", Toast.LENGTH_LONG).show();
Intent q = new Intent(getApplicationContext(),bills.class);
startActivity(q);
}
});
}
}
There are two parts/questions.
First to retrieve the data, so that it can be displayed in the editbills activity, you can utilise the row's id that is passed to the activity in conjunction with the getRecordById method.
I'd suggest that adding a method to the editbills class will simplyfy matters.
private void populateDisplay(int id) {
Cursor csr = dbAdapter.getRecordById(id);
if (csr.moveToFirst()) {
editText.setText(csr.getString(csr.getColumnIndex(DBAdapter.KEY_NAME)));
editText2.setText(csr.getString(csr.getColumnIndex(DBAdapter.KEY_AMOUNT)));
editText3.setText(csr.getString(csr.getColumnIndex(DBAdapter.KEY_DUEDATE)));
}
csr.close();
}
You could invoke the above method after retrieving the id from the Intent using :-
populateDisplay(selectedID);
To update based upon the content's of the EditTexts un-comment the updateRecord method in DBAdapter.java and the change :-
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("test", "adding");
db.open();
long id = db.insertRecord(editText.getText().toString(), editText2.getText().toString(), editText3.getText().toString());
db.close();
Toast.makeText(Editbills.this," Added", Toast.LENGTH_LONG).show();
Intent q = new Intent(getApplicationContext(),bills.class);
startActivity(q);
}
});
to :-
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (dbAdapter.updateRecord(
selectedId,
editText.getText().toString(),
editText2.getText().toString(),
editText3.getText().toString())
) {
Log.d("TEST","Row successfully updated.");
Toast.makeText(getApplicationContext(),"Row Updated.",Toast.LENGTH_LONG).show();
populateDisplay(selectedId);
} else {
Toast.makeText(getApplicationContext(),"Row not Updated",Toast.LENGTH_LONG).show();
}
Intent q = new Intent(getApplicationContext(),bills.class);
startActivity(q);
}
});
You will additionally have to add a line initialise the dbAdapter i.e. dbAdapter = new DBAdapter(this); i.d suggest adding this line immediately after the line setContentView(R.layout.activity_editbills);
Note the above code is in-principle and has not been thoroughly tested so it may contains errors.
Edit complete working example :-
The following code is basically an implementation of the above, except modified to utilise a Bill class. Rather than an ArrayList<String> as the source for the Adapter it has ArrayList<Bill>.
Thus all the data (id, name, amount and duedate) is available.
You should notice that I've overridden the toString method to return a String that combines the name, amount and duedate. The ArrayAdapter uses the object's toString method to populate the view.
Saying that the critical value is the rowid or an alias of rowid as this can be used to identify a row even if the other data is identical (as would happen when running this example more than once due to the addSomeData method). Hence, only the id is extracted and passed to the Editbills activity when an item in the list is long clicked (changed from just clicked to reduce the potential for accidental use).
Bill.java
public class Bill {
private long id;
private String name;
private String amount;
private String duedate;
public Bill(long id, String name, String amount, String duedate) {
this.id = id;
this.name = name;
this.amount = amount;
this.duedate = duedate;
}
/*
Note if this Constructor used then setId should be used
*/
public Bill(String name, String amount, String duedate) {
new Bill(0,name,amount,duedate);
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getDuedate() {
return duedate;
}
public void setDuedate(String duedate) {
this.duedate = duedate;
}
/*
As ArrayAdapter uses toString method change this
to return all items
*/
#Override
public String toString() {
return name + " " + amount + " " + duedate;
}
}
MainActivity.java
This is the equivalent to your Bills.java without a lot of the bloat such as FAB. :-
public class MainActivity extends AppCompatActivity {
public static final String ID_INTENTEXTRA = DBAdapter.KEY_ROWID + "_INTENTEXTRA"; //<<<< ADDED
DBAdapter mDBAdapter;
Cursor mCsr;
ListView mrecycleview;
ArrayAdapter adapter; //<<<< NOT ListAdapter
Context context; // ADDED
private static final String TAG ="assignments";
ArrayList<Bill> mBillList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
mrecycleview = this.findViewById(R.id.mRecycleView);
mDBAdapter = new DBAdapter(this);
addSomeData();
adapter = new ArrayAdapter<Bill>(
this,
android.R.layout.simple_list_item_1,
mBillList
);
mrecycleview.setAdapter(adapter);
mrecycleview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Bill b = (Bill) adapter.getItem(position);
Intent i = new Intent(context,Editbills.class);
i.putExtra(ID_INTENTEXTRA,b.getId()); //Get ID
startActivity(i);
return true;
}
});
rebuildBillList();
}
//<<<< ADDED Method to refresh the ListView resumed
#Override
protected void onResume() {
super.onResume();
rebuildBillList();
}
// Add some data (note will add 2 rows each time it is run)
private void addSomeData() {
mDBAdapter.insertRecord("Bill1","2018-10-02","English");
mDBAdapter.insertRecord("Bill2","2018-09-03","Mathematics");
mDBAdapter.insertRecord("Bill3","2018-11-04", "Geography");
}
public void rebuildBillList() {
mBillList.clear();
mCsr = mDBAdapter.getAllAsCursor();
while (mCsr.moveToNext()) {
mBillList.add(new Bill(
mCsr.getLong(mCsr.getColumnIndex(DBAdapter.KEY_ROWID)),
mCsr.getString(mCsr.getColumnIndex(DBAdapter.KEY_NAME)),
mCsr.getString(mCsr.getColumnIndex(DBAdapter.KEY_AMOUNT)),
mCsr.getString(mCsr.getColumnIndex(DBAdapter.KEY_DUEDATE))
)
);
}
adapter.notifyDataSetChanged();
}
}
Note the above adds 3 rows each time it is run.
Editbills.java
public class Editbills extends AppCompatActivity {
Button button;
private static final String Tag = "assignments";
DBAdapter db = new DBAdapter(this);
private String selectedName;
private long selectedID;
DBAdapter dbAdapter;
private EditText editText,editText2,editText3;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editbills);
context = this;
dbAdapter = new DBAdapter(this); //<<<< ADDED
button=(Button)findViewById(R.id.button);
editText =(EditText)findViewById(R.id.edittext);
editText2=(EditText)findViewById(R.id.edittext2);
editText3 =(EditText)findViewById(R.id.edittext3);
//get the intent extra from the ListDataActivity
Intent receivedIntent = getIntent();
//now get the itemID we passed as an extra
selectedID = receivedIntent.getLongExtra(MainActivity.ID_INTENTEXTRA,-1L); //NOTE: -1 is just the default value
populateDisplay(selectedID);
//now get the name we passed as an extra
//selectedName = receivedIntent.getStringExtra("name");
//set the text to show the current selected name
//editText.setText(selectedName); <<<< commented out
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/*
Log.d("test", "adding");
db.open();
long id = db.insertRecord(editText.getText().toString(), editText2.getText().toString(), editText3.getText().toString());
db.close();
Toast.makeText(Editbills.this," Added", Toast.LENGTH_LONG).show();
*/
/*
* <<<< Not the way as it ends/closes the existing activity
Intent q = new Intent(getApplicationContext(),MainActivity.class);
startActivity(q);
*/
String toast = "Updated.";
if (dbAdapter.updateRecord(selectedID,
editText.getText().toString(),
editText2.getText().toString(),
editText3.getText().toString())) {
} else {
toast = "Not Updated.";
}
Toast.makeText(context,toast,Toast.LENGTH_LONG).show();
finish(); //<<<< ends/closes this activity and returns to calling activity
}
});
}
private void populateDisplay(long id) {
Cursor csr = dbAdapter.getRecordById(id);
if (csr.moveToFirst()) {
editText.setText(csr.getString(csr.getColumnIndex(DBAdapter.KEY_NAME)));
editText2.setText(csr.getString(csr.getColumnIndex(DBAdapter.KEY_AMOUNT)));
editText3.setText(csr.getString(csr.getColumnIndex(DBAdapter.KEY_DUEDATE)));
}
csr.close();
}
}
Basically as per the original answer.
DBAdapter.java
public class DBAdapter {
public static final String KEY_ROWID = "id";
public static final String KEY_NAME = "name";
public static final String KEY_AMOUNT = "amount";
public static final String KEY_DUEDATE = "duedate";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "billsdb";
private static final String DATABASE_TABLE = "bills";
private static final int DATABASE_VERSION = 2;
// Replaces DATABASE_CREATE using the one source definition
private static final String TABLE_CREATE =
"CREATE TABLE IF NOT EXISTS " + DATABASE_TABLE + "(" +
KEY_ROWID + " INTEGER PRIMARY KEY, " + // AUTOINCREMENT NOT REQD
KEY_NAME + " DATE NOT NULL, " +
KEY_AMOUNT + " VARCHAR ," +
KEY_DUEDATE + " DATE " +
")";
private Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(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(TABLE_CREATE); // NO need to encapsulate in try clause
}
#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 contacts"); //????????
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
//---opens the database--- NOT NEEDED
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database--- NOT NEEDED
public void close()
{
DBHelper.close();
}
//---insert a record into the database---
public long insertRecord(String name, String amount, String duedate)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_AMOUNT, amount);
initialValues.put(KEY_DUEDATE, duedate);
return DBHelper.getWritableDatabase().insert(DATABASE_TABLE,
null,
initialValues
);
}
//---deletes a particular record---
public boolean deleteContact(long rowId)
{
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
//---retrieves all the records--- SEE FOLLOWING METHOD
public Cursor getAllRecords()
{SQLiteDatabase db = DBHelper.getWritableDatabase();
String query ="SELECT * FROM " + DATABASE_TABLE;
Cursor data = db.rawQuery(query,null);
return data;
}
//As per getAllRecords but using query convenience method
public Cursor getAllAsCursor() {
return DBHelper.getWritableDatabase().query(
DATABASE_TABLE,
null,null,null,null,null,null
);
}
public Cursor getItemID(String name) {
SQLiteDatabase db = DBHelper.getWritableDatabase();
String query = "SELECT " + KEY_ROWID + " FROM " + DATABASE_TABLE +
" WHERE " + KEY_NAME + " = '" + name + "'";
Cursor data = db.rawQuery(query, null);
return data;
}
// Retrieve a row (single) according to id
public Cursor getRecordById(long id) {
return DBHelper.getWritableDatabase().query(
DATABASE_TABLE,
null,
KEY_ROWID + "=?",
new String[]{String.valueOf(id)},
null,null,null
);
}
//---updates a record---
public boolean updateRecord(long rowId, String name, String amount, String duedate) {
ContentValues args = new ContentValues();
args.put(KEY_NAME, name);
args.put(KEY_AMOUNT, amount);
args.put(KEY_DUEDATE, duedate);
String whereclause = KEY_ROWID + "=?";
String[] whereargs = new String[]{String.valueOf(rowId)};
return DBHelper.getWritableDatabase().update(DATABASE_TABLE,
args,
whereclause,
whereargs
) > 0;
}
}
Basically as was except that upDateRecord has been un-commented, again as per the original answer.
Results
1st Run - MainActivity (Bills) :-
Long Click Bill2 (note changed from Click as Long Click is less prone to accidental use)
Change data (Update button not clicked)
Update Button Clicked (Toast was Updated.)
Note use of finish() to return to the invoking activity and then the use of onResume to refresh the list according to the updated data (possibly your next question).
using startActivity will simply result in issues.
Note Values are date and course rather then amount and duedate because I didn't change the values in the addSomeData method (easily done).
the actual data itself is irrelevant to the process.

My application crashes after I try to insert an Item into my database [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I can open my Datenbase but if I try to insert an item my application crashes.
Insert the item only to my ListView works.
I create a new Object in another Activity and take the Values in an Intent.
But when I start the intent and go back to the Main/List_page Activity my App crashes. Without the Database, the application runs.
Heres my codes: ReceptListAdapter.java:
public class ReceptListDatabase {
private static final String DATABASE_NAME = "receptlist.db";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_TABLE = "receptlistitems";
public static final String KEY_ID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_KATEGORY = "kategory";
public static final String KEY_INGREDIENTS = "ingredients";
public static final String KEY_DIRECTIONS = "ingredients";
public static final int COLUMN_NAME_INDEX = 1;
public static final int COLUMN_KATEGORY_INDEX = 2;
public static final int COLUMN_INGREDIENTS_INDEX = 3;
public static final int COLUMN_DIRECTIONS_INDEX = 4;
private ReceptDBOpenHelper dbHelper;
private SQLiteDatabase DB;
public ReceptListDatabase(Context context) {
dbHelper = new ReceptDBOpenHelper(context, DATABASE_NAME, null,
DATABASE_VERSION);
}
public void open() throws SQLException {
try {
db = dbHelper.getWritableDatabase();
} catch (SQLException e) {
db = dbHelper.getReadableDatabase();
}
}
public void close() {
db.close();
}
public long insertReceptItem(ListItem item) {
ContentValues itemValues = new ContentValues();
itemValues.put(KEY_NAME, item.getName());
itemValues.put(KEY_KATEGORY,item.getKategory());
itemValues.put(KEY_INGREDIENTS, item.getIngredients());
itemValues.put(KEY_DIRECTIONS, item.getDirection());
return db.insert(DATABASE_TABLE, null, itemValues);
}
public void removeReceptItem(ListItem item) {
String toDelete = KEY_NAME + "=?";
String[] deleteArguments = new String[]{item.getName()};
db.delete(DATABASE_TABLE, toDelete, deleteArguments);
}
public ArrayList<ListItem> getAllReceptItems() {
ArrayList<ListItem> items = new ArrayList<ListItem>();
Cursor cursor = db.query(DATABASE_TABLE, new String[] { KEY_ID,
KEY_NAME, KEY_KATEGORY, KEY_INGREDIENTS, KEY_DIRECTIONS, null}, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
String name = cursor.getString(COLUMN_NAME_INDEX);
String kategory = cursor.getString(COLUMN_KATEGORY_INDEX);
String ingredients = cursor.getString(COLUMN_INGREDIENTS_INDEX);
String directions = cursor.getString(COLUMN_DIRECTIONS_INDEX);
items.add(new ListItem(name, kategory, ingredients, directions, null));
} while (cursor.moveToNext());
}
return items;
}
private class ReceptDBOpenHelper extends SQLiteOpenHelper {
private static final String DATABASE_CREATE = "create table "
+ DATABASE_TABLE + " (" + KEY_ID
+ " integer primary key autoincrement, " + KEY_NAME
+ " text not null, " + KEY_KATEGORY
+ " text, " + KEY_INGREDIENTS
+ " text not null, " + KEY_DIRECTIONS
+ " text not null);";
public ReceptDBOpenHelper(Context c, String dbname,
SQLiteDatabase.CursorFactory factory, int version) {
super(c, dbname, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
And my Main Activity:
public class List_Page extends Activity {
private ListViewAdapter adapter;
private ArrayList<ListItem> itemList;
private ListView list;
private DatabaseAdapter receptDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
setupButton();
setupListView();
addObject();
setupDatabase();
}
private void setupDatabase() {
receptDB = new DatabaseAdapter(this);
receptDB.open();
}
private void setupButton() {
Button addItemButton = (Button) findViewById(R.id.addItemButton);
addItemButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
buttonClicked();
}
});
}
private void buttonClicked() {
//get EditText
Intent newItemIntent = new Intent(List_Page.this, Add_Object.class);
startActivity(newItemIntent);
finish();
}
private void setupListView() {
itemList = new ArrayList<ListItem>();
adapter = new ListViewAdapter(List_Page.this, itemList);
list = (ListView) findViewById(R.id.listItem);
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
//fehler bei removeTaskAtPosition(position);
return true;
}
});
View header = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.activity_list_item, null);
list.addHeaderView(header);
list.setAdapter(adapter);
}
private void addObject(){
Intent intent = getIntent();
if (intent.hasExtra(Constants.KEY_RECEPT_NAME)) {
String name = intent.getExtras().getString(Constants.KEY_RECEPT_NAME);
String kategory = intent.getExtras().getString(Constants.KEY_KATEGORY);
String ingredients = intent.getExtras().getString(Constants.KEY_INGREDIENTS);
String directions = intent.getExtras().getString(Constants.KEY_DIRECTIONS);
Bitmap image = (Bitmap) intent.getParcelableExtra(Constants.KEY_IMAGE);
ListItem newObject = new ListItem(name,kategory,ingredients,directions, image);
itemList.add(newObject);
receptDB.insertReceptItem(newObject);
//refreshArrayList();
}
}
private void refreshArrayList() {
ArrayList tempList = receptDB.getAllReceptItems();
itemList.clear();
itemList.addAll(tempList);
adapter.notifyDataSetChanged();
}
private void removeTaskAtPosition(int position) {
if (itemList.get(position) != null) {
receptDB.removeReceptItem(itemList.get(position));
refreshArrayList();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onDestroy() {
super.onDestroy();
receptDB.close();
}
}
Logcat:
08-12 15:37:00.743 22879-22879/de.ur.mi.android.excercises.starter E/AndroidRuntime: FATAL EXCEPTION: main
Process: de.ur.mi.android.excercises.starter, PID: 22879
java.lang.RuntimeException: Unable to start activity ComponentInfo{de.ur.mi.android.excercises.starter/de.ur.mi.android.excercises.starter.List_Page}: java.lang.NullPointerException: Attempt to invoke virtual method 'long de.ur.mi.android.excercises.starter.DatabaseAdapter.insertReceptItem(de.ur.mi.android.excercises.starter.domain.ListItem)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2720)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2781)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1508)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:241)
at android.app.ActivityThread.main(ActivityThread.java:6274)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'long de.ur.mi.android.excercises.starter.DatabaseAdapter.insertReceptItem(de.ur.mi.android.excercises.starter.domain.ListItem)' on a null object reference
at de.ur.mi.android.excercises.starter.List_Page.addObject(List_Page.java:99)
at de.ur.mi.android.excercises.starter.List_Page.onCreate(List_Page.java:40)
at android.app.Activity.performCreate(Activity.java:6720)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2673)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2781) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1508) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:241) 
at android.app.ActivityThread.main(ActivityThread.java:6274) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 
In your Activity's onCreate you are calling addObject() before calling setupDatabase(). Only inside setupDatabase() you are initialising receptDB instance.
But you are accessing that receptDb inside addObject() method.
receptDB.insertReceptItem(newObject);
So during that time, your receptDB has null reference and so you are getting NullPointerException.
So swap the below two lines from,
addObject();
setupDatabase();
to this:
setupDatabase();
addObject();

how to get data from android database into an arraylist

I'm very new at android programming and this is my first question on stack overflow ever. I am having trouble understanding where i have gone wrong in my code implementation. I'm trying to store data in a database and then extract it into an arraylist.
This is the class where i add data into the database in the button onclicklistener:
public class KarmaDescription extends AppCompatActivity {
Button button;
TasksDBHandler dbHandler;
int tId = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_karma_desc2min);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Overview");
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MyTasksGS myTask = new MyTasksGS(tId, "New Task Title", 2);
dbHandler.addTask(myTask);
Toast.makeText(KarmaDescription.this, "Task Added", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
}
This is the class which manages the database:
public class TasksDBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "tasks.db";
public static final String TABLE_TASKS = "tasks";
public static final String COLUMN_ID = "id";
public static final String COLUMN_TASKNAME = "taskname";
public static final String COLUMN_DAYSLEFT = "daysleft";
public TasksDBHandler(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_TASKS + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY," +
COLUMN_TASKNAME + " TEXT," +
COLUMN_DAYSLEFT + " INTEGER" +
")";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TASKS);
onCreate(db);
}
//Add a new row to the database
public void addTask(MyTasksGS myTask) {
ContentValues values = new ContentValues();
values.put(COLUMN_ID, myTask.getId());
values.put(COLUMN_TASKNAME, myTask.getTitle());
values.put(COLUMN_DAYSLEFT, myTask.getDaysRemaining());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_TASKS, null, values);
db.close();
}
//Delete row from the database
public void deleteTask(String taskID) {
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_TASKS + " WHERE " + COLUMN_ID + "=\"" + taskID + "\";");
}
//To put data into an arraylist
public List<MyTasksGS> getDataFromDB()
{
int id, daysRemaining;
String title;
List<MyTasksGS> tasksList = new ArrayList<MyTasksGS>();
String query = "SELECT * FROM " + TABLE_TASKS;
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
cursor.moveToFirst();
while (cursor.moveToNext())
{
id = cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_ID));
title = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_TASKNAME));
daysRemaining = cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_DAYSLEFT));
MyTasksGS myTask = new MyTasksGS(id, title, daysRemaining);
tasksList.add(myTask);
}
return tasksList;
}
}
I'm trying to copy the arraylist data which is returned from the above class(using getDataFromDB function) into myTaskList here and im getting this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List com.example.prateek.karma.TasksDBHandler.getDataFromDB()' on a null object reference
public class MyTasksFragment extends Fragment {
Button taskComplete;
RecyclerView RVMyTasks;
static MyTasksAdapter mtAdapter;
List<MyTasksGS> myTaskList = new ArrayList<>();
TasksDBHandler dbHandler;
public MyTasksFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_my_tasks, container, false);
taskComplete = (Button) view.findViewById(R.id.taskComplete);
RVMyTasks = (RecyclerView) view.findViewById(R.id.RVMyTasks);
mtAdapter = new MyTasksAdapter(myTaskList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext());
RVMyTasks.setLayoutManager(mLayoutManager);
RVMyTasks.setItemAnimator(new DefaultItemAnimator());
RVMyTasks.setAdapter(mtAdapter);
myTaskList = dbHandler.getDataFromDB();
mtAdapter.notifyDataSetChanged();
return view;
}
}
And this is the MyTasksGS class:
public class MyTasksGS {
String title;
int daysRemaining;
int id;
public MyTasksGS() {
}
public MyTasksGS(int id, String title, int daysRemaining) {
this.title = title;
this.daysRemaining = daysRemaining;
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getDaysRemaining() {
return daysRemaining;
}
public void setDaysRemaining(int daysRemaining) {
this.daysRemaining = daysRemaining;
}
}
I may have made a very silly mistake somewhere but im not able to find it. Any help is appreciated
You need to instantiate the dbHandler, you are trying to use it without a valid instance. It causes the NullPointerException.
In your on onCreateView
before myTaskList = dbHandler.getDataFromDB();
add : dbHandler = new TasksDBHandler(getActivity());
use your class property DATABASE_NAME and DATABASE_VERSION instead of pass in constructor.
Change your TaskDBHandler constructor like this
public TasksDBHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

Android: Listview item not deleting. Id not being retrieved

I am currently trying to add a deleting ability to a ListView onItemLongClick. Unfortunately, for some reason I cannot seem to do this. Whenever I long click, the dialog box appears correctly and when I press yes to delete, nothing at all happens. The item still remains in the Listview and in the database because I call the method to display all the items from the updated database right after I call my delete method. I have been trying to fix this problem for two days now and I have gotten nowhere. It seems as though it is unable to retrieve an Id from the database for each item, but I am not sure why it would be doing this.
Here is my habit object class:
public class Habit extends Object implements Serializable{
private int day_count;
private int _id;
private String habit_name, date_started, end_date, day_count_string, id_string;
public Habit(){
}
public Habit(int id, String name, String startDate, String endDate, int dayCount){
this._id = id;
this.habit_name = name;
this.date_started = startDate;
this.end_date = endDate;
this.day_count = dayCount;
}
public Habit(String name, String startDate, String endDate, int dayCount){
this.habit_name = name;
this.date_started = startDate;
this.end_date = endDate;
this.day_count = dayCount;
}
public int getID()
{
return _id;
}
public int setID(int id)
{
return this._id;
}
public String getIDString()
{
id_string = "" + this._id;
return id_string;
}
public int getDayCount()
{
return this.day_count;
}
public String getDayCountString()
{
day_count_string = "" + this.day_count;
return day_count_string;
}
public int setDayCount(int dayCount)
{
return this.day_count;
}
public String getName()
{
return this.habit_name;
}
public void setName(String name)
{
this.habit_name = name;
}
public String getStartDate()
{
return this.date_started;
}
public void setStartDate(String startDate)
{
this.date_started = startDate;
}
public String getEndDate()
{
return this.end_date;
}
public void setEndDate(String endDate)
{
this.end_date = endDate;
}
}
Here is my databaseHelper code where I call add habit to create one habit item in the database and I call deleteHabit to delete the habit at the location of the id that is in the habit object class:
public class HabitDbHelper extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME="habits";
public static final String TABLE_HABITS = "habit_names";
public static final String KEY_NAME = "hname";
public static final String KEY_ID = "id";
public static final String KEY_STARTDATE = "start_date";
public static final String KEY_ENDDATE = "end_date";
public static final String KEY_DAYCOUNT = "day_count";
public HabitDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE "+TABLE_HABITS+" ("
+KEY_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "
+KEY_NAME+" TEXT, "
+KEY_STARTDATE+" TEXT, "
+KEY_ENDDATE+" TEXT, "
+KEY_DAYCOUNT+" INTEGER);");
}
// Upgrading Database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_HABITS);
onCreate(db);
}
//Adding new habit
public void addHabit(Habit habit) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, habit.getName()); // Habit Name
values.put(KEY_STARTDATE, habit.getStartDate()); // Start Date
values.put(KEY_ENDDATE, habit.getEndDate()); // End Date
values.put(KEY_DAYCOUNT, habit.getDayCount());
// Inserting Row
db.insert(TABLE_HABITS, null, values);
db.close(); // Closing database connection
}
// Fetching 1 Habit
public Habit getHabit(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_HABITS, new String[] { KEY_ID,
KEY_NAME, KEY_STARTDATE ,KEY_ENDDATE, KEY_DAYCOUNT }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Habit habit = new Habit(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), Integer.parseInt(cursor.getString(4)));
// return contact
return habit;
}
// Fetching all Habits
public ArrayList<Habit> getAllHabits() {
ArrayList<Habit> habitList = new ArrayList<Habit>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_HABITS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Habit habit = new Habit();
habit.setID(Integer.parseInt(cursor.getString(cursor.getColumnIndex(KEY_ID))));
habit.setName(cursor.getString(cursor.getColumnIndex(KEY_NAME)));
habit.setStartDate(cursor.getString(cursor.getColumnIndex(KEY_STARTDATE)));
habit.setEndDate(cursor.getString(cursor.getColumnIndex(KEY_ENDDATE)));
habit.setDayCount(Integer.parseInt(cursor.getString(cursor.getColumnIndex(KEY_DAYCOUNT))));
// Adding contact to list
habitList.add(habit);
} while (cursor.moveToNext());
}
return habitList;
}
// Deleting Single Habit
public void deleteHabit(Habit habit) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_HABITS, KEY_ID + " = ?",
new String[] { String.valueOf(habit.getID()) });
db.close();
}
}
Here is my Listview adapter where each item is put into a custom item layout:
public class HabitAdapter extends BaseAdapter {
private ArrayList<Habit> habits;
private Context context;
private int layoutId;
private long id1;
public HabitAdapter(Context c, int LayoutId,ArrayList<Habit> habits) {
this.context = c;
this.layoutId = LayoutId;
this.habits = habits;
}
#Override
public int getCount() {
return habits.size();
}
#Override
public Habit getItem(int position) {
return habits.get(position);
}
#Override
public long getItemId(int position) {
Habit habit = (Habit)habits.get(position);
id1 = Long.parseLong(habit.getIDString());
return id1;
}
public View getView(int pos, View child, ViewGroup parent) {
Holder mHolder;
LayoutInflater layoutInflater;
Habit habit = habits.get(pos);
if (child == null) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.fragment_start_habit_item, null);
mHolder = new Holder();
mHolder.title = (TextView)child.findViewById(R.id.fragment_title);
mHolder.dayCount = (TextView)child.findViewById(R.id.fragment_days_left);
mHolder.startDate = (TextView)child.findViewById(R.id.fragment_start_date);
child.setTag(mHolder);
} else {
mHolder = (Holder) child.getTag();
}
mHolder.title.setText(habit.getName());
mHolder.dayCount.setText("Days Completed: " + habit.getDayCountString());
mHolder.startDate.setText("Date Started: " + habit.getStartDate());
return child;
}
public class Holder {
TextView title;
TextView dayCount;
TextView startDate;
}
}
And finally, my main activity where I delete the item that is selected onItemLongClick:
public class fourtyMain extends Activity
{
private HabitDbHelper mDB;
private ListView mList;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fourty_main);
mList = (ListView)findViewById(R.id.habit_list);
mDB = new HabitDbHelper(this);
getActionBar().setDisplayShowTitleEnabled(false);
//Start new activity with click
mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long arg3)
{
Intent singleI = new Intent(fourtyMain.this, SingleHabitView.class);
final Habit habit = (Habit) parent.getAdapter().getItem(position);
singleI.putExtra("habit", habit);
startActivity(singleI);
}
});
//long click to delete data
mList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, final View view, int position, long id) {
final Habit habit = (Habit) parent.getAdapter().getItem(position);
deleteHabitInListView(habit);
return true;
}
private void deleteHabitInListView(final Habit habit){
Builder deleteDialog = new AlertDialog.Builder(fourtyMain.this);
deleteDialog.setTitle("Delete " + habit.getName() + "?");
deleteDialog.setMessage("Are you sure you want to delete this habit? All your progress will be lost!");
deleteDialog.setPositiveButton("Yes", new AlertDialog.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mDB.deleteHabit(habit);
displayData();
}
});
deleteDialog.setNegativeButton("No", new AlertDialog.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
deleteDialog.show();
}
});
}
//Populate Listview
#Override
protected void onResume() {
displayData();
super.onResume();
}
private void displayData()
{
ArrayList<Habit> habitList = mDB.getAllHabits();
HabitAdapter disadpt = new HabitAdapter(fourtyMain.this, R.layout.fragment_start_habit_item, habitList);
mList.setAdapter(disadpt);
disadpt.notifyDataSetChanged();
}
}
I am absolutely lost on this one. I have been working for two days now to try and fix this problem and I have gotten nowhere. If I had to guess, I think I am going wrong on either retrieving the ID from the database or storing it incorrectly.
EDIT:
To add to this, I just found a way to write the id to a toast whenever the item is clicked. No matter what item in the list, it is returning 0 for the id. This makes me think that I am either fetching the id incorrectly or storing it incorrectly and my delete function is correct.
Insted of handling listview's setOnItemLongClickListener method, handl the perticuler cell's setOnItemLongClickListener
just like bleow :
public View getView(int pos, View child, ViewGroup parent) {
Holder mHolder;
LayoutInflater layoutInflater;
Habit habit = habits.get(pos);
if (child == null) {
layoutInflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.fragment_start_habit_item, null);
mHolder = new Holder();
mHolder.llCellLayout = (LinearLayout)child.findViewById(R.id.llCellLayout);
mHolder.title = (TextView)child.findViewById(R.id.fragment_title);
mHolder.dayCount = (TextView)child.findViewById(R.id.fragment_days_left);
mHolder.startDate = (TextView)child.findViewById(R.id.fragment_start_date);
child.setTag(mHolder);
} else {
mHolder = (Holder) child.getTag();
}
mHolder.title.setText(habit.getName());
mHolder.dayCount.setText("Days Completed: " + habit.getDayCountString());
mHolder.startDate.setText("Date Started: " + habit.getStartDate());
mHolder.llCellLayout.setOnItemLongClickListener(new OnItemLongClickListener(){
//** you can get id here and write code here for delete**
});
return child;
}
public class Holder {
TextView title;
TextView dayCount;
TextView startDate;
LinearLayout llCellLayout; //** this is the layout of cell**
}
try this code for delete operation
public float delete(String table,String colmName,String data) {
// TODO Auto-generated method stub
SQLiteDatabase db=dbhlpr.getWritableDatabase();
String[] arr={data};
colmName=colmName+"=?";
float res=db.delete(table, colmName,arr );
db.close();
return res;
}
Try to delete like below,
// Deleting Single Habit
public void deleteHabit(Habit habit) {
SQLiteDatabase database = this.getWritableDatabase();
{
database.execSQL("delete from " + "TABLE_HABITS"
+ " where KEY_ID='" + String.valueOf(habit.getID())+ "'");
}
database .close();
}
you could try the following:
1.Either change the query to a raw query like this:
public void deleteHabit(Habit habit) {
SQLiteDatabase db = this.getWritableDatabase();
String sql = "delete from " + TABLE_HABITS + " where "
+ KEY_ID + "=" + habit.getID();
db.rawQuery(sql,null);
db.close();
}
2.Or you could also try this:
public void deleteHabit(Habit habit) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_HABITS, KEY_ID+ "=" + habit.getID(), null);
db.close();
}
Hope that helps!
I managed to figure it out and of course it was the simplest error possible. In my habit object class I had it written:
public int setID(int id)
{
return this._id;
}
When all I needed to do was change it to this:
public void setID(int id)
{
this._id = id;
}
Stupid rookie mistake on my part but luckily thanks to trial and error by everybody I finally figured out my screw up. Thanks to anybody that helped out!

close() was not explicity called on database

I need to know where to call the db.close() in my code. I've added it on onCreate() method, but when I need to use some methods it says database not open, and then I've removed from onCreate() and it says close() was not explicity called. so where should I close, could it be inside each method of the class??
here is the code:
public class HoursPerDayDataHelper {
private static final String DATABASE_NAME = "database.db";
private static final int DATABASE_VERSION = 1;
protected static final String TABLE_NAME = "table";
protected String TAG = "HoursPerDayDataHelper";
private Context context;
private SQLiteDatabase db;
OpenHelper openHelper = null;
public HoursPerDayDataHelper(Context context) {
this.context = context;
openHelper = new OpenHelper(this.context);
this.db = openHelper.getWritableDatabase();
openHelper.onCreate(db);
}
public void close() {
if (openHelper != null) {
openHelper.close();
}
}
public void deleteAll() {
this.db.delete(TABLE_NAME, null, null);
}
public String selectDuration(String date) {
String duration = "";
Integer value = 0;
String returnment = "";
Log.i(TAG, "date do select: " + date);
Cursor cursor = this.db.query(TABLE_NAME, new String[] { "duration" },
"date = ? ", new String[]{ date }, null, null, null);
Log.i(TAG, "cursor string " + cursor);
if (cursor.moveToFirst()) {
do {
Log.i(TAG, "dentro do if cursor");
duration = cursor.getString(0);
value += Integer.parseInt(duration);
} while (cursor.moveToNext());
returnment = Integer.toString(value);
}else{
Log.i(TAG, "bla bla bla");
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return returnment;
}
public ArrayList<String[]> selectTopContacts() {
ArrayList<String[]> list1 = new ArrayList<String[]>();
Cursor cursor = this.db.query(TABLE_NAME, null, null, null, null, null,
"duration desc");
if (cursor.moveToFirst()) {
do {
if (cursor.getString(2) != "") {
String[] data = new String[4];
data[0] = cursor.getString(2);
data[1] = cursor.getString(4);
data[2] = cursor.getString(5);
data[3] = cursor.getString(7);
list1.add(data);
} else {
String[] data = new String[3];
data[1] = cursor.getString(4);
data[2] = cursor.getString(5);
data[3] = cursor.getString(7);
list1.add(data);
}
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return list1;
}
public static class OpenHelper extends SQLiteOpenHelper {
OpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS "
+ TABLE_NAME
+ "(id INTEGER PRIMARY KEY AUTOINCREMENT, duration TIME, date DATE, current_time TIME)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("HoursPerDay Database",
"Upgrading database, this will drop tables and recreate.");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
}
And this is my Activity:
public class HoursPerDay extends Activity{
private String LOG_TAG = "HoursPerDay";
private TextView mDateDisplay;
public String date;
private int mYear;
private int mMonth;
private int mDay;
private int newDay;
private String hpdData;
private HoursPerDayDataHelper hpd;
OpenHelper openHelper = new OpenHelper(HoursPerDay.this);
static final int DATE_DIALOG_ID = 0;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hours_per_day);
hpd = new HoursPerDayDataHelper(this);
// capture our View elements
mDateDisplay = (TextView) findViewById(R.id.dateDisplay);
// get the current date
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
// display the current date (this method is below)
}
#Override
protected void onDestroy() {
super.onDestroy();
if (openHelper != null) {
openHelper.close();
}
if (hpd != null) {
hpd.close();
}
}
// the callback received when the user "sets" the date in the dialog
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
setBasicContent();
hpd.close();
}
};
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this,
mDateSetListener,
mYear, mMonth, mDay);
}
return null;
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.layout.hoursperdaymenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.filter_by_day:
showDialog(DATE_DIALOG_ID);
return true;
case R.id.filter_by_user:
showDialog(DATE_DIALOG_ID);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void setBasicContent() {
date = (mMonth + 1) + "/" + newDay + "/" + mYear;
hpdData = this.hpd.selectDuration(date);
mDateDisplay.setText(hpdData);
hpd.close();
}
}
I think there are 2 ways:
in onPause-method and check there isFinishing if yes -> close. Problem: if your app gets killed by app-killer, db remains open.
You open and close the DB each time (methods) you read/write.
EDIT:
Ok, I see why it could be caused. I think you misunderstood the usage of the SQLiteOpenHelper. You never have to call the onCreate-method.
Defently the better way is to make a DBHelper class and use it in a separate calls, lets say SQLDataHandler.
Your activity look good. I changed a few things, look if it helps. I'll mark them:
That's all what should be in the Helper class:
public static class OpenHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "database.db";
private static final int DATABASE_VERSION = 1;
protected static final String TABLE_NAME = "table";
protected String TAG = "HoursPerDayDataHelper";
Just leave it CREATE TABLE it gets only created/called if there isn't one existing.
I have seen errors occurring if the String is passed directly
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE "
+ TABLE_NAME
+ "(id INTEGER PRIMARY KEY AUTOINCREMENT, duration TIME, date DATE, current_time TIME)";
db.execSQL(query);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
OpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
}
To use it:
Just call in your DataHandler class :
OpenHelper helper = new OpenHelper(ctx);
// SQLiteDatabase db = helper.getReadableDatabase();
SQLiteDatabase db = helper.getWritableDatabase();
All other stuff, like deleting, adding and so on, should be done in a "DataHandler" class.
Just use the same two methods there to get your DB. At the end, when you are finished, you call just in you DataHandler class db.close().
Like this the activity itself never uses de DB directly. Better practice I think ;)
I hope it helps. For any other questions, just ask :)
EDIT2:
First, in general it should work with a inner class.
BUT: In case you want to add another table from another class it won't work anymore. Thats why it's the better way to put it in a separate class from beginning. It's even reusable (with some smal adjustments).
Put the code I posted in your class OpenHelper. Nothing more.
Then, put the data manipulation stuff in a class called something like: DataHandlerDB.
Code example:
package ...;
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;
public class DataHandlerDB {
public static void persistAll(Context ctx, List<Module> moduleList) {
DatabaseHelper helper = new DatabaseHelper(ctx);
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
for (Module m : moduleList) {
values.put("_id", m.get_id());
values.put("name", m.getModule());
db.insert("module", null, values);
}
db.close();
}
public static List<Module> findAll(Context ctx) {
List<Module> result = new ArrayList<Module>();
DatabaseHelper helper = new DatabaseHelper(ctx);
SQLiteDatabase db = helper.getReadableDatabase();
Cursor c = db.query(ModuleDB.TABLE_NAME, new String[] { ModuleDB.ID,
ModuleDB.MODULE}, null, null, null, null, null);
while (c.moveToNext()) {
Module m = new Module(c.getInt(0), c.getString(1));
result.add(m);
}
c.close();
db.close();
return result;
}
// Update Database entry
public static void update(Context ctx, Module m) {
DatabaseHelper helper = new DatabaseHelper(ctx);
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("_id", m.get_id());
values.put("name", m.getModule());
db.update("module", values, null, null);
db.close();
}
public static void delete(Context ctx, Module m) {
DatabaseHelper helper = new DatabaseHelper(ctx);
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("_id", m.get_id());
values.put("name", m.getModule());
db.delete("module","_id = m.get_id()", null);
db.close();
}
public static void createDB(Context ctx) {
DatabaseHelper helper = new DatabaseHelper(ctx);
SQLiteDatabase db = helper.getWritableDatabase();
db.close();
}
}
In order to be more efficient the methods are static, you won't need to create objects.
Use it like this: In your activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// get the a writable DB, in case it's not existing it gets created.
DataHandlerDB.createDB(this);
// get stuff out of DB
moduleList = DataHandlerDB.findAll(this);
adapter = new ArrayAdapter<Module>(this,
android.R.layout.simple_list_item_1, moduleList);
setListAdapter(adapter);
}
if you open in onCreate, then close in onDestroy

Categories