confusing about customize listview in android studio - java

What's the problem that my db is null?
there says Cursor cursor = myDb.getData(select * from Donation_Details); myDb : null and it pops out the error below.
And here is the runtime error says
Here is the DatabaseHelper which When I assign & declear database.
private static final String DATABASE_NAME = "eBossCharity.db";
private static final int DATABASE_VERSION = 1;
public dbOpenHelper(Context context){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
Here is the dbAccess when I want to get data from database.
public dbOpenHelper openHelper;
public SQLiteDatabase db;
private static dbAccess instance;
public dbAccess(Context context) {
this.openHelper = new dbOpenHelper(context);
}
public static dbAccess getInstance(Context context) {
if (instance == null) {
instance = new dbAccess(context);
}
return instance;
}
public Cursor getData(String sql) {
db = openHelper.getReadableDatabase();
return db.rawQuery("", null);
}
Here is the Summary page when I want to show the data into the customize list view. I put a break point at line 13 and debug it. It says my database is null. I Called the dbAccess method getData and grab the database"Donation_details". It should show the data...
ListView listView;
ArrayList<Model> mList;
RecordListAdapter mAdapter = null;
dbAccess myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_summary__page);
this.listView = findViewById(R.id.listView);
mList = new ArrayList<>();
mAdapter = new RecordListAdapter(this,R.layout.row,mList);
listView.setAdapter(mAdapter);
Cursor cursor = myDb.getData("Select * from Donation_Details");
mList.clear();
while(cursor.moveToNext()){
int id = cursor.getInt(0);
String txnno = cursor.getString(1);
String name = cursor.getString(2);
String txndate = cursor.getString(3);
BigDecimal amount = BigDecimal.valueOf(cursor.getDouble(4));
String description1 = cursor.getString(5);
String createddate = cursor.getString(7);
mList.add(new Model(id,txnno,name,txndate,amount,description1,createddate));
}
I think I missed something here and there. But I couldn't find it, Or maybe I typed wrong something to cause database is null? Can I have some guidance? Thank in advance...

You need to initialize 'dbAccess myDb'

Solution:
Write this
myDb = new dbAccess(this);
In your onCreate () after the line setContentView(...)
Try it..

Related

how to delete a specific item from table in database?

I want to make a to-do list app, and I wanted to delete the item in the list by tapping the checkbox.
I tried to make a "deleteTask"(as you see in the code) method in the database class. Also, you can see the "populateListView"
method, it provides data from the database into listview, I use it to refresh after each time a task got deleted from the database.
public void deleteTask(String task) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, COL2 , new String[]{task});
}
public void populateListView() {
try {
mDataBaseHelper = new DataBaseHelper(MainActivity.this);
data = mDataBaseHelper.getData();
mArrayList = new ArrayList<>();
if (data.getCount() != 0) {
while (data.moveToNext()) {
mArrayList.add(data.getString(1));
ListAdapter listAdapter = new ArrayAdapter(MainActivity.this, R.layout.list_items, R.id.checkBox, mArrayList);
list = (ListView) findViewById(R.id.myListId);
list.setAdapter(listAdapter);
}
mDataBaseHelper.close();
} else {
toastMessage("the Database is empty");
}
}catch(Exception e){
Log.e(TAG, "populateListView: error"+e.getStackTrace() );
}
}
when the application gets started, I tapped the item that I want to delete, but I see that the items start to be deleted by order from above!
one by one each time I tapped any checkbox.
You want :-
public void deleteTask(String task) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, COL2 + "=?" , new String[]{task});
}
If you weren't trapping the error by using the try/catch using db.delete(TABLE_NAME, COL2 , new String[]{task}); you would get an exception along the lines of :-
java.lang.IllegalArgumentException: Too many bind arguments. 1 arguments were provided but the statement needs 0 arguments.
However
Assuming that the issue with deleting rows sequentially rather than according to the checked item(s), is likely due to the handling of the checked items. However, as the code for this is not provided it would only be guess work to know where in the code you are going wrong.
One thing is that you do not want to be creating a new listadapter instance every time you populate the ListView.
As a hint to handling a ListView, but deleting an item when it is long-clicked based upon the COL2 value, perhaps consider the following which has been based upon your code (but deletes according to long clicking an item) :-
public void populateLisView() {
mDataBaseHelper = new DataBaseHelper(this); //<<<<<<<<<< NOTE 1
list = (ListView) this.findViewById(R.id.myListId); //<<<<<<<<<< NOTE 1
data = mDataBaseHelper.getData(); //<<<<<<<<<< get the data to be listed
if (listadapter == null) { //<<<<<<<<<< Only need to instantiate one adapter when it has not bee instantiated
listadapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,android.R.id.text1,data); // for convenience using a stock layout
list.setAdapter(listadapter);
//<<<<<<<<<<< add the onItemLongClick listener
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
mDataBaseHelper.deleteTaskByCol2(data.get(position)); //<<<<<<<<<< gets the value of the item according to it's position in the list
populateLisView(); //<<<<<<<<<< as the item has been deleted then refresh the Listview
return true; // flag the event as having been handled.
}
});
//<<<<<<<<<<< If the Adapter has been instantiated then refresh the ListView's data
} else {
listadapter.clear(); // Clear the data from the adapter
listadapter.addAll(data); // add the new changed data to the adapter
listadapter.notifyDataSetChanged(); // tell the adapter that the data has changed
}
}
NOTE 1
you would typically instantiate these variables once.
Check the comments
You may wish to edit your question to include how you are handling the check events.
The Full Working Example
DatabaseHelper.java
Note this may differ from yours a little
public class DataBaseHelper extends SQLiteOpenHelper {
public static final String DBNAME = "mydb";
public static final int DBVERSION = 1;
public static final String TABLE_NAME = "mytable";
public static final String COL1 = "col1";
public static final String COL2 = "col2";
SQLiteDatabase db;
private static final String CRT_MYTABLE_SQL = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME +
"(" +
COL1 + " TEXT, " +
COL2 + " TEXT" +
")";
public DataBaseHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CRT_MYTABLE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public long addMytableRow(String col1, String col2) {
ContentValues cv = new ContentValues();
cv.put(COL1,col1);
cv.put(COL2,col2);
return db.insert(TABLE_NAME,null,cv);
}
public ArrayList<String> getData() {
ArrayList<String> rv = new ArrayList<>();
Cursor csr = db.query(TABLE_NAME,null,null,null,null,null,null);
while (csr.moveToNext()) {
rv.add(csr.getString(csr.getColumnIndex(COL2)));
}
csr.close();
return rv;
}
public void deleteTaskByCol2(String task) {
db.delete(TABLE_NAME,COL2 + "=?",new String[]{task});
}
}
MainActivity.java
i.e. an example activity that is based upon your code, but according to the above :-
public class MainActivity extends AppCompatActivity {
DataBaseHelper mDataBaseHelper;
ArrayList<String> data;
ListView list;
ArrayAdapter<String> listadapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addSomeTestData();
populateLisView();
}
private void example001() {
}
public void populateLisView() {
mDataBaseHelper = new DataBaseHelper(this);
list = (ListView) this.findViewById(R.id.myListId);
data = mDataBaseHelper.getData();
if (listadapter == null) {
listadapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,android.R.id.text1,data);
list.setAdapter(listadapter);
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//mDataBaseHelper.deleteTaskWrong(data.get(position)); // ooops
mDataBaseHelper.deleteTaskByCol2(data.get(position));
populateLisView();
return true;
}
});
} else {
listadapter.clear();
listadapter.addAll(data);
listadapter.notifyDataSetChanged();
}
}
private void addSomeTestData() {
if (mDataBaseHelper == null) {
mDataBaseHelper = new DataBaseHelper(this);
}
if (DatabaseUtils.queryNumEntries(mDataBaseHelper.getWritableDatabase(),DataBaseHelper.TABLE_NAME) > 0) return;
mDataBaseHelper.addMytableRow("Test1","Test1");
mDataBaseHelper.addMytableRow("Test2","Test2");
mDataBaseHelper.addMytableRow("Test3","Test3");
mDataBaseHelper.addMytableRow("Test4","Test4");
}
}
Note AddSomeTestData adds some data for testing/demonstration.
Result
When first run :-
After LongClicking Test 2
i.e. the long clicked item has been removed (from the list and the database) and the list refreshed.
Try to replace
db.delete(TABLE_NAME, COL2 , new String[]{task});
By
db.delete(TABLE_NAME, COL2 + " = ?" , new String[]{task});

Multiple List RecyclerView SQLitedatabase

here's the structure
I have an app that makes the users' all his/her favorites placed on one place. So that he/she will not go through all the data. All I want is to have a recyclerview with multiple list that the "ListTitle" dynamically created, and when the "ListTitle" is already in it, only the child will appear. If not, create again another cardview. Thanks in advance.
My Code:
LoadsFavoriteAdapter.java
public class LoadFavoritesAdapter extends RecyclerView.Adapter<LoadFavoritesAdapter.LoadFavoritesViewHolder> {
private ArrayList<LoadFavorites> loadFavorites;
private Context context;
private ArrayList<LoadFavorites> mloadFavorites;
final String loadParent = "";
public LoadFavoritesAdapter(ArrayList<LoadFavorites> loadFavorites, Context context){
this.loadFavorites = loadFavorites;
this.context = context;
this.mloadFavorites = loadFavorites;
}
public class LoadFavoritesViewHolder extends RecyclerView.ViewHolder{
TextView txtLoadNameTest, txtLoadAmountTest;
public LoadFavoritesViewHolder(View view){
super(view);
txtLoadAmountTest = view.findViewById(R.id.txtLoadAmountTest);
txtLoadNameTest = view.findViewById(R.id.txtLoadNameTest);
}
}
public LoadFavoritesViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.favorite_item, parent, false);
return new LoadFavoritesViewHolder(itemView);
}
public void onBindViewHolder(final LoadFavoritesViewHolder holder, int position){
holder.txtLoadNameTest.setText(loadFavorites.get(position).getLoadName());
holder.txtLoadAmountTest.setText(loadFavorites.get(position).getLoadAmount());
}
public int getItemCount(){
return mloadFavorites.size();
}}
Favorites.java
public class Favorites extends AppCompatActivity {
Database localDb;
Context CTX = this;
private RecyclerView recyclerView;
private ArrayList<LoadFavorites> loadFavorites;
private LoadFavoritesAdapter loadFavoritesAdapter;
private Database database;
private ArrayList<LoadFavorites> mloadFavorites;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favorites);
localDb = new Database(this);
recyclerView = findViewById(R.id.recycler_favorites);
loadFavorites = new ArrayList<>();
loadFavoritesAdapter = new LoadFavoritesAdapter(loadFavorites, this);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(loadFavoritesAdapter);
database = new Database(this);
getDataFromSQLite();
}
private void getDataFromSQLite(){
new AsyncTask<Void, Void, Void>(){
protected Void doInBackground(Void... params){
loadFavorites.clear();
loadFavorites.addAll(database.getFavorites());
return null;
}
protected void onPostExecute(Void aVoid){
super.onPostExecute(aVoid);
}
}.execute();
}}
Database.java
public class Database extends SQLiteAssetHelper {
private static final String DB_NAME="Favorites.db";
private static final int DB_VER=1;
public Database(Context context) {
super(context, DB_NAME, null, DB_VER);
try{
String myPath = context.getFilesDir().getAbsolutePath(); // also check the extension of you db file
File dbfile = new File(myPath);
if(dbfile.exists()){
Toast.makeText(context, "database exists", Toast.LENGTH_LONG).show();
Toast.makeText(context, ""+myPath, Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "cant find database", Toast.LENGTH_LONG).show();
Toast.makeText(context, ""+myPath, Toast.LENGTH_SHORT).show();
}
}
catch(SQLiteException e){
System.out.println("Database doesn't exist");
}
}
public void addToFavorites(String loadId, String loadName, String loadDetail, String loadNumber, String loadDuration, String loadAmount, String loadParent){
SQLiteDatabase db = getReadableDatabase();
String query = String.format("INSERT INTO Favorites(LoadId, LoadName, LoadDetail, LoadNumber, LoadDuration, LoadAmount, LoadParent) VALUES('%s','%s','%s','%s','%s','%s','%s');", loadId, loadName, loadDetail, loadNumber, loadDuration, loadAmount, loadParent);
db.execSQL(query);
}
public void removeFromFavorites(String loadId){
SQLiteDatabase db = getReadableDatabase();
String query = String.format("DELETE FROM Favorites WHERE LoadId='%s';", loadId);
db.execSQL(query);
}
public boolean isFavorite(String loadId){
SQLiteDatabase db = getReadableDatabase();
String query = String.format("SELECT * FROM Favorites WHERE LoadId='%s';", loadId);
Cursor cursor = db.rawQuery(query,null);
if(cursor.getCount() <= 0){
cursor.close();
return false;
}
cursor.close();
return true;
}
public Cursor getInformation(Database database){
SQLiteDatabase db = database.getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String[] columns = {"LoadId", "LoadParent"};
String sqlTable = "Favorites";
qb.setTables(sqlTable);
Cursor CR = qb.query(db,columns,null,null,null,null,null);
return CR;
}
public List<LoadFavorites> getFavorites(){
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String[] sqlSelect = {"LoadId", "LoadName", "LoadDetail", "LoadNumber", "LoadDuration", "LoadAmount", "LoadParent"};
String sqlTable = "Favorites";
qb.setTables(sqlTable);
Cursor c = qb.query(db,sqlSelect,null,null,null,null,null);
final List<LoadFavorites> result = new ArrayList<>();
if(c.moveToFirst()){
do{
result.add(new LoadFavorites(c.getString(c.getColumnIndex("LoadId")),
c.getString(c.getColumnIndex("LoadName")),
c.getString(c.getColumnIndex("LoadDetail")),
c.getString(c.getColumnIndex("LoadNumber")),
c.getString(c.getColumnIndex("LoadDuration")),
c.getString(c.getColumnIndex("LoadAmount")),
c.getString(c.getColumnIndex("LoadParent"))
));
}while(c.moveToNext());
}
return result;
}}

Error when accessing a SQlite database in android studio

Following my last post i was using SQLiteOpenHelper to access a pre-populated sqlite database and someone suggested i use SQLAssetHelper so i found a guide followed it and tried to implement it but i am still getting errors.
like: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.content.Context.getDatabasePath(java.lang.String)' on a null object reference
I know what a null pointer exception is in most cases but dont understand it in this context as i am new to android development. The errors on line 26 of my DBHleper class below. - String dbPath = myContext.getDatabasePath(DATABASE_NAME).getPath();
public class DBHelper extends SQLiteAssetHelper {
private static final String DATABASE_NAME = "Database.db";
private static final int DATABASE_VERSION = 1;
private Context myContext;
private SQLiteDatabase mDatabase;
public DBHelper(Context context){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
public void openDatabase(){
String dbPath = myContext.getDatabasePath(DATABASE_NAME).getPath();
if(mDatabase!= null && mDatabase.isOpen()){
return;
}
mDatabase = SQLiteDatabase.openDatabase(dbPath,null,SQLiteDatabase.OPEN_READWRITE);
}
public Cursor getItems(){
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables("Attraction");
Cursor c = qb.query(db,null,null,null,null,null,null);
c.moveToFirst();
return c;
}
}
My main
public class MainActivity extends AppCompatActivity {
DBHelper newDB;
private Cursor attraction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
newDB = new DBHelper(this);
newDB.openDatabase();
attraction = newDB.getItems();
}
}
I am probably having a mental block and not seeing the solution but any more help on this issue will be appreciated.

Android NullPointerException on retrieving SQlite data to listiew thru SimpleCursorAdapter [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I'm trying to populate my database to listview through simple cursor adapter via intent to new activity. Cant figure out why is it crashing?
This is my Database helper class:
public class DBhelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Mydatabase.db";
public static final String TABLE_NAME = "contacts";
public static final String _ID = "_ID";
public static final String COL_2 = "NAME";
public static final String COL_3 = "PHONE";
public static final String COL_4 = "EMAIL";
public static final String COL_5 = "HQ";
public static final String COL_6 = "ADDRESS";
public DBhelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table contacts"+ "(_id integer primary key autoincrement, name text, phone text, email text, hq text, address text)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
public boolean insertContact (String name, String phone, String email, String hq, String address){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,name);
contentValues.put(COL_3,phone);
contentValues.put(COL_4,email);
contentValues.put(COL_5,hq);
contentValues.put(COL_6,address);
db.insert(TABLE_NAME,null,contentValues);
return true;
}
public Cursor getAllDAta(){
Cursor cursor;
String[] columns = {DBhelper._ID, DBhelper.COL_2, DBhelper.COL_3, DBhelper.COL_4, DBhelper.COL_5, DBhelper.COL_6};
SQLiteDatabase db = this.getWritableDatabase();
cursor = db.query(DBhelper.TABLE_NAME,columns, null, null, null, null, null);
return cursor;
}
DBhelper dbHelper;
SQLiteDatabase database;
Context context;
public DBhelper open() throws SQLException {
dbHelper = new DBhelper(context);
database = dbHelper.getWritableDatabase();
return this;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
DBhelper mydb;
EditText name, phone, email, hq, address;
Button addData, viewData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mydb = new DBhelper(this);
name = (EditText) findViewById(R.id.editName);
phone = (EditText) findViewById(R.id.editPhone);
email = (EditText) findViewById(R.id.editEmail);
hq = (EditText) findViewById(R.id.editHQ);
address = (EditText) findViewById(R.id.editAddress);
addData = (Button) findViewById(R.id.addData);
viewData = (Button) findViewById(R.id.viewData);
}
public void addClick(View view){
String nm, ph, em, h, as;
nm = name.getText().toString();
ph = phone.getText().toString();
em = email.getText().toString();
h = hq.getText().toString();
as = address.getText().toString();
boolean checkk = mydb.insertContact(nm,ph,em,h,as);
if (checkk = true) {
Toast.makeText(MainActivity.this, "Data Added", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(MainActivity.this,"Data Not Added",Toast.LENGTH_LONG).show();
}
}
public void showClick(View v1){
Intent intent = new Intent(MainActivity.this,Displayc.class);
startActivity(intent);
finish();
}
}
My display activity
public class Displayc extends AppCompatActivity {
ListView listView;
DBhelper mydb1;
SimpleCursorAdapter adapter;
final String[] from = new String[] {DBhelper._ID, DBhelper.COL_2, DBhelper.COL_3, DBhelper.COL_4, DBhelper.COL_5, DBhelper.COL_6};
final int[] to = new int[] {R.id.idv, R.id.namev, R.id.phonev, R.id.emailv, R.id.hqv, R.id.addressv };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_displayc);
listView = (ListView) findViewById(R.id.list_sq);
mydb1 = new DBhelper(this.getBaseContext());
mydb1.open();
Cursor c = mydb1.getAllDAta();
adapter = new SimpleCursorAdapter(getBaseContext(),R.layout.template,c,from,to,0);
listView.setAdapter(adapter);
}
}
Error message:
[java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bibulkumar.sqliteapp/com.example.bibulkumar.sqliteapp.Displayc}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase android.content.Context.openOrCreateDatabase(java.lang.String, int, android.database.sqlite.SQLiteDatabase$CursorFactory, android.database.DatabaseErrorHandler)' on a null object reference
[Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase android.content.Context.openOrCreateDatabase(java.lang.String, int, android.database.sqlite.SQLiteDatabase$CursorFactory, android.database.DatabaseErrorHandler)' on a null object reference
Context context;
public DBhelper open() throws SQLException {
dbHelper = new DBhelper(context);
database = dbHelper.getWritableDatabase();
return this;
The context you use here is not initialized and therefore null. Hence the NPE when you're calling getWritableDatabase().
Remove the open() and any calls to it - you don't actually need it for anything.

listview from assets/example.sqlite

I want to generate list view from an existing database . I have gone through several websites which will create database on run time ,but I don't want it like that . What I want is to read database from the exiting one, and populate listview from it. I am new to android development.
My database path .
assets/databases/example.sqlite
Check this library: SQLiteAssetHelper.
This is working example:
public class MyDataBase extends SQLiteAssetHelper {
private static final String TAG = "MyDataBase.class";
private static final String DATABASE_NAME = "news.sqlite";
private static final int DATABASE_VERSION = 1;
//Table Fields
private static final String ITEM_TITLE = "title";
private static final String ITEM_DESCRIPTION = "description";
private static final String ITEM_CATEGORY = "category";
private static final String ITEM_PUBDATE = "pubDate";
private static final String ITEM_CREATOR = "creator";
private static final String ITEM_URL = "url";
private static final String ITEM_IMAGE_URI = "image_uri";
private static final String ITEM_IMAGE_PATH = "image_path";
//Table name
private static final String TABLE = "Item";
public MyDataBase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
//getting Items from database
public ArrayList<Item> getItems(){
ArrayList<Item> items=new ArrayList<>();
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String [] sqlSelect = {"id", ITEM_TITLE, ITEM_DESCRIPTION, ITEM_CATEGORY, ITEM_PUBDATE,
ITEM_CREATOR, ITEM_URL, ITEM_IMAGE_URI, ITEM_IMAGE_PATH };
String sqlTables = TABLE;
qb.setTables(sqlTables);
Cursor c = qb.query(db, sqlSelect, null, null,
null, null, null);
if (c.moveToFirst()) {
do {
Item item = new Item();
item.setTitle(c.getString(c.getColumnIndex(ITEM_TITLE)));
item.setCategory(c.getString(c.getColumnIndex(ITEM_CATEGORY)));
item.setDescription(c.getString(c.getColumnIndex(ITEM_DESCRIPTION)));
item.setPubDate(c.getString(c.getColumnIndex(ITEM_PUBDATE)));
item.setCreator(c.getString(c.getColumnIndex(ITEM_CREATOR)));
item.setURL(c.getString(c.getColumnIndex(ITEM_URL)));
item.setImage_uri(c.getString(c.getColumnIndex(ITEM_IMAGE_URI)));
item.setImage_path(c.getString(c.getColumnIndex(ITEM_IMAGE_PATH)));
items.add(item);
} while (c.moveToNext());
}
Log.i(TAG, "getItems() completed");
c.close();
db.close();
return items;
}
And now get your data from DB asynchronously:
private class DbTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
MyDataBase db = new MyDataBase(context);
list.clear();
list.addAll(db.getItems());
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
adapter.notifyDataSetChanged();
}
Hope this answer will be useful for you.
Happy coding!

Categories