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);
}
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();
}
}
Please find below the code I have implemented.
I need to detect the click event of the button outside another method.
public List<CorrectAnswer> passSessionIdTogetResults(String id) {
db = this.getReadableDatabase();
List<CorrectAnswer> correctAnswerList = new ArrayList<>();
CorrectAnswer correctAnswer = new CorrectAnswer();
Cursor cursor2 = db.rawQuery("SELECT * FROM table_test_start WHERE test_start_id ="+id,null);
if(cursor2.moveToFirst()){
do{
String question_number= cursor2.getString(cursor2.getColumnIndex(ID_TEST));
String question_id = cursor2.getString(cursor2.getColumnIndex(QUESTION_ID_TEST_START));
String selected_option = cursor2.getString(cursor2.getColumnIndex(SELECTED_OPTION_TEST_START));
Cursor cursor = db.rawQuery("SELECT * FROM practice_questions WHERE question_content_id='"+question_id+"' AND question_answer='"+selected_option+"'", null);
if (cursor.moveToFirst()) {
String green = "green";
correctAnswer.setCorrect_anwer_green(green);
Log.d("DbHelper","Question ID "+question_id);
Log.d("DbHelper","Correct Answer "+green);
}else {
String red = "red";
correctAnswer.setWrong_answer_red(red);
Log.d("DbHelper","Question ID "+question_id);
Log.d("DbHelper","Wrong Answer " +red );
}
correctAnswer.setCorrect_id(question_number);
correctAnswer.setQuestion_number_id(question_id);
correctAnswer.setSelected_set_options(selected_option);
correctAnswerList.add(correctAnswer);
}while(cursor2.moveToNext());
}
return correctAnswerList;
}
Getting last value of and inserted for n times.
Try this
String question_number= cursor2.getString(cursor2.getColumnIndex(ID_TEST));
String question_id = cursor2.getString(cursor2.getColumnIndex(QUESTION_ID_TEST_START));
String selected_option = cursor2.getString(cursor2.getColumnIndex(SELECTED_OPTION_TEST_START));
Cursor cursor = db.rawQuery("SELECT * FROM practice_questions WHERE question_content_id='"+question_id+"' AND question_answer='"+selected_option+"'", null);
cursor.moveToFirst()
do{
String green = "green";
correctAnswer.setCorrect_anwer_green(green);
Log.d("DbHelper","Question ID "+question_id);
Log.d("DbHelper","Correct Answer "+green);
correctAnswer.setCorrect_id(question_number);
correctAnswer.setQuestion_number_id(question_id);
correctAnswer.setSelected_set_options(selected_option);
correctAnswerList.add(correctAnswer);
} while(cursor2.moveToNext());
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;
}
I'm trying to share a video(to social media) in an app I'm building. I'm using intents for which I need a Uri to parse. I'm trying to select items on a simple file manager (List activity) and then share them on long press. Thus I require the following code to get the Uri of the video for using it in the intents.
ContentResolver contentResolver = ctx.getContentResolver();
String videoUriStr = null;
long videoId = -1;
Uri videosUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
String[] projection = { MediaStore.Video.VideoColumns._ID };
// TODO This will break if we have no matching item in the MediaStore.
Cursor cursor = contentResolver.query(videosUri, projection,
MediaStore.Video.VideoColumns.DATA + " =?",
new String[] { fileToShare }, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(projection[0]);
videoId = cursor.getLong(columnIndex);
cursor.close();
if (videoId != -1)
videoUriStr = videosUri.toString() + "/" + videoId;
{
return videoUriStr;
}
UPDATE
The first few items on the ListActivity File manager file will share properly. But the latest videos show the error.
Error: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
your cursor has 0 rows. So, the line cursor.getLong(columnIndex); throws CursorIndexOutOfBoundsException. please check for null and check whether any rows exist or not.
If there is no rows cursor.moveToFirst() will return false.
Cursor cursor = contentResolver.query(videosUri, projection,
MediaStore.Video.VideoColumns.DATA + " =?",
new String[] { fileToShare }, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndex(projection[0]);
videoId = cursor.getLong(columnIndex);
cursor.close();
if (videoId != -1)
{
videoUriStr = videosUri.toString() + "/" + videoId;
}
}
}
return videoUriStr;
The MediaStore.Video.VideoColumns.DATA field holds the path for the video file. So, if you are using uri (content://mnt/sdcard/Videos/test.mp4) to fetch the file change it to file path (/mnt/sdcard/Videos/test.mp4).
Use while loop to check is cursor have data or not :
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(projection[0]);
videoId = cursor.getLong(columnIndex);
cursor.close();
Replace with this code :
while (cursor.moveToNext()){
int columnIndex = cursor.getColumnIndex(projection[0]);
videoId = cursor.getLong(columnIndex);
}
cursor.close();
Error: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
means your cursor has no data.
use check for cursor emptyness:
if (cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndex(projection[0]);
videoId = cursor.getLong(columnIndex);
}
cursor.close();
This scenario does not depend on phone to phone. The problem is that your cursor has no data.
You can use cursor.moveToFirst() which returns false if the cursor is empty, or use cursor.getCount() to know the number of rows in the cursor.
e.g
if (cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndex(projection[0]);
videoId = cursor.getLong(columnIndex);
}
cursor.close();
or
if (cursor.getCount() > 0) {
int columnIndex = cursor.getColumnIndex(projection[0]);
videoId = cursor.getLong(columnIndex);
}
cursor.close();
first of all you need to check the size of the cursor.
if(cursor.size()>0)
{
// do here
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(projection[0]);
videoId = cursor.getLong(columnIndex);
cursor.close();
if (videoId != -1)
videoUriStr = videosUri.toString() + "/" + videoId;
{
return videoUriStr;
}
}
I was able to get my problem solved but I still don't understand why I faced that problem with the old code. Thanks for all the help.
public static Uri getVideoContentUriFromFilePath(Context context, File fileToShare) {
String filePath = fileToShare.getAbsolutePath();
Cursor cursor = context.getContentResolver().query(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Video.Media._ID },
MediaStore.Video.Media.DATA + "=? ",
new String[] { filePath }, null);
if (cursor != null && cursor.moveToFirst()) {
int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
return Uri.withAppendedPath(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, "" + id);
} else {
if (fileToShare.exists()) {
ContentValues values = new ContentValues();
values.put(MediaStore.Video.Media.DATA, filePath);
return context.getContentResolver().insert(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
} else {
return null;
}
}
}
table 1 is MsgTable, 2nd is ContactTable & the third 1 is KeyTable...
i have to select data from first 2 tables & insert it into 3rd table??
public void setKeyValues(String msg_id, String contact_id )//insert intokeytable(msgid - contact)
{
db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put("Msg_Id", msg_id);
values.put("Contact_Id", contact_id);
i = db.insert("KeyTable", null, values);//contact
if(i != 0)
{
}
}
public ArrayList<String> getValues()
{
ArrayList<String> arr = null;
try
{
db = getReadableDatabase();
arr = new ArrayList<String>();
Cursor c1= null;
Cursor c2 = null;
c1 = db.rawQuery("select Msg_id from KeyTable where Contact_id = 1", null);
while(c1.moveToNext())
{
String msg = c1.getString(c1.getColumnIndex("MSG"));
String str = msg ;
arr.add(str);
Log.d("fuuast",str);
}
c2 = db.rawQuery("select Contact_id from KeyTable where Msg_id = 1", null);
while(c2.moveToNext())
{
String contact = c2.getString(c2.getColumnIndex("Contact"));
String str = contact ;
arr.add(str);
Log.d("fuuast",str);
}
}catch(Exception ex)
{
ex.printStackTrace();
}
return arr;
}
}