Community I m new in android so to just implement the concept of sqlity from udacity as guided,I built a small app...as show below code with category activity(main) EVEN I CALLED getReadeableDatabase() on open helper class in onCreate of main activity(catalog),clear data,uninstalled app,no solution found?
public class CatalogActivity extends AppCompatActivity {
sqlitedbhelper sqdb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_catalog);
// Setup FAB to open EditorActivity
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(CatalogActivity.this, EditorActivity.class);
startActivity(intent);
}
});
sqdb = new sqlitedbhelper(this);
Log.v("my tag", "0");
displaydata();
}
public void displaydata() {
SQLiteDatabase mdb = sqdb.getReadableDatabase();
String[] projection = {
PetContract.petdata.col_id,
PetContract.petdata.col_name,
PetContract.petdata.col_breed,
PetContract.petdata.col_sex,
PetContract.petdata.col_weight};
// Perform a query on the pets table
Cursor cursor = mdb.query(
PetContract.petdata.pet_table, // The table to query
projection, // The columns to return
null, // The columns for the WHERE clause
null, // The values for the WHERE clause
null, // Don't group the rows
null, // Don't filter by row groups
null); // The sort order
TextView txt = (TextView) findViewById(R.id.text_view_pet);
try {
txt.setText("no of columns:");
txt.append(String.valueOf(cursor.getCount()));
} finally {
cursor.close();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu options from the res/menu/menu_catalog.xml file.
// This adds menu items to the app bar.
getMenuInflater().inflate(R.menu.menu_catalog, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// User clicked on a menu option in the app bar overflow menu
switch (item.getItemId()) {
// Respond to a click on the "Insert dummy data" menu option
case R.id.action_insert_dummy_data:
// Do nothing for now
return true;
// Respond to a click on the "Delete all entries" menu option
case R.id.action_delete_all_entries:
// Do nothing for now
return true;
}
return super.onOptionsItemSelected(item);
}
}
Below is the contract class
public final class PetContract {
private PetContract() {}
public static final class petdata implements BaseColumns{
public static final String pet_table="pet";
public static final String col_name="name";
public static final String col_weight="weight";
public static final String col_breed="breed";
public static final String col_id=BaseColumns._ID;
public static final String col_sex="sex";
//constants starts here
public static final int sex_male=1;
public static final int sex_female=2;
public static final int sex_unknown=0;
}
}
And finally the sqlitedbhelper class
public class sqlitedbhelper extends SQLiteOpenHelper {
public static final int database_ver=1;
public static final String database_nAME="shelter";
public sqlitedbhelper(Context context) {
super(context, database_nAME, null, database_ver);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.v("my tag","in on create db helper");
String SQL_CREATE_PETS_TABLE = "CREATE TABLE " + petdata.pet_table + " ("
+ petdata.col_id + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ petdata.col_name + " TEXT NOT NULL, "
+ petdata.col_breed + " TEXT, "
+ petdata.col_sex + " INTEGER NOT NULL, "
+ petdata.col_weight + " INTEGER NOT NULL DEFAULT 0);";
Log.v("my tag"," b4 passed sql create db helper");
db.execSQL(SQL_CREATE_PETS_TABLE);
Log.v("my tag","passed sql create db helper");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}
Now the problem is when I run it database named shelter is created but no table is created.
You have to mention this at your CatalogActivity inside onCreat method
sqdb = new sqlitedbhelper (this);
This will help you..
Related
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
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();
Here is my MainActivity.java
public class MainActivity extends AppCompatActivity{
CountriesDbAdapter myDB = new CountriesDbAdapter(this);
ListView listView;
public String lat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDB.open();
myDB.deleteBank();
myDB.insertBank();
listView = (ListView) findViewById(R.id.listView);
toggleView();
WebView webView = (WebView) this.findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new WebViewJavaScriptInterface(this), "android");
webView.requestFocusFromTouch();
webView.setWebViewClient(new WebViewClient());
webView.setWebChromeClient(new WebChromeClient());
webView.loadUrl("file:///android_asset/www/bank.html");
}
public void toggleView() {
final Cursor cursor = myDB.fetchBank();
final String[] arr = new String[cursor.getCount()];
int i = 0;
if (cursor.moveToFirst()) {
do {
String data = cursor.getString(cursor.getColumnIndex("banks"));
arr[i] = data;
i++;
} while (cursor.moveToNext());
}
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, arr);
listView.setAdapter(adapter);
final StringBuffer buffer = new StringBuffer();
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Toast.makeText(MainActivity.this, arr[position], Toast.LENGTH_SHORT).show();
Cursor res = myDB.answerRequest(arr[position]);
if (res.moveToFirst()) {
do {
lat=res.getString(2);
//buffer.append("lat: " + lat + "\n");
// buffer.append("long: " + res.getString(3) + "\n\n");
// showMessage("Data", buffer.toString());
//showMessage();
} while (res.moveToNext());
}
}
});
}
class WebViewJavaScriptInterface {
private Activity activity;
public WebViewJavaScriptInterface(Activity activity) {
this.activity = activity;
}
#JavascriptInterface
public String getData() {
//From Here how can i Return my Updated latitude to javascript file
}
}
CountriesDbAdapter.java
package com.example.student.finalone;
public class CountriesDbAdapter {
public static final String COLUMN_BANK = "banks";
public static final String COLUMN_BANKL = "banksl";
public static final String COLUMN_BANKLG = "bankslg";
private static final String TAG = "CountriesDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
public static final String KEY_ROWID = "id";
private static final String DATABASE_NAME = "Vijayawada";
private static final String BANK_TABLE = "Bank";
private static final int DATABASE_VERSION = 1;
private final Context mCtx;
private static final String DATABASE_BANK = "CREATE TABLE if not exists " + BANK_TABLE + " (" + KEY_ROWID + " integer PRIMARY KEY autoincrement," + COLUMN_BANK + "," + COLUMN_BANKL + "," + COLUMN_BANKLG + ");";
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.w(TAG, DATABASE_BANK);
db.execSQL(DATABASE_BANK);
}
#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 " + BANK_TABLE);
}
}
public CountriesDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public CountriesDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public long createBank(String b, double blat,double blong) {
ContentValues initialValues = new ContentValues();initialValues.put(COLUMN_BANK, b);initialValues.put(COLUMN_BANKL, blat);initialValues.put(COLUMN_BANKLG, blong);
return mDb.insert(BANK_TABLE, null, initialValues);
}
public boolean deleteBank() {
int doneDelete = 0;
doneDelete = mDb.delete(BANK_TABLE, null , null);
Log.w(TAG, Integer.toString(doneDelete));
return doneDelete > 0;
}
public void insertBank()
{
createBank("ServicebranchSBI",16.5109,80.651);createBank("StateBankofIndia",16.5011,80.6559);createBank("StateBankOfHyderabad",16.4966,80.6569);
createBank("BankOfBaroda",16.4974,80.6546);createBank("AndhraBank",16.5028,80.6396);createBank("AndhraBank",16.5062,80.648);
}
public Cursor fetchBank() {
String SelectQuery="select * from "+BANK_TABLE;
Cursor mCursor = mDb.rawQuery(SelectQuery,null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor answerRequest(String position) {
String SelectQuery= "SELECT * FROM " + BANK_TABLE + " WHERE " + COLUMN_BANK + "='" + position + "'";
Cursor mCursor = mDb.rawQuery(SelectQuery,null);
// String result="";
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
}
index.html
<html>
<head>
<script>
var showData = function() {
var data = android.getData();
window.alert("Hello! Data are: " + data + "; first = " + data);
}
</script>
</head>
<body>
<p>Lorem ipsem dolor et ceteris.</p>
<input type="button" value="Display data" onclick="showData()">
</body>
</html>
Iam trying to access the database from MainActivity.java and push it to the html file, Whenever i click on the html button it shows 0's in some cases iam getting error near the double lat declaration
You can achieve it in two ways:
1. Implement the Activity from OnItemClickListener and override onItemClick parallel to onCreate. Define double array a class variable and update that inside onItemClick
public class MainActivity extends Activity implements OnItemClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Your code here
}
}
2.Create a class MyItemClickListener and implement it from OnItemClickListener. Define double array a class variable
class MyItemClickListener implements OnItemClickListener
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Your code here
//Update the class member a1dToJson(lat).toString();//Here it returns all 0's
}
}
Change setOnItemClickListener to:
listView.setOnItemClickListener(new MyItemClickListener());
Thanks in advance for helping me out. This is my first time working on SQLite Database as well as creating an app.
Problem: When I click save"ImageButton" on the AddEntry.xml for some reason its not displaying on my listview which is located in my Fragment Home.xml. I found fragments to be a tad difficult since you have to change the code around in order for it to work. so please excuse if my code is all over the place.
AddEntry.java
public class AddEntry extends Fragment implements View.OnClickListener
{
EditText DescriptionET,CalorieET;
ImageButton Savebtn, Cancelbtn;
String description , calorieAmt;
CalorieDatabase calorieDB;
public AddEntry() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View myView = inflater.inflate(R.layout.fragment_add_entry,
container, false);
Savebtn = (ImageButton) myView.findViewById(R.id.SaveBtn);
Savebtn.setOnClickListener(this);
Cancelbtn = (ImageButton) myView.findViewById(R.id.CancelBtn);
Cancelbtn.setOnClickListener(this);
return myView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
DescriptionET= (EditText)view.findViewById(R.id.foodEditText);
CalorieET=(EditText)view.findViewById(R.id.caloriesEditText);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.SaveBtn:
description = DescriptionET.getText().toString();
calorieAmt=CalorieET.getText().toString();
((appMain) getActivity()).loadSelection(0);
break;
case R.id.CancelBtn:
EditText descriptionET=
(EditText)getView().findViewById(R.id.foodEditText);
descriptionET.setText("");
EditText calorieET=
(EditText)getView().findViewById(R.id.caloriesEditText);
calorieET.setText("");
break;
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
}
FragmentHome.java
public class FragmentHome extends Fragment implements
View.OnClickListener {
public static final String ARG_SECTION_NUMBER =
"section_number";
public static final String ARG_ID = "_id";
private TextView label;
private int sectionNumber = 0;
private Calendar fragmentDate;
ListView listview;
ImageButton AddEntrybtn;
CalorieDatabase calorieDB;
private View v;
private android.support.v4.app.FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;
public FragmentHome() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container,
Bundle savedInstanceState) {
View myView = inflater.inflate(R.layout.fragment_home,
container, false);
label= (TextView) myView.findViewById(R.id.section_label);
AddEntrybtn = (ImageButton) myView.findViewById(R.id.AddItems);
AddEntrybtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
((appMain)getActivity()).loadSelection(1);
}
});
return myView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle username = getActivity().getIntent().getExtras();
String username1 = username.getString("Username");
TextView userMain= (TextView)
getView().findViewById(R.id.User);
userMain.setText(username1);
openDataBase();
}
private void openDataBase (){
calorieDB= new CalorieDatabase(getActivity());
calorieDB.open();
}
private void closeDataBase(){
calorieDB.close();
};
private void populateLVFromDB(){
Cursor cursor = calorieDB.getAllRows();
String[] fromFieldNames = new String[]
{CalorieDatabase.KEY_NAME, CalorieDatabase.KEY_CalorieValue};
int[] toViewIDs = new int[]
{R.id.foodEditText, R.id.caloriesEditText, };
SimpleCursorAdapter myCursorAdapter =
new SimpleCursorAdapter(
getActivity(),
R.layout.row_item,
cursor,
fromFieldNames,
toViewIDs
);
// Set the adapter for the list view
listview = (ListView) getActivity().findViewById(R.id.listViewDB);
listview.setAdapter(myCursorAdapter);
}
#Override
public void onResume() {
super.onResume();
// set label to selected date. Get date from Bundle.
int dayOffset = sectionNumber -
FragmentHomeDayViewPager.pagerPageToday;
fragmentDate = Calendar.getInstance();
fragmentDate.add(Calendar.DATE, dayOffset);
SimpleDateFormat sdf = new
SimpleDateFormat(appMain.dateFormat);
String labelText = sdf.format(fragmentDate.getTime());
switch (dayOffset) {
case 0:
labelText += " (Today)";
break;
case 1:
labelText += " (Tomorrow)";
break;
case -1:
labelText += " (Yesterday)";
break;
}
label.setText(labelText);
}
#Override
public void onDestroy() {
super.onDestroy();
closeDataBase();
}
#Override
public void onDetach() {
super.onDetach();
startActivity( new Intent(getContext(),MainActivity.class));
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.AddItems:
AddEntry addEntry = new AddEntry();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(R.id.FragmentHolder,addEntry)
.commit();
break;
}
}
}
CalorieDatabase.java
public class CalorieDatabase {
// Constants & Data
private static final String TAG = "DBAdapter";
// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
public static final String KEY_NAME = "Description";
public static final String KEY_CalorieValue = "Calories";
public static final int COL_NAME = 1;
public static final int COL_CalorieValue= 2;
public static final String[] ALL_KEYS = new String[]
{KEY_ROWID, KEY_NAME, KEY_CalorieValue};
public static final String DATABASE_NAME = "CalorieDb";
public static final String DATABASE_TABLE = "Calorie_Info";
public static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement, "
+ KEY_NAME + " text not null, "
+ KEY_CalorieValue + " integer not null "
+ ");";
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
public CalorieDatabase(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public CalorieDatabase open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to the database.
public long insertRow(String description, int CalorieVal) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, description);
initialValues.put(KEY_CalorieValue, CalorieVal);
// Insert it into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String description, int
CalorieValue) {
String where = KEY_ROWID + "=" + rowId;
ContentValues newValues = new ContentValues();
newValues.put(KEY_NAME, description);
newValues.put(KEY_CalorieValue, CalorieValue);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int
newVersion) {
Log.w(TAG, "Upgrading application's database from version " +
oldVersion
+ " to " + newVersion + ", which will destroy all old
data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
}
Thanks again for helping me out. I've been stressing for the last couple of days trying to figure it out.
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);
}