SQLite query: get all columns of a row(android)? - java

Here is the schema:
SQL query is:
SELECT * from unjdat where col_1 = "myWord";
i.e., I want to display all columns for a row whose col_1 is myWord.
int i;
String temp;
words = new ArrayList<String>();
Cursor wordsCursor = database.rawQuery("select * from unjdat where col_1 = \"apple\" ", null); //myWord is "apple" here
if (wordsCursor != null)
wordsCursor.moveToFirst();
if (!wordsCursor.isAfterLast()) {
do {
for (i = 0; i < 11; i++) {
temp = wordsCursor.getString(i);
words.add(temp);
}
} while (wordsCursor.moveToNext());
}
words.close();
I think the problem lies with the looping. If I remove the for loop and do a wordsCursor.getString(0) it works. How to loop to get all columns?
Note:
col_1 is never null, any of the col_2 to col_11 may be null for some rows.
All columns and all rows in the table are unique.

This is how it should be
Cursor cursor = db.rawQuery(selectQuery, null);
ArrayList<HashMap<String, String>> maplist = new ArrayList<HashMap<String, String>>();
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
for(int i=0; i<cursor.getColumnCount();i++)
{
map.put(cursor.getColumnName(i), cursor.getString(i));
}
maplist.add(map);
} while (cursor.moveToNext());
}
db.close();
// return contact list
return maplist;
Edit User wanted to know how to fill ListView with HashMap
//listplaceholder is your layout
//"StoreName" is your column name for DB
//"item_title" is your elements from XML
ListAdapter adapter = new SimpleAdapter(this, mylist, R.layout.listplaceholder, new String[] { "StoreName",
"City" }, new int[] { R.id.item_title, R.id.item_subtitle });

Related

Can't add items from database to list

i am trying to add some items from database to my list but when i run the application i see that the list is empty.
this is what i did to add items to a list
car_size = dbHelper.getSize("cars"); // getSize is a method that count items in database
Random random = new Random();
int cars_random = random.nextInt(car_size);
List<String> myList = dbHelper.read_added_names("cars"); // and this line should add items from database to the list
if(myList!= null && myList.size() > 0) {
textView.setText(myList.get(truth_random));
}else {
Toast.makeText(activity.this, "" + myList.size(), Toast.LENGTH_SHORT).show();
} // here i can see that the size of my list is 0 and it's empty
I'm sure the methode that should read database (here i named it read_aded_names) works fine
public List<String> read_added_names (String subject){
String selectQuery;
List<String> list = new ArrayList<String>();
if (subject.equals("*")) {
selectQuery = "SELECT * FROM " + TABLE_NAME1;
}else {
selectQuery = "SELECT * FROM " + TABLE_NAME1 + " WHERE " + COLUMN_SUBJECT + " = '" + subject+" '";
}
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(1));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return list;
}
Query contains space after subject variable making it "cars " instead of "cars". This can be the issue.

how to store string data into integer array from sqlite for android

I want to convert the sqlite data into integer array.
public Integer[] getch() {
SQLiteDatabase database = this.getReadableDatabase();
Cursor cursor = database.rawQuery("SELECT sum(sales) FROM sales group by outlet_code order by ordered_date", null);
// String[] array = new String[crs.getCount()];
int columnIndex = 3;
Integer[] in = new Integer[cursor.getCount()];
if (cursor.moveToFirst())
{
for (int i = 0; i < cursor.getCount(); i++)
{
in[i] = cursor.getInt(columnIndex);
cursor.moveToNext();
}
}
cursor.close();
return in;
}
I need result in following format:
int[] income = { 2000,2500,2700,3000,2800,3500,3700,3800, 0,0,0,0};
Integer[] income = controller.getch();
I'm getting the error :
Couldn't read row 0, col 3 from CursorWindow. Make sure the Cursor is
initialized correctly before accessing data from it
Why are you using columnIndex = 3, your sql query will return only 1 column i.e Sum(sales), so you should set your columnIndex value to 0
Try this
public Integer[] getch() {
SQLiteDatabase database = this.getReadableDatabase();
Cursor cursor = database.rawQuery("SELECT sum(sales) FROM sales group by outlet_code order by ordered_date", null);
// String[] array = new String[crs.getCount()];
int columnIndex = 0;
Integer[] in = new Integer[cursor.getCount()];
if (cursor.moveToFirst())
{
for (int i = 0; i < cursor.getCount(); i++)
{
in[i] = cursor.getInt(columnIndex);
cursor.moveToNext();
}
}
cursor.close();
return in;
}
Hope this helps

retrieve multiple rows form android sqlite

I am going to fetch some rows with specific tag in android Sqlite.
The problems are
I got 15 with cursor.getCount(); but 13 rows retrieved.
the 13 rows just repeat last row data
here is my code
public ArrayList<HashMap<String, String>> getTodo(String tag) {
ArrayList<HashMap<String,String>> arList = new ArrayList<HashMap<String,String>>();
HashMap<String, String> todo = new HashMap<String, String>();
String selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE "
+ COLUMN_TAG + " = ?";
String[] args={tag};
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, args);
// Move to first row
cursor.moveToFirst();
System.out.println(cursor.getCount());
if (cursor.getCount() > 0) {
do {
todo.put(COLUMN_ID, cursor.getString(cursor.getColumnIndex(COLUMN_ID)));
todo.put(COLUMN_FROM, cursor.getString(cursor.getColumnIndex(COLUMN_FROM)));
todo.put(COLUMN_TO, cursor.getString(cursor.getColumnIndex(COLUMN_TO)));
todo.put(COLUMN_TITLE, cursor.getString(cursor.getColumnIndex(COLUMN_TITLE)));
todo.put(COLUMN_TAG, cursor.getString(cursor.getColumnIndex(COLUMN_TAG)));
arList.add(todo);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
// return todo
return arList;
}
Please help. Thanks
You are using the same todo object for all rows, so you end up with lots of references to the same object.
Create a new one for each row in the loop:
Cursor cursor = db.rawQuery(selectQuery, args);
try {
while (cursor.moveToNext()) {
HashMap<String, String> todo = new HashMap<String, String>();
todo.put(...);
...
arList.add(todo);
}
finally {
cursor.close();
}
It's better to make the todo's you want to acquire into objects
public class Todo {
public String id, from, to, title, tag;
//setters and getters (not necessary)
}
public ArrayList<MyData> getTodo(String tag) {
ArrayList<MyData> arList = new ArrayList<MyData>();
String selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE "
+ COLUMN_TAG + " = ?";
String[] args={tag};
try {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, args);
// Move to first row
if (!cursor.moveToFirst())
return arList;
do {
Todo todo = new Todo();
todo.id = cursor.getString(cursor.getColumnIndex(COLUMN_ID));
todo.from = cursor.getString(cursor.getColumnIndex(COLUMN_FROM));
todo.to = cursor.getString(cursor.getColumnIndex(COLUMN_TO));
todo.title = cursor.getString(cursor.getColumnIndex(COLUMN_TITLE))
todo.tag = cursor.getString(cursor.getColumnIndex(COLUMN_TAG));
arList.add(todo);
} while(cursor.moveToNext());
cursor.close();
db.close();
return arList;
}
finally {
cursor.close();
db.close();
}
}
You keep putting new strings to an already created hashmap, but you keep using the same keys, and therefore, many entries get replaced. The Todo object keeps your code readable. You should also check if the cursor can jump to the first entry (which makes a getCount call unnecessary)

How to put cursor data in array?

I am fetching data from database and after that assigning it to arrays in this process i always get length of all arrays as 1 only.
Method :
public void fetchData() {
database.open();
Cursor cursor = database.getAllData();
cursor.moveToFirst();
while (!(cursor.isAfterLast())) {
nameArr = new String[] { cursor.getString(1) }; // i tried to put cursor data in arr from here
addressArr = new String[] { cursor.getString(2) };
contactArr = new String[]{ cursor.getString(3) };
cursor.moveToNext();
}
database.close();
Log.d("ArrayLength", Integer.toString(nameArr.length));//The arraylength is 1 i dont know why??
}
Use Cursor.getCount() outside while loop to initialize all arrays as:
int count=cursor.getCount();
nameArr=new String[count];
addressArr=new String[count];
contactArr=new String[count];
int index_count=0;
while(!(cursor.isAfterLast())){
nameArr[index_count]=cursor.getString(1);
addressArr[index_count]=cursor.getString(2);
contactArr[index_count]=cursor.getString(3);
index_count++;
cursor.moveToNext();
}
To avoid use of index_count use ArrayList to store all data from cursor/
This is a very simple example...
Cursor client = db.rawQuery(sql, null);
String[][] clients = new String[2][client.getCount()];
if(client.moveToFirst()){
do{
clients[0][i] = client.getString(client.getColumnIndex(CLIENT_NAME));
clients[1][i++] = String.valueOf(client.getInt(client.getColumnIndex(CLIENT_ID)));
}while (client.moveToNext());
}
client.close();

Android Show database entries in listview

I have searched and cannot figure out why my code is not working correctly. I want to display a row from my database and show all the records of that row in a listview. The code works, however it only returns one listview value and not all records from the row inside the database. Here is my updated code:
db = openOrCreateDatabase ("Names", MODE_PRIVATE, null);
String query = "SELECT * from players";
Cursor c = db.rawQuery(query, null);
int count = c.getCount();
c.moveToFirst();
ListView layout=(ListView)findViewById(R.id.listView1);
for (Integer j = 0; j < count; j++){
String lister = c.getString(c.getColumnIndex("names_of"));
String[] items = {lister};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
layout.setAdapter(adapter);
c.moveToNext();
}
db.close();
}
The array is working incorrectly, how do I get more than the first value? Thank you all in advance
use this one, You should be store all value in string array and move the adapter line out of loop
for (Integer j = 0; j < count; j++){
String[j] items = lister;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
layout.setAdapter(adapter);
try this code.
try to use this:
db = openOrCreateDatabase ("Names", MODE_PRIVATE, null);
String query = "SELECT * from players";
Cursor c = db.rawQuery(query, null);
int count = 0;
String[] items=new String[c.getCount()];
if (c.moveToFirst()) {
do {
TextView txt = new TextView(getApplicationContext());
txt.setText(c.getString(c.getColumnIndex("names_of")));
txt.setPadding(20, 20, 20, 20);
txt.setTextSize(20.0f);
txt.setTextColor(Color.MAGENTA);
String lister = c.getString(c.getColumnIndex("names_of"));
items[count] = lister;
count++;
} while (c.moveToNext());
}
c.close();
}
db.close();
after that set adapter if items is not empty
if(items.length>0){
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
layout.setAdapter(adapter);
}

Categories

Resources