How to add SQLite rows to an ArrayList<> - android

I retrieve all the rows from my SQLite-DB Table
Cursor cursor = db.rawQuery("select * from table",null);
Then I want to add each row to an ArrayList
Please help!

IF you're using custom object array, then use like following :
public void fillDataToArray() {
ArrayList<BeanClass> arrayList = new ArrayList<BeanClass>();
DatabaseHandler db = new DatabaseHandler(getActivity());
db.open();
try
{
Cursor c = db.getImageNameForList();
if (c != null && c.getCount() > 0) {
c.moveToFirst();
for (int count = 0; count < c.getCount(); count++) {
Beanclass detail = new Beanclass ();
detail.setName(c.getString(c
.getColumnIndex(DatabaseHandler._ID)));
detail.setPath(c.getString(c
.getColumnIndexOrThrow(DatabaseHandler._PATH)));
arrayList.add(detail);
c.moveToNext();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
c.close();
db.close();
}
If you use this in activity, change getActivity() to local context or whichever way you use context in activities.
DATA RETRIEVAL METHOD IN DB ADAPTER CLASS :
> public Cursor getImageNameForList() {
return db.rawQuery("select " + IMAGE_PATH + " from "+ TABLE_PRODUCT_IMAGES , null);
}

Code to do that would look like this, depending on whats in your Table. You have to create a Class that is able to represent a Row in your table.
For example if there are people in your table, with name and age, you will need an object Human(String name, int age) to put into a list.
SQLiteDatabase db = helper.getReadableDatabase();
ArrayList<Human> results = new ArrayList<Human>();
try {
String rawQuery = "Select name, age from people";
Cursor c = db.rawQuery(rawQuery, null);
try {
if (!c.moveToFirst())
return null;
do {
results.add(new Human(c.getString(0),c.getInt(1)));
} while (c.moveToNext());
} finally {
c.close();
}
} finally {
db.close();
}
public class Human {
private String name;
private int age;
public Human (String name, int age) {
this.name = name;
this.age = age;
}
}

In your Db Adapter class, add this method
public ArrayList<String>getData()
{
ArrayList<String>names=new ArrayList<String>();
Cursor c = getReadableDatabase().rawQuery("Select * from tableName", null);
c.moveToFirst();
do
{
String s1=c.getString(c.getColumnIndex("<Column_Name>"));
names.add(s1);
}while(c.moveToNext());
return names;
}
after that in your activity class add this
ArrayList<String> cid;
DB_Adapter database = new DB_Adapter(getApplicationContext(), "<your schema name>", null, 1);
cid=database.getData();
After that add your arraylist to your array adapter which is set to ListView

Related

How to get assign values to an arraylist item inside a cursor iterator

I am trying to assign one variable to an ArrayList item inside a cursor but it always returns me last value. Here is the code below.
Getting value from DB
public ArrayList<Bean> getPendingData(String s) {
SQLiteDatabase db = getWritableDatabase();
String[] columns = {name};
String[] selectionArgs = {s};
Cursor cursor = db.query(TABLE_NAME, columns, " pending= ? ", selectionArgs, null, null, null, null);
cursor.moveToFirst();
ArrayList<Bean> pending = new ArrayList<>();
String index0 = null;
Bean bean;
bean = new Bean();
while(!cursor.isAfterLast()) {
index0 = cursor.getString(cursor.getColumnIndex(name));
bean.setQuestion(index0);
pending.add(bean);
cursor.moveToNext();
}
cursor.close();
return pending;
}
Bean.java
public class Bean {
public static int id; // ans
public static String score;
public static String logo;
public static String image;
public static String getQuestion() {
return question;
}
public static void setQuestion(String question) {
Bean.question = question;
}
public static String question;
public static String description;
public static String option_three;
public static String OptionFour;
}
You should initialize your bean inside the while block:
while(!cursor.isAfterLast()) {
Bean bean = new Bean();
index0 = cursor.getString(cursor.getColumnIndex(name));
bean.setQuestion(index0);
pending.add(bean);
cursor.moveToNext();
}
The reason is that Java uses objects by reference, so you're always adding the same object to the array "pending", but in following iterations you're changing the value of this object, so finally you have the value of the last iteration.
cursor.isAfterLast() returns true when cursor is at last row position. Adding a ! (not) means perform till it is not at the end of cursor.
so while(!cursor.isAfterLast()){} means while loop will traverse till last record of cursor.
Use this method to fetch all rows returning from cursor.
if (cursor != null) {
if (cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
homeClassesArrayList = new ArrayList<>();
do {
// fetching data
} while (cursor.moveToNext());
}
}
}

How to iterate and retrieve over all data stored in sqlite database

I am having problem while retrieving data from sqlite database what I need is to retrieve all data on console. But I am getting only one rows data on console
Here is the code to insert and retrieve data from Sqlite. Please specify what I am missing or doing wrong. Thanks for any help.
public long InsertContacts(Contacts contacts) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_IMAGE, DbUtility.getBytes(contacts.getBmp()));
contentValues.put(KEY_BABY_NAME, contacts.getBaby_name());
contentValues.put(KEY_GENDER, contacts.getBaby_gender());
contentValues.put(KEY_SET_DATE, contacts.getDate());
contentValues.put(KEY_SET_TIME, contacts.getTime());
return db.insert(TABLE_NAME, null, contentValues);
}
public Contacts retriveContactsDetails() {
SQLiteDatabase db = this.getReadableDatabase();
String[] columns = new String[]{KEY_IMAGE, KEY_BABY_NAME, KEY_GENDER, KEY_SET_DATE, KEY_SET_TIME};
Cursor cursor = db.query(TABLE_NAME, columns, null, null, null, null, null);
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
byte[] blob = cursor.getBlob(cursor.getColumnIndex(KEY_IMAGE));
String name = cursor.getString(cursor.getColumnIndex(KEY_BABY_NAME));
String gender = cursor.getString(cursor.getColumnIndex(KEY_GENDER));
String date = cursor.getString(cursor.getColumnIndex(KEY_SET_DATE));
String time = cursor.getString(cursor.getColumnIndex(KEY_SET_TIME));
Log.d(TAG, DbUtility.getImage(blob) + name + "-" + gender + "-" + date + "- " + time); // I need to get all date here that have been inserted but i am getting only first rows data every time i insert.
cursor.moveToNext();
return new Contacts(DbUtility.getImage(blob), name, gender, date, time);
}
cursor.close();
return null;
}
}
Contacts.java
public class Contacts {
private Bitmap bmp;
private String baby_name;
private String baby_gender;
private String date;
private String time;
public Contacts(Bitmap b, String n, String g, String d, String t) {
bmp = b;
baby_name = n;
baby_gender = g;
date = d;
time = t;
}
public Bitmap getBmp() {
return bmp;
}
public String getBaby_name() {
return baby_name;
}
public String getBaby_gender() {
return baby_gender;
}
public String getDate() {
return date;
}
public String getTime() {
return time;
}
}
You should change your retriveContactsDetails() to this:
public List<Contacts> retriveContactsDetails() {
SQLiteDatabase db = this.getReadableDatabase();
String[] columns = new String[]{KEY_IMAGE, KEY_BABY_NAME, KEY_GENDER, KEY_SET_DATE, KEY_SET_TIME};
List<Contacts> contactsList = new ArrayList<>();
Cursor cursor;
try {
cursor = db.query(TABLE_NAME, columns, null, null, null, null, null);
while(cursor.moveToNext()) {
byte[] blob = cursor.getBlob(cursor.getColumnIndex(KEY_IMAGE));
String name = cursor.getString(cursor.getColumnIndex(KEY_BABY_NAME));
String gender = cursor.getString(cursor.getColumnIndex(KEY_GENDER));
String date = cursor.getString(cursor.getColumnIndex(KEY_SET_DATE));
String time = cursor.getString(cursor.getColumnIndex(KEY_SET_TIME));
contactsList.add(new Contacts(DbUtility.getImage(blob), name, gender, date, time));
Log.d(TAG, DbUtility.getImage(blob) + name + "-" + gender + "-" + date + "- " + time);
}
} catch (Exception ex) {
// Handle exception
} finally {
if(cursor != null) cursor.close();
}
return contactsList;
}
Also, your Contacts class should be named Contact as it contains only a single instance of your object.
public Contacts retriveContactsDetails() {
...
while (cursor.isAfterLast() == false) {
...
cursor.moveToNext();
return new Contacts(...);
}
Your Contacts class is named wrong because it contains only a single contact. It should be named Contact.
The return statement does what it says, it returns from the function. So the loop body cannot be executed more than once.
What you actually want to do is to construct a list of contacts, add one contact object to the list in each loop iteration, and return that list at the end.

How to correctly write big CRUD sqlite android app

I'm writing an app that manipulates with database consists of 3 tables. I created this database from json file using models (Worker model, specialty model) with getters and setters. Now I want to get specific info from this database. I'v already made it but my code is pretty silly. What I need is to change the architecture of my app but I don't know how exactly it should looks like.
This is the examples of my methods, and they are pretty week
This is how I add info into database. I like it, I think it's correct:
public void addWorker(Worker worker){
List<Specialty> specialty;
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
//fixind names
String f_name = fixName(worker.getF_name());
String l_name = fixName(worker.getL_name());
String birthday = fixDate(worker.getBirthday());
values.put(KEY_F_NAME, f_name);
values.put(KEY_L_NAME, l_name);
values.put(KEY_BIRTHDAY, birthday);
values.put(KEY_AVATR_URL, worker.getAvart_url());
specialty = worker.getSpecialty();
long worker_id = db.insert(TABLE_WORKERS,null,values);
//add unique specialty
for (Specialty spec: specialty){
createRelations(worker_id, spec.getSpecialty_id());
if (getCount(spec.getSpecialty_id()) == 0){
addSpecialty(spec);
}
}
}
And this is how I take info from database:
public String[] getFullInfo(String worker_name){
String selectQuery = "HUGE QUERY HERE "where workers.f_name =?";
Log.e(LOG_TAG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, new String [] {worker_name});
String[] details = new String[5];
c.moveToFirst();
while (c.isAfterLast() == false){
details[0] = c.getString(c.getColumnIndex(KEY_F_NAME));
details[1] = c.getString(c.getColumnIndex(KEY_L_NAME));
details[2] = c.getString(c.getColumnIndex(KEY_BIRTHDAY));
details[3] = c.getString(c.getColumnIndex("age"));
details[4] = c.getString(c.getColumnIndex(KEY_SPEC_NAME));
c.moveToNext();
}
return details;
}
This is my another query and it has different return type:
public List<Map<String ,String>> getWorkerListBySpec(String spec_name){
String selectQuery = "HUGE QUERY HERE
"where specialty.spec_name=?";
Log.e(LOG_TAG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, new String [] {spec_name});
//making list of workers
List<Map<String ,String>> data = new ArrayList<Map<String,String>>();
c.moveToFirst();
while (c.isAfterLast() == false){
Map<String,String> datum = new HashMap<String,String>(2);
datum.put(KEY_F_NAME, c.getString(c.getColumnIndex(KEY_F_NAME)));
datum.put(KEY_L_NAME, c.getString(c.getColumnIndex(KEY_L_NAME)));
datum.put(KEY_BIRTHDAY, c.getString(c.getColumnIndex(KEY_BIRTHDAY)));
data.add(datum);
c.moveToNext();
}
return data;
}
and the third one, which also have different return type:
public List<String> getAllSpecs_Names(){
List<String> spec_names = new ArrayList<String>();
String selectQuery = "select * from " + TABLE_SPECIALTY;
Log.e(LOG_TAG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
if (c.moveToFirst()){
do{
spec_names.add(c.getString(c.getColumnIndex(KEY_SPEC_NAME)));
}while (c.moveToNext());
}
return spec_names;
}
I know, that this is all wrong.
Please tell me how I should make all my queries.
It will be good if you give me the link to check how the app should look like
instead of returning a List or Map, you should better return a own CursorWrapper
so you could could look like this:
public WorkerCursor getWorkerListBySpec(String spec_name){
String selectQuery = "HUGE QUERY HERE
"where specialty.spec_name=?";
Log.e(LOG_TAG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, new String [] {spec_name});
return new WorkerCursor(cursor);
}
public static class WorkerCursor extends CursorWrapper {
/**
* Creates a cursor wrapper.
*
* #param cursor The underlying cursor to wrap.
*/
public WorkerCursor(Cursor cursor) {
super(cursor);
}
public Worker getWorker() {
return getWorkerAtCursor();
}
public Worker getWorker(int position) {
if (moveToPosition(position)) {
return getWorkerCursor();
} else {
return null;
}
}
private Worker getWorkerAtCursor() {
if (isBeforeFirst() || isAfterLast()) {
return null;
}
worker worker = new Worker();
worker.name = c.getString(c.getColumnIndex(KEY_F_NAME));
....
return worker;
}
}
and the same for your List, just with a other CursorWrapper
and don't forget to close the CursorWrapper, when it's no more needed, like in onDestroy of Activity and so

How to retrieve whole Row of data in Sqlite

I want to retrieve a whole row at a time in sqlite database. All of them are strings. I wrote a method.
If anyone could check the error of this.
Thanks
public ArrayList<Integer> queueAll_row(){
String[] columns = new String[]{Key_row_ID,Key_Customer_name,Key_customer_nic,Key_roof,Key_floor,Key_walls,Key_toilets,Key_No_Rooms,Key_electricity,Key_drinkingWater,Key_status,Key_ownership
,Key_hvBankAcc,Key_loansOfOtherBnks,Key_current_No_Emp,Key_new_Emp,Key_income_source1,Key_income_source2,Key_income_source3};
Cursor cursor = ourDb.query(DB_Table, columns,
null, null, null, null, null);
ArrayList<Integer> values = new ArrayList<Integer>();
cursor.moveToFirst();
while (cursor.moveToNext()) {
values.add(cursor.getInt(0));
}
return values;
}
Please try this, I hope its help you.
public ArrayList<ProjectModel> getprojectName() {
ArrayList<ProjectModel> values = new ArrayList<ProjectModel>();
String query = "SELECT * from project";
cursor = sqLiteDatabase.rawQuery(query, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
values.add(new ProjectModel(cursor.getString(cursor
.getColumnIndex("project_id")), cursor
.getString(cursor.getColumnIndex("project_name"))));
} while (cursor.moveToNext());
}
}
return values;
}
model class
public class ProjectModel {
private String project_id;
private String project_name;
public ProjectModel(String project_id, String project_name) {
super();
this.project_id = project_id;
this.project_name = project_name;
}
public String getProject_id() {
return project_id;
}
public String getProject_name() {
return project_name;
}
You may run a raw query also to get whole row from a table in database..
you may try this code.. hope it will work for you.
public ArrayList<Integer> queueAll_row() {
String query = "select * from " + DB_Table;
Cursor cursor = ourDb.rawQuery(query, null);
ArrayList<Integer> values = new ArrayList<Integer>();
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
while (cursor.moveToNext()) {
values.add(cursor.getInt(0));
}
}
return values;
}
Steps:-
1.To store all value from single row you have to use model class
2.add following code
public ArrayList queueAllRow(){
String query = "select * from "+DB_Table;
Cursor cursor = ourDb.rawQuery(query, null);
ArrayList<ModelClass> values = new ArrayList<ModelClass>();
if(cursor.moveToFirst()){
do {
ModelClass ob1=new ModelClass();
ob1.setvalue(cursor.getString(cursor.getColumnIndex("COL_NAME")));
//set the values to other data members, same like above
values.add(ob1);
} while (cursor.moveToNext());
}
return values;
}

Read data from database in format row[field] -> value

I got really confused with the database usage in Android.
I have this database:
Table name: articles
Fields: id, article, chapterid
i currently have the below code and use it inside a fragment:
List<Comment> contents = ((MainActivity)getActivity()).connectRawQueryDB("database.sqlite", "SELECT * FROM articles WHERE chapterid = 1");
And in my MainActivity
public List<Comment> connectRawQueryDB(String DB_NAME, String RawQuery) {
List<Comment> comments = new ArrayList<Comment>();
Cursor cursor = database.rawQuery(RawQuery,null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Comment comment = cursorToComment(cursor);
comments.add(comment);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
return comments;
}
private Comment cursorToComment(Cursor cursor) {
Comment comment = new Comment();
comment.setId(cursor.getLong(0));
comment.setComment(cursor.getString(1));
return comment;
}
What i need is to make a query to the database and then output values in the following format:
e.g. row[article] and get the value of article and from the same query get row[id] and get the value in id field.
Add this method in you dbhandler....
public ArrayList<Comment> getCommentdata()
{
//get db
SQLiteDatabase db = getWritableDatabase();
ArrayList<Comment> resultCommentList = new ArrayList<Comment>();
String resultQuery = "select id, article, chapterid from "+YOUR_TABLE;
Cursor cursor = db.rawQuery(resultQuery, null);
if(cursor.moveToFirst())
{
do
{
Comment commentObject = new Comment();
commentObject.setcommentUID(cursor.getInt(0));
commentObject.setarticle(cursor.getString(1));
commentObject.setChapterID(cursor.getInt(2));
resultCommentList.add(commentObject);
}
while(cursor.moveToNext());
}
//close db
if(db != null)
db.close();
return resultCommentList;
}
And when yout want to retrive data
allComent = localDBHelper.getCommentdata();
for(int i = 0; i < allComent .size(); i++)
{
int id=allComment.get(i).getcommentUID();
String =allComment.get(i).getarticle();
int cid=allComment.get(i).getChapteID();
}

Categories

Resources