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;
}
Related
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());
}
}
}
I use this method for retrieving my data
public String getdata() {
String[] columns= new String[]{RowId,RowBusinessName};
Cursor c=OurDatabase.query(TableName,columns,null,null,null,null,null);
String Result="";
int iRowId=c.getColumnIndex(RowId);
int iRowBusinessName=c.getColumnIndex(RowBusinessName);
for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
Result=Result+c.getString(iRowBusinessName)+"\n";
}
return Result;
}
How can I make it return structured data (id & business_name)?
I want to display every business_name in a single textview.
Please help
If I understand what you are trying to do, here is the solution if you want to get only 1 RowBusinessName returned as a String. (Hoping that your RowBusinessName is type String).
public String getdata(int rowId) {
String[] columns= new String[]{RowId,RowBusinessName};
Cursor cursor = db.query(TABLENAME, columns, RowId + "=?", new String[]{rowId + ""}, null, null, null, null);
String Result="";
if (cursor != null && cursor.moveToFirst()) {
// not required though
int rowId = cursor.getInt(cursor.getColumnIndexOrThrow(RowId));
String rowBusinessName = cursor.getString(cursor.getColumnIndexOrThrow(RowBusinessName));
result = rowBusinessName;
}
return result;
}
Now if you want a list of RowBusinessName, then you have to build a List<String> rather than appending it to Result. That's not really a good way!
public List<String> getAll() {
List<String> businessNameList = new ArrayList<String>();
String[] columns= new String[]{RowId,RowBusinessName};
Cursor c=OurDatabase.query(TableName,columns,null,null,null,null,null);
if (c != null && c.moveToFirst()) {
// loop until the end of Cursor and add each entry to Ticks ArrayList.
do {
String businessName = cursor.getString(cursor.getColumnIndexOrThrow(RowBusinessName));
if (businessName != null) {
businessNameList.add(businessName);
}
} while (c.moveToNext());
}
return businessNameList;
}
These are work around.
The appropriate answer would be to create an Object that holds id and businessName. That way, you build an object from DB and just return the entire Object.
if i have same values in a column and i want to return only one instead of all of them what would be a method.
ArrayList<String> getAllNotes() {
Cursor cursor;
mDbHelper = mSqliteHelper.getWritableDatabase();
String query = "SELECT * FROM " + SqliteHelpers.TABLE_NAME;
cursor = mDbHelper.rawQuery(query, null);
ArrayList<String> arrayList = new ArrayList<>();
while (cursor.moveToNext()) {
String itemname = cursor.getString(cursor.getColumnIndex(SqliteHelpers.NOTES_COLUMN));
if (itemname != null) {
arrayList.add(itemname);
}
}
return arrayList;
}
As you can see in image there are four items all are same but i want one tobe return other will be returned normal. except more than one.image
Just return the column you want:
ArrayList<String> getAllNotes() {
Cursor cursor;
mDbHelper = mSqliteHelper.getWritableDatabase();
String query = "SELECT Distinct NOTES_COLUMN FROM " + SqliteHelpers.TABLE_NAME;
cursor = mDbHelper.rawQuery(query, null);
ArrayList<String> arrayList = new ArrayList<>();
while (cursor.moveToNext()) {
String itemname = cursor.getString(cursor.getColumnIndex(SqliteHelpers.NOTES_COLUMN));
if (itemname != null) {
arrayList.add(itemname);
}
}
return arrayList;
}
I am trying to populate my AutoCompleteTextView from a column of values in my database.
The query I am running in my database is:
// GET MEMOS
public ArrayList<String> autoCompleteMemo(String table)
{
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<String> memoList = new ArrayList<String>();
String SQL_GET_MEMOS = "SELECT memo FROM " + table;
Cursor cursor = db.rawQuery(SQL_GET_MEMOS, null);
cursor.moveToFirst();
if (!cursor.isAfterLast()) {
do {
memoList.add(cursor.getString(0));
}
while (cursor.moveToNext());
}
cursor.close();
db.close();
return memoList;
}
And here is how I am attempting to set the values:
memoList = new String[db.autoCompleteMemo(table).size()];
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, memoList);
etMemo.setAdapter(adapter);
For some reason, this does not appear to be working. Am i converting from ArrayList to String[] properly?
Thanks
Also,
If i do something similar to this
String[] memoList = getResources().getStringArray(R.array.memoList);
and populate that in Strings.xml it works fine.
I changed my DB method to the following and it now works
public String[] autoCompleteMemo(String table) {
SQLiteDatabase db = this.getReadableDatabase();
String SQL_GET_MEMOS = "SELECT memo FROM " + table;
Cursor cursor = db.rawQuery(SQL_GET_MEMOS, null);
if (cursor.getCount() > 0) {
String[] str = new String[cursor.getCount()];
int i = 0;
while (cursor.moveToNext()) {
str[i] = cursor.getString(cursor.getColumnIndex("memo"));
i++;
}
return str;
}
else {
return new String[] {};
}
}
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