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);
}
Related
In Android Studio I have checkboxes on a TableLayout TableRows that will display values id from SQLite database. I want whenever I click "SHOW" button to get the values of all checked checkboxes.
I could not get the values to display. And the for- and while loops make each id display thrice.
SQLiteDatabase db = dataHelper.getReadableDatabase();
String selectQuery = "SELECT * FROM table2 where column2 =" + 1;
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndex("_id"));
TableLayout table;
final int row = 3;
final CheckBox cb[] = new CheckBox[row];
table = (TableLayout) findViewById(R.id.tablelayout);
for (int i = 0; i < row; i++) {
TableRow rows = new TableRow(this);
final CheckBox pass = new CheckBox(this);
pass.setGravity(Gravity.CENTER);
pass.setTextColor(Color.BLACK);
pass.setText("a" + id);
rows.addView(pass);
View view = new View(this);
view.setLayoutParams(new
TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT, 2));
view.setBackgroundColor(Color.BLACK);
table.addView(rows);
table.addView(view);
cb[i] = pass;
}
smsbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int a = 0; a < row; a++) {
if (cb[a].isChecked()) {
Message.message(getApplicationContext(), "Checked :" + cb[a].getText());
}
}
}
});
}
}
I got it worked. The for loop and while loop together makes the loops to increase the creation of rows. So I used only for loop to select from sqlite column and also to create the table rows. Thanks to all. My working code below.
SQLiteDatabase db = dataHelper.getReadableDatabase();
String selectQuery = "SELECT * FROM " + dbSMS.TABLE_TALERT + " where _id > 1";
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.getCount() > 0) {
TableLayout table;
final int row = cursor.getCount(); //variable to get the number of row
final CheckBox cb[] = new CheckBox[row];
table = (TableLayout) findViewById(R.id.tablelayout);
for (int i = 0; i < row; i++) {
cursor.moveToNext();
int id = cursor.getInt(cursor.getColumnIndex("_id"));
TableRow rows = new TableRow(this);
final CheckBox gateway = new CheckBox(this);
gateway.setGravity(Gravity.CENTER);
gateway.setTextColor(Color.BLACK);
gateway.setText(String.valueOf(id));
rows.addView(gateway);
View view = new View(this);
view.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT, 2));
view.setBackgroundColor(Color.BLACK);
table.addView(rows);
table.addView(view);
cb[i] = gateway;
smsbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int a = 0; a < row; a++) {
if (cb[a].isChecked()) {
Message.message(getApplicationContext(), "Checked :" + cb[a].getText());
}
}
}
});
}
}
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
Im making an android app and this part is where a cursor will go through a database and store the 'title' section of the table into a string array. This is then called in another class and is used to dynamically show buttons based on the entries. The code for putting the titles into an array is as follows:
public String[] getTitles()
{
SQLiteDatabase db =getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, SPORTS_TABLE_NAME);
String title;
String[] titleArray = new String[100];
String sql = "SELECT Title FROM Sports;";
Cursor cursor = db.rawQuery(sql, null);
int i = 1;
while (cursor.moveToNext()) {
if(cursor != null && cursor.moveToFirst()) {
title = cursor.getString(0);
titleArray[i] = title;
i++;
}
if(cursor != null)
db.close();
}
cursor.close();
return titleArray;
}
Then it is called with the following code:
int i = 1;
String[] titlesArray = db.getTitles();
for(String titles: titlesArray){
Button btn = new Button(this);
btn.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
btn.setId(i);
btn.setText(titlesArray[i]);
ll.addView(btn);
i++;
}
Been looking for a while and think it needs a fresh pair of eyes.. any ideas?
what if your query returns more than 100 rows? If think it would be safer to use something like
String sql = "SELECT Title FROM Sports;";
Cursor cursor = db.rawQuery(sql, null);
if (cursor == null)
return;
String[] titleArray = new String[cursor.getCount()];
while (cursor.moveToNext()) {
title = cursor.getString(0);
titleArray[i] = title;
i++;
}
of, better, a Collection.
String sql = "SELECT Title FROM Sports;";
Cursor cursor = db.rawQuery(sql, null);
if (cursor == null)
return;
ArrayList<String> titleArrayList = new ArrayList<String>();
while (cursor.moveToNext()) {
title = cursor.getString(0);
titleArrayList.add(title);
}
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 });
I am trying to get the mp3 files from the sd card and put them on a listview why does this code not work it messes up when adding elements to the song name
String[] proj = { MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Artists.ARTIST };
Cursor tempCursor = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
proj,
null,
null,
null);
tempCursor.moveToFirst(); //reset the cursor
int col_index=-1;
int numSongs=tempCursor.getCount();
int currentNum=0;
do{
col_index = tempCursor.getColumnIndexOrThrow(MediaStore.Audio.Artists.ARTIST);
List<String> songname = new ArrayList<String>();
if(tempCursor.moveToNext()){
songname.add(tempCursor.getString(currentNum+1));
ArrayAdapter<String> songss = new ArrayAdapter<String>(this, R.id.songs,songname);
setListAdapter(songss);
} else{
return;
}
currentNum++;
}while (tempCursor.moveToNext());
this line should be outside of the do...while() loop
List<String> songname = new ArrayList<String>();
as the loop iterating every time songname will define in memory with new object and you got only last name. simillary this code also after the while loop
ArrayAdapter<String> songss = new ArrayAdapter<String>(this, R.id.songs,songname);
setListAdapter(songss);
here is the complete code
String[] proj = { MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Artists.ARTIST };
Cursor tempCursor = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
proj,
null,
null,
null);
int col_index=-1;
int numSongs=tempCursor.getCount();
int currentNum=0;
List<String> songname = new ArrayList<String>();
while (tempCursor.moveToNext())
col_index = tempCursor.getColumnIndexOrThrow(MediaStore.Audio.Artists.ARTIST);
songname.add(tempCursor.getString()); // here you need the column index number of song title name only
}
ArrayAdapter<String> songss = new ArrayAdapter<String>(this, R.id.songs,songname);
setListAdapter(songss);
This piece of code does not make much sense, what are you trying to do?
List<String> songNames = new ArrayList<String>();
Cursor c = grabCursorWithSongs();
try {
while (c.moveToNext()) {
String songName = c.getString(c.getColumnIndex("song_name"));
songNames.add(songName);
}
} finally {
c.close();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(...);
setListAdapter(adapter);