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!
Related
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..
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;
}}
I am not getting the add string returned back.
The android app takes input as food item and prints its respective calories.
here is the code for creating table:
public class dietclass extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "diet7.db";
public static final String TABLE_NAME = "Cal_val";
public static final String COL1 = "ID";
public static final String COL2 = "ITEM";
public static final String COL3 = "QUANTITY";
public static final String COL4 = "CALORIES";
public dietclass(Context context) {
super(context,DATABASE_NAME,null,1);
SQLiteDatabase db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,ITEM TEXT,QUANTITY VARCHAR,CALORIES INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " +TABLE_NAME);
onCreate(db);
}
}
And here is the code for retrieving data from my activity which is taking item and calories as input.
public class foodcal extends AppCompatActivity {
EditText item;
EditText quantity;
TextView calories;
Button calculate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_foodcal);
item = (EditText)findViewById(R.id.etitem);
quantity = (EditText)findViewById(R.id.etquantity);
calories = (TextView)findViewById(R.id.calories);
calculate = (Button)findViewById(R.id.calculate);
calculate.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String itemstr = item.getText().toString();
printDatabase(itemstr);
//String dbstring = dietclass.databaseToString(itemstr);
//calories.setText(String.valueOf(dbstring));
}
});
}
public void printDatabase(String item){
String dbstring = dietclass.databaseToString(this,item);
//String label;
//label = dbstring + "calories";
calories.setText(String.valueOf(dbstring));
}
private static class dietclass extends SQLiteOpenHelper {
private static String DB_PATH = "/data/data/com.example.janhvik.dietapp/databases/";
private static String DB_NAME = "diet7.db";
private static String TABLE_NAME = "Cal_val";
private static SQLiteDatabase myDataBase;
private Context myContext;
public dietclass(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
private static String databaseToString(Context ctx, String item_name) {
String myDbPath;
int cal = 0 ;
String add="";
myDbPath = DB_PATH+DB_NAME;
myDataBase = SQLiteDatabase.openOrCreateDatabase(myDbPath, null);
String query = "SELECT * FROM "+TABLE_NAME+" WHERE ITEM='"+item_name+"'";
Cursor c = myDataBase.rawQuery(query,null);
if(c!= null && c.moveToFirst()){
add = c.getString(c.getColumnIndex("CALORIES"));
c.close();
}
add = add + " calories";
//Toast.makeText(ctx,add, Toast.LENGTH_LONG).show();
return add;
}
I am not getting any error but the code is not taking the value from the select query, can anyone help in this.
I think you've got rather mixed up and complicated matters by appearing to use multiple database helpers/methods to open the same database when you only need to use the database helper. I'm unsure what the exact issue was, there was insufficient code to build an exact replica.
Instead a created simplified working code.
Here's a rewrite/simplification based upon your code :-
First ONE databasehelper class namely dietclass :-
public class dietclass extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "diet7.db";
public static final String TABLE_NAME = "Cal_val";
public static final String COL1 = "ID";
public static final String COL2 = "ITEM";
public static final String COL3 = "QUANTITY";
public static final String COL4 = "CALORIES";
//private static String DB_PATH = "/data/data/com.example.janhvik.dietapp/databases/";
//private static String DB_NAME = "diet7.db";
SQLiteDatabase myDataBase;
private Context myContext;
public dietclass(Context context) {
super(context,DATABASE_NAME,null,1);
myDataBase = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,ITEM TEXT,QUANTITY VARCHAR,CALORIES INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " +TABLE_NAME);
onCreate(db);
}
public long insertCal_ValEntry(String item, String quantity, int calories) {
ContentValues cv = new ContentValues();
cv.put(COL2,item);
cv.put(COL3,quantity);
cv.put(COL4,calories);
return myDataBase.insert(TABLE_NAME,null,cv);
}
public String databaseToString(String item_name) {
//String myDbPath;
int cal = 0 ;
String add="";
//myDbPath = DB_PATH+DB_NAME;
//myDataBase = SQLiteDatabase.openOrCreateDatabase(myDbPath, null);
String query = "SELECT * FROM "+TABLE_NAME+" WHERE ITEM='"+item_name+"'";
Cursor c = myDataBase.rawQuery(query,null);
if(c.moveToFirst()){
add = c.getString(c.getColumnIndex("CALORIES"));
c.close();
}
add = add + " calories";
//Toast.makeText(ctx,add, Toast.LENGTH_LONG).show();
return add;
}
}
Notes
For testing purposes, method insertCal_ValEntry has been added.
Done away with any attempt to open Database rather this is done by the helper.
The check to see if the cursor is null has been removed, it is basically useless as SQLite will not return a null, it will always return a cursor, which may be empty. the Cursor move??? methods, such as moveToFirst return false if the move cannot be made.
Context isn't required by the databaseToString method so removed it.
databaseToString method made to be an instance method rather than class method (i.e not static) and made it public.
The activity in this case I've used MainActivity
public class MainActivity extends AppCompatActivity {
EditText item;
EditText quantity;
TextView calories;
Button calculate;
dietclass dbhelper; //<<<< we want an instance of the database helper
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_foodcal);
item = (EditText)findViewById(R.id.etitem);
quantity = (EditText)findViewById(R.id.etquantity);
calories = (TextView)findViewById(R.id.calories);
calculate = (Button)findViewById(R.id.calculate);
dbhelper = new dietclass(this); //<<<< get the instance of the database helper
dbhelper.insertCal_ValEntry("Porridge", "100g",5000); //<<<< For testing
dbhelper.insertCal_ValEntry("Cake","500g", 20000); //<<<< For testing
calculate.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String itemstr = item.getText().toString();
printDatabase(itemstr);
//String dbstring = dietclass.databaseToString(itemstr);
//calories.setText(String.valueOf(dbstring));
}
});
}
public void printDatabase(String item){
String dbstring = dbhelper.databaseToString(item); //<<<<
//String label;wr
//label = dbstring + "calories";
calories.setText(String.valueOf(dbstring));
}
}
Notes
The principle used above could be used in any activity. That is get an instance of the database helper and then invoked methods within the helper to get/add/alter data in the database.
Results from the above:-
1) When App is started:-
2) Clicking without input (or inputting item not in table) :-
3) Clicking after inputting valid item :-
Additional Info
If you really want to get the database path the following is less prone to errors:-
String databasepath = getDatabasePath(dietclass.DATABASE_NAME).getPath();
((TextView) findViewById(R.id.dbpath)).setText(databasepath);
With the dbpath TextView (note run on 7.0.0 device):-
On a 4.1.1 device :-
I'm trying to get integer values, to be displayed in a listview from SQLlite using cursors but it shows the following error:
java.lang.IllegalStateException: Couldn't read row 0, col 4 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
Here are my code
MyItems.java:
public ArrayList<SalesItemInformationLV> retrieveAllForlist(Context c)
{
ArrayList<SalesItemInformationLV> items = new ArrayList<SalesItemInformationLV>();
Cursor myCursor;
String mystring = "";
MyDbAdapter db = new MyDbAdapter(c);
db.open();
//contactIdList.clear();
//contactList.clear();
myCursor = db.retrieveAllEntriesCursor();
if (myCursor != null && myCursor.getCount() > 0)
{
myCursor.moveToFirst();
do {
contactIdList.add(myCursor.getInt(db.COLUMN_KEY_ID));
items.add(new SalesItemInformationLV(myCursor.getString(db.COLUMN_NAME_ID), myCursor.getInt(db.COLUMN_QTYSOLD_ID)));
} while (myCursor.moveToNext());
}
db.close();
return items;
}
MyDbAdapter.java:
private SQLiteDatabase _db;
private final Context context;
public static final String KEY_ID = "_id";
public static final int COLUMN_KEY_ID = 0;
public static final String ENTRY_NAME = "entry_name";
public static final int COLUMN_NAME_ID = 1;
public static final String ENTRY_QTYSOLD = "entry_qtysold";
public static final int COLUMN_QTYSOLD_ID = 4;
private MyDBOpenHelper dbHelper;
//private MyDBOpenHelper dbHelper2;
public MyDbAdapter(Context _context)
{
this.context = _context;
//step 16 - create MyDBOpenHelper object
//constructor
dbHelper = new MyDBOpenHelper(context, DATABASE_NAMEA, null, DATABASE_VERSION);
//constructor
//dbHelper2 = new MyDBOpenHelper(context, DATABASE_NAME2, null, DATABASE_VERSION);
}
public Cursor retrieveAllEntriesCursor() {
//step 21 - retrieve all records from table
Cursor c = null;
try {
c = _db.query(DATABASE_TABLE, new String[] {KEY_ID, ENTRY_NAME}, null, null, null, null, null);
}
catch (SQLiteException e)
{
Log.w(MYDBADAPTER_LOG_CAT, "Retrieve fail!");
}
return c;
}
I suspect the error comes from MyItems.java, but I'm having a hard time figuring out what's the error.
Seems like you are fetching only 2 columns(KEY_ID, ENTRY_NAME) from database and while reading you are expecting 3 columns.
c = _db.query(DATABASE_TABLE, new String[] {KEY_ID, ENTRY_NAME}, null, null, null, null, null);
You are trying to get value from column 4, which is throuing an error.
public static final int COLUMN_QTYSOLD_ID = 4;
Use this method in your databasehelper class
public Cursor getalldata() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery(" select * from " + TABLE_Name, null);
return res;
}
**and call this method where you want to get your data from database table **
public void getdata(){
Cursor res = db.getstafdata(); //db id an object of database helper //class
if (res.getCount() == 0) {
Toast.makeText(getApplicationContext(),
"no data", Toast.LENGTH_LONG).show();
} else {
StringBuffer stbuff = new StringBuffer();
while (res.moveToNext()) {
detail.add(new doctor_details(res.getString(1),res.getString(2),res.getString(3)));
}
}
}
I have a problem in adding values to my String[] array from another class. What I wanted to do is to add values to my MainScreenEntered.java class from database through my MyDatabaseAdapter.java class.
PLease help.
THis is my code.
MainScreenentered.java
public class MainScreenEntered extends Activity implements OnItemClickListener{
#SuppressLint("NewApi")
ListView lv;
List<RowItem> rowItems;
MyDatabaseAdapter mh;
String username;
ListView listViewSMS;
Cursor cursor;
Context context;
public static String[] names = new String[] {};
public static String[] descriptions = new String[] {};
public static String[] pics = new String[] {};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_screen_entered);
mh = new MyDatabaseAdapter(this);
Bundle bundle = this.getIntent().getExtras();
username = bundle.getString("username");
Message.message(this, username);
try
{
mh.getDataToDatabase();
rowItems = new ArrayList<RowItem>();
for(int i =0; i< names.length; i++)
{
RowItem item = new RowItem(pics[i], names[i], descriptions[i]);
rowItems.add(item);
}
lv = (ListView)findViewById(R.id.lvEntries);
CustomListViewAdapter adapter = new CustomListViewAdapter(this, R.layout.list_layout,rowItems);
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);
}
catch(Exception e)
{
Message.message(this, ""+e);
}
}
}
MyDatabaseAdapter.java
public class MyDatabaseAdapter {
MyHelper helper;
public MyDatabaseAdapter (Context context)
{
helper = new MyHelper(context);
}
public void getDataToDatabase()
{
MainScreenEntered ms = new MainScreenEntered();
SQLiteDatabase db = helper.getWritableDatabase();
String columns[] = {MyHelper.ENTRY_FULLNAME,MyHelper.ENTRY_DESCRIPTION,MyHelper.ENTRY_IMAGE};
Cursor c=db.query(MyHelper.TABLE_ENTRIES, columns, null, null, null, null, null);
int i=0;
while(c.moveToNext())
{
String name = c.getString(0);
String desc = c.getString(1);
String pic = c.getString(2);
ms.names[i] = name;
ms.descriptions[i] = desc;
ms.pics[i] = pic;
i++;
}
db.close();
}
}
you can do like this
in onCreate
mh = new MyDatabaseAdapter(this,this);
now
public class MyDatabaseAdapter {
MyHelper helper;
MainScreenEntered ms;
public MyDatabaseAdapter (Context context, MainScreenEntered ms)
{
helper = new MyHelper(context);
this.ms = ms;
}
public void getDataToDatabase()
{
SQLiteDatabase db = helper.getWritableDatabase();
String columns[] = {MyHelper.ENTRY_FULLNAME,MyHelper.ENTRY_DESCRIPTION,MyHelper.ENTRY_IMAGE};
Cursor c=db.query(MyHelper.TABLE_ENTRIES, columns, null, null, null, null, null);
int i=0;
while(c.moveToNext())
{
String name = c.getString(0);
String desc = c.getString(1);
String pic = c.getString(2);
ms.names[i] = name;
ms.descriptions[i] = desc;
ms.pics[i] = pic;
i++;
}
db.close();
}
}
Try this..
In your MainScreenEntered.java
public static ArrayList<String> names = new ArrayList<String>();
public static ArrayList<String> descriptions = new ArrayList<String>();
public static ArrayList<String> pics = new ArrayList<String>();
and MyDatabaseAdapter
while(c.moveToNext())
{
String name = c.getString(0);
String desc = c.getString(1);
String pic = c.getString(2);
MainScreenEntered.names.add(name);
MainScreenEntered.descriptions.add(desc);
MainScreenEntered.pics.add(pic);
}
then
rowItems = new ArrayList<RowItem>();
for(int i =0; i<names.length; i++)
{
RowItem item = new RowItem(pics.get(i), names.get(i), descriptions.get(i));
rowItems.add(item);
}
use c.movetoFirst() before while loop and for static array u doesn't have to create object of it u can directly call it ClassName.variable_name ... it will be a better if you use arraylist of string rather than string array.
Be careful by doing DB operation on the UI thread you will might have some ANR.