Issue adding string to List<String> - java

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);

Related

Function to get only camera image paths, not all images stored on android phone

I've got a function that returns the paths of all images on my phone, however I only want it to return images took by the camera. Here is the function:
public String[] getPath(){
final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
final String orderBy = MediaStore.Images.Media._ID;
//Stores all the images from the gallery in Cursor
Cursor cursor = getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
null, orderBy);
//Total number of images
int count = cursor.getCount();
//Create an array to store path to all the images
String[] arrPath = new String[count];
for (int i = 0; i < count; i++) {
cursor.moveToPosition(i);
int dataColumnIndex = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
//Store the path of the image
arrPath[i]= cursor.getString(dataColumnIndex);
Log.i("PATH", arrPath[i]);
}
cursor.close();
return arrPath;
}
What do I need to change in order to only get the paths stored in /DCIM/CAMERA?
Usually every Android device saves the camera images to DCIM directory. Here is a method that gets all the images saved in that directory.
public static List<String> getCameraImages(Context context) {
public final String CAMERA_IMAGE_BUCKET_NAME = Environment.getExternalStorageDirectory().toString()+ "/DCIM/Camera";
public final String CAMERA_IMAGE_BUCKET_ID = String.valueOf(CAMERA_IMAGE_BUCKET_NAME.toLowerCase().hashCode());
final String[] projection = { MediaStore.Images.Media.DATA };
final String selection = MediaStore.Images.Media.BUCKET_ID + " = ?";
final String[] selectionArgs = { CAMERA_IMAGE_BUCKET_ID };
final Cursor cursor = context.getContentResolver().query(Images.Media.EXTERNAL_CONTENT_URI,
projection,
selection,
selectionArgs,
null);
ArrayList<String> result = new ArrayList<String>(cursor.getCount());
if (cursor.moveToFirst()) {
final int dataColumn =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
do {
final String data = cursor.getString(dataColumn);
result.add(data);
} while (cursor.moveToNext());
}
cursor.close();
return result;
}

String array throws index out of bounds exception

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);
}

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);
}

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

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 });

Categories

Resources