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();
Related
I have an array string named "likedAlbums_name"
That array String contains a list of names. I would like to pass the list of names into the whereVal of the cursor.
When I have 1 name in the "likedAlbums_name" array string, everything works fine. But if I have more than 1 name, it crash.
How to I fix that?
Thank you!!!
code:
likedAlbums_name = database.getLikedAlbums(); // returns a list of names
Code:
public void getSongsInAlbum() {
String[] projections = {
MediaStore.Audio.Albums.ALBUM,
MediaStore.Audio.Albums.ARTIST,
MediaStore.Audio.Albums.NUMBER_OF_SONGS,
MediaStore.Audio.Albums.ALBUM_ART};
String where = MediaStore.Audio.Media.ALBUM + "=?";
String[] whereVal = likedAlbums_name;
String orderBy = MediaStore.Audio.Media.ALBUM;
ContentResolver contentResolver = getActivity().getContentResolver();
Cursor cursor = contentResolver.query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, projections, where, whereVal, orderBy);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
newAlbum newAlbum = new newAlbum();
newAlbum.albumName = cursor.getString(0);
newAlbum.artist_Name = cursor.getString(1);
newAlbum.number_of_songs_in_album = cursor.getInt(2);
album_list.add(newAlbum);
} while (cursor.moveToNext());
}
cursor.close();
}
}
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);