Reputation: 430
I have been struggling for hours trying to use an array inside a while loop. The problem is that im very new to android development so i have no idea how to do this. I have seen similar questions but most/all of them does not suite for my scenario. The code below does work but im calling a new instance of articlesData for each row in the while statement, this causes it to just return the value of the last row.. Is there any way to use an array like ArticlesData[] and get all my data in it? Please help :) Here is my code:
public ArticlesData[] getArticleData(int no) {
Log.e("DB STAT", "getArticleData Called");
SQLiteDatabase db = helper.getWritableDatabase();
String[] columns = { ArticlesHelper.ID, ArticlesHelper.TITLE, ArticlesHelper.IMAGEURL };
Cursor cursor = db.query(ArticlesHelper.TABLE_NAME,
columns,
ArticlesHelper.DATENUMBER+" < '"+Integer.toString(no)+"'", null, null, null, ArticlesHelper.DATENUMBER+" DESC", "20");
while (cursor.moveToNext()) {
int id = cursor.getInt(0);
Log.e("DB STAT", "Article Id = "+Integer.toString(id));
String title = cursor.getString(1);
Log.e("DB STAT", "Article Title = "+title);
String url = cursor.getString(2);
articlesData = new ArticlesData[] {
new ArticlesData(title, Integer.toString(id), url)
};
}
return articlesData;
}
Upvotes: 0
Views: 92
Reputation: 2538
You most probably want to use a Collection such as List:
public List<ArticlesData> getArticleData(int no) {
Log.e("DB STAT", "getArticleData Called");
SQLiteDatabase db = helper.getWritableDatabase();
String[] columns = { ArticlesHelper.ID, ArticlesHelper.TITLE, ArticlesHelper.IMAGEURL };
Cursor cursor = db.query(ArticlesHelper.TABLE_NAME,
columns,
ArticlesHelper.DATENUMBER+" < '"+Integer.toString(no)+"'", null, null, null, ArticlesHelper.DATENUMBER+" DESC", "20");
List<ArticlesData> list = new ArrayList<ArticlesData>();
while (cursor.moveToNext()) {
int id = cursor.getInt(0);
Log.e("DB STAT", "Article Id = "+Integer.toString(id));
String title = cursor.getString(1);
Log.e("DB STAT", "Article Title = "+title);
String url = cursor.getString(2);
list.add(new ArticlesData(title, Integer.toString(id), url));
}
return list;
}
You should not try to use a raw array here because it has a fixed size. You could use it if you limited the number of rows in the query so you'd know exactly how much elements you need, but even then it would still be much easier to just use a Collection elsewhere in the code.
As you seem new to Android development and Java I suggest you first get acquainted with the basic data structures such as Maps, Lists, and Sets, and then later you might want to use an ORM to save you the pain of writing boilerplate code for interacting with a database.
Upvotes: 1