Get filename from database and use it to populate an ImageView - java

I'm creating an app which at this point needs to get a filename from a sqlite database, get the image with that filename and insert it in an ImageView, i've created this code right now, but i think i'm doing everything wrong here...
Database db = new Database(getApplicationContext());
SQLiteDatabase readableDatabase = db.getReadableDatabase();
final Cursor curFileName = readableDatabase.rawQuery("select filename from data order by id asc", null);
image = (ImageView) findViewById(R.id.image);
int filename = curFileName.getColumnIndex("filename");
String filenameString = curFileName.getString(filename);
d = Drawable.createFromPath(Environment.getExternalStorageDirectory().toString()+filenameString);
Toast.makeText(getApplicationContext(), filenameString, Toast.LENGTH_SHORT).show();
handleDrawable(d);
yes sorry, this is the exception:
04-09 13:48:16.950: E/AndroidRuntime(30802): FATAL EXCEPTION: main
04-09 13:48:16.950: E/AndroidRuntime(30802): java.lang.RuntimeException: Unable to start activity ComponentInfo{g.d.filer/g.d.filer.Favorites}: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 33

you must position the cursor before you can read
int filename = curFileName.getColumnIndex("filename");
if (cur.moveToFirst()) { // position cursor to first item. false: empty resultset
String filenameString = curFileName.getString(filename);
d = Drawable.createFromPath(Environment.getExternalStorageDirectory().toString()+filenameString);
Toast.makeText(getApplicationContext(), filenameString, Toast.LENGTH_SHORT).show();
handleDrawable(d);
...
}

Did you add
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
or
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
in the manifest file.
Because, beginning with Android 4.4, these permissions are not required if you're reading or writing only files that are private to your app. For more information, see
http://developer.android.com/guide/topics/data/data-storage.html#filesExternal

I had edited my answer. I hope this will help u. :D
if (cursor.moveToFirst()){
do{
String data = cursor.getString(cursor.getColumnIndex("filename"));
// here you have to generate Image view and add bitmap to imageview
}while(cursor.moveToNext());
}
cursor.close()

Related

Android BLE - Unable to Write to ESP32

I have been trying to get BLE to work properly. I am needing to connect to an ESP32 and send wifi credentials for the device's initial setup. I have attempted to find code that functions and works correctly but have been unable to do so.
My overall goal is to have the user input the SSID and password, then the next screen called BLEScanner then has a scanner where the user will select the device and press connect. Once the device connects, I am trying to have the application handle the data transfer without the user needing to provide any more input. In the code below, the user inputs the wifi credentials in a previous view that passes the information to BLEScanner.
I am running the application on a LG Nexus 5. It is running Android 6.0.1
I am attempting to use the following code to write to a Gatt characteristic after I discover it. When I get the list, I am parsing through the characteristics that I have discovered and attempting to write to all of the characteristics. To write to the characteristics, I am doing the following. gattCharacteristic is type BluetoothGattCharacteristic. bluetoothGatt is of type BluetoothGatt. HomeBoyEugene is the SSID of a local coffee shop, which is why is is listed in the code at the end of the question.
gattCharacteristic.setValue("SSID_AS_STRING");
gattCharacteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
bluetoothGatt.writeCharacteristic(gattCharacteristic);
I have noticed some strange behavior while trying to get this to work correctly. The first is that when I perform a permissions check, ActivityCompat.checkSelfPermission(this, BLUETOOTH_CONNECT) does not return as PERMISSION_GRANTED. I have tried to include methods to grant the permissions but they are not working. I have also included the permission in my Manifest, using the following block.
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
This is the segment of code that I am using to try to get permissions for BLUETOOTH_CONNECT:
ActivityCompat.requestPermissions(BLEScanner.this, new String[] { BLUETOOTH_CONNECT }, 0);
Okay here's where we get into the confusing behavior. I'm using the following block to read the value of the characteristic and convert it into a string so I can print it into Logcat in Android Studio
byte[] hex2 = gattCharacteristic.getValue();
String str2 = new String(hex2, StandardCharsets.UTF_8);
When I perform this operation, it is returning the value that I am attempting to write to it, i.e. SSID_AS_STRING. However, the ESP32 is not recognizing a write event. The ESP will display on its console whenever a write event occurs and we have verified that the ESP code works with other third party apps. I am trying to figure out now why it would seem that I am writing to the characteristics on my end and that I am able to read the value that I am writing to it, but the ESP is not actually writing to it.
Below is a large snippet of the code. I have a lot of print statements throughout, but figured you would like to see everything in context.
private void displayGattServices(List<BluetoothGattService> gattServices) {
if (gattServices == null) return;
String mWriteValue = "Testing";
Log.i("gattServices", String.valueOf(gattServices));
// Loops through available GATT Services.
for (BluetoothGattService gattService : gattServices) {
final String uuid = gattService.getUuid().toString();
System.out.println("Service discovered: " + uuid);
BLEScanner.this.runOnUiThread(new Runnable() {
public void run() {
Log.i("service", "Service discovered: " + uuid + "\n");
}
});
new ArrayList<HashMap<String, String>>();
List<BluetoothGattCharacteristic> gattCharacteristics =
gattService.getCharacteristics();
// Loops through available Characteristics.
for (BluetoothGattCharacteristic gattCharacteristic :
gattCharacteristics) {
final String charUuid = gattCharacteristic.getUuid().toString();
//System.out.println("Characteristic discovered for service: " + charUuid);
gattCharacteristic.setValue("HomeBoyEugene");
gattCharacteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
if (ActivityCompat.checkSelfPermission(this, BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
Log.i("Permission Check","Checking Permissions for writeCharacteristic");
ActivityCompat.requestPermissions(BLEScanner.this, new String[] { BLUETOOTH_CONNECT }, 0);
}
bluetoothGatt.writeCharacteristic(gattCharacteristic);
Log.i("characteristics", "Characteristic discovered for service: " + charUuid + "\n");
Log.i("read characteristics", String.valueOf(bluetoothGatt.readCharacteristic(gattCharacteristic)));
byte[] hex2 = gattCharacteristic.getValue();
String str2 = new String(hex2, StandardCharsets.UTF_8);
Log.i("value", String.valueOf(str2));
Log.i("spacer", "----------------------------------------");
}
Log.i("BREAK","=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
// Second loop to try to read what was written to the characteristics in the previous for loop
for (BluetoothGattCharacteristic gattCharacteristic :
gattCharacteristics) {
byte[] hex2 = gattCharacteristic.getValue();
String str2 = new String(hex2, StandardCharsets.UTF_8);
Log.i("value", String.valueOf(str2));
}
Log.i("BREAK","=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=/");
}
}
Any and all help is much appreciated. I don't really know how to word what I'm asking but I'm out of ideas on how to continue with debugging this. Thanks!

CursorWindow: Window is full

I'm new and after days, maybe I found that I have this issue, I have a very big data in a big listView
W/CursorWindow: Window is full: requested allocation 1432389 bytes, free space 750700 bytes, window size 2097152 bytes
E/CursorWindow: Failed to read row 0, column 0 from a CursorWindow which has 0 rows, 64 columns.
W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x420aeda0)
03-03 15:50:00.162 16239-16239/id.co.bumisentosa.yantek E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IllegalStateException: Couldn't read row 0, col 0 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
I have read some same issue
android java.lang.IllegalStateException: Couldn't read row 0, col 0 from CursorWindow
And I found my issue is my image in blob (byte) will not load into my listView.
Then how can I solve my cameraIntent and save it to a specific folder then put it in database and load it in ListView. I really need your help and by examples. Thank You
What I was use is like this
public void openCamera(int resultCode) {
Inspection_JTR_Fragment_Foto_Tab.gallery = false;
File image = new File(appFolderCheckandCreate(resultCode), "img" + getTimeStamp()
+ ".jpg");
Uri uriSavedImage = Uri.fromFile(image);
id.co.bumisentosa.yantek.fragment_JTM.Inspection_JTM_Fragment_Foto_Tab.cameraImagePath = image.getAbsolutePath();
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
i.putExtra("return-data", true);
startActivityForResult(i, resultCode);
}
private String appFolderCheckandCreate(int resultCode) {
String appFolderPath = "";
File externalStorage = Environment.getExternalStorageDirectory();
switch (resultCode) {
case 1:
if (externalStorage.canWrite()) {
appFolderPath = externalStorage.getAbsolutePath() + "/yantek-babel-android/jtr/Keseluruhan Tiang";
File dir = new File(appFolderPath);
if (!dir.exists()) {
dir.mkdirs();
}
} else {
}
break;
}
return appFolderPath;
}
And save it to database
public boolean onOptionsItemSelected(MenuItem item) {
final int id = item.getItemId();
if (id == R.id.action_upload) {
// Upload data ke server
imageArray = Inspection_JTM_Fragment_Foto_Tab.getimageArray();
imageArray_2 = Inspection_JTM_Fragment_Foto_Tab.getimageArray_2();
databaseHandler.saveTest(new ItemsDetails(
imageArray,
imageArray_2
));
}
return super.onOptionsItemSelected(item);
}
my database
public String saveTest(ItemsDetails details) {
try {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
// cv.put(KEY_ID, post.getId());
// cv.put(KEY_ID, "null");
cv.put(COL_LOCATION_ID, details.getunitID());
cv.put(COL_SECTION_ID, details.getjaringanID());
cv.put(COL_INSPECTION_DATE, details.gettanggalInspeksi());
cv.put(COL_INSPECTION_TYPE_ID, details.gettipeInspeksiID());
cv.put(COL_PHOTO_ENTIRE_PATH, details.getimageArray());
cv.put(COL_PHOTO_ISOLATOR_PATH, details.getimageArray_2());
cv.put(COL_POLE_NO, details.getnoTiang());
cv.put(COL_POLE_IRON, details.gettiangBesi());
cv.put(COL_POLE_CONCRETE, details.gettiangBeton());
cv.put(COL_POLE_WOOD, details.gettiangKayu());
cv.put(COL_POLE_CONDITION_BROKEN, details.getkondisiTiangRetak());
cv.put(COL_POLE_CONDITION_TILT, details.getkondisiTiangMiring());
cv.put(COL_POLE_CONDITION_SHIFT, details.getkondisiTiangPindah());
cv.put(COL_CROSS_ARM_TWIST, details.getcrossArmMelintir());
cv.put(COL_CROSS_ARM_RUST, details.getcrossArmKarat());
cv.put(COL_CROSS_ARM_TILT, details.getcrossArmMiring());
cv.put(COL_ARM_TIE_REPAIR, details.getarmTiePerbaiki());
cv.put(COL_ARM_TIE_RUST, details.getarmTieKarat());
cv.put(COL_ARM_TIE_BRACE, details.getarmTiePasang());
cv.put(COL_ISOLATOR_FULCRUM_R_LEAK, details.getisolatorTumpuRGompel());
cv.put(COL_ISOLATOR_FULCRUM_R_BROKEN, details.getisolatorTumpuRPecah());
cv.put(COL_ISOLATOR_FULCRUM_S_LEAK, details.getisolatorTumpuSGompel());
cv.put(COL_ISOLATOR_FULCRUM_S_BROKEN, details.getisolatorTumpuSPecah());
cv.put(COL_ISOLATOR_FULCRUM_T_LEAK, details.getisolatorTumpuTGompel());
cv.put(COL_ISOLATOR_FULCRUM_T_BROKEN, details.getisolatorTumpuTPecah());
cv.put(COL_ISOLATOR_PULL_R_LEAK, details.getisolatorTarikRGompel());
cv.put(COL_ISOLATOR_PULL_R_BROKEN, details.getisolatorTarikRPecah());
cv.put(COL_ISOLATOR_PULL_S_LEAK, details.getisolatorTarikSGompel());
cv.put(COL_ISOLATOR_PULL_S_BROKEN, details.getisolatorTarikSPecah());
cv.put(COL_ISOLATOR_PULL_T_LEAK, details.getisolatorTarikTGompel());
cv.put(COL_ISOLATOR_PULL_T_BROKEN, details.getisolatorTarikTPecah());
cv.put(COL_ARRESTER_R_BROKEN, details.getarresterRusakR());
cv.put(COL_ARRESTER_S_BROKEN, details.getarresterRusakS());
cv.put(COL_ARRESTER_T_BROKEN, details.getarresterRusakT());
cv.put(COL_CONDUCTOR_R_BUYER, details.getkonduktorRBuyer());
cv.put(COL_CONDUCTOR_R_LOOSE, details.getkonduktorRKendor());
cv.put(COL_CONDUCTOR_S_BUYER, details.getkonduktorSBuyer());
cv.put(COL_CONDUCTOR_S_LOOSE, details.getkonduktorSKendor());
cv.put(COL_CONDUCTOR_T_BUYER, details.getkonduktorTBuyer());
cv.put(COL_CONDUCTOR_T_LOOSE, details.getkonduktorTKendor());
cv.put(COL_CONNECTOR_PG_R_35MM, details.getkonektorPGR35mm());
cv.put(COL_CONNECTOR_PG_R_70MM, details.getkonektorPGR70mm());
cv.put(COL_CONNECTOR_PG_R_150MM, details.getkonektorPGR150mm());
cv.put(COL_CONNECTOR_PG_S_35MM, details.getkonektorPGS35mm());
cv.put(COL_CONNECTOR_PG_S_70MM, details.getkonektorPGS70mm());
cv.put(COL_CONNECTOR_PG_S_150MM, details.getkonektorPGS150mm());
cv.put(COL_CONNECTOR_PG_T_35MM, details.getkonektorPGT35mm());
cv.put(COL_CONNECTOR_PG_T_70MM, details.getkonektorPGT70mm());
cv.put(COL_CONNECTOR_PG_T_150MM, details.getkonektorPGT150mm());
cv.put(COL_BENDING_WIRE_R, details.getbendingWireR());
cv.put(COL_BENDING_WIRE_S, details.getbendingWireS());
cv.put(COL_BENDING_WIRE_T, details.getbendingWireT());
cv.put(COL_ULTRASONIC_R, details.getultrasonicR());
cv.put(COL_ULTRASONIC_S, details.getultrasonicS());
cv.put(COL_ULTRASONIC_T, details.getultrasonicT());
cv.put(COL_GSW_EXIST, details.getgswAda());
cv.put(COL_GSW_NOT_EXIST, details.getgswTidakAda());
cv.put(COL_TREE_EXIST, details.getpohonAda());
cv.put(COL_TREE_NOT_EXIST, details.getpohonTidakAda());
cv.put(COL_LONGITUDE, details.getlongitude());
cv.put(COL_LATITUDE, details.getlatitude());
cv.put(COL_SUGGESTION, details.getSaran());
cv.put(COL_DESCR, details.getketerangan());
db.insert(INSPECTIONS_MV_TABLE_NAME, null, cv);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return getNewTestID();
}
Then how can I solve my cameraIntent and save it to a specific folder
then put it in database and load it in ListView. I really need your
help and by examples.
In short you can't. Although you can store the image in the database you cannot retrieve it from the database because it is too large to fit into a CursorWindow which has a limitation of 2MB (2097152).
The image itself is around 1432389 bytes but the CursorWindow only has 750700 bytes. So as 1432389 is greater than 750700 image (blob) it can't be extracted.
You can get around the issue if you :-
save it to a specific folder, then
save the path (or part of the path) in the database rather than the image, and then
extract the path and then get the image via the path when loading the ListView.

How to get playlist by name in android default music player?

I want to play songs of a playlist name "myPlaylist" from Android music player in my Application i searched on internet that plays songs of selected playlist we can select playlist by ID i have 3 playlists in my GenyMotion i pass
PlaySongsFromAPlaylist(0);
the 0 for first playlist
my method is
public void PlaySongsFromAPlaylist(int playListID){
String[] ARG_STRING = {MediaStore.Audio.Media._ID,MediaStore.Audio.Media.DATA,MediaStore.Audio.Media.DISPLAY_NAME,MediaStore.Video.Media.SIZE,android.provider.MediaStore.MediaColumns.DATA};
Uri membersUri= MediaStore.Audio.Playlists.Members.getContentUri("external", playListID);
Cursor songsWithingAPlayList = this.managedQuery(membersUri, ARG_STRING, null, null, null);
int theSongIDIwantToPlay = 0; // PLAYING FROM THE FIRST SONG
if(songsWithingAPlayList != null)
{
songsWithingAPlayList.moveToPosition(theSongIDIwantToPlay);
String DataStream = songsWithingAPlayList.getString(4);
PlayMusic(DataStream);
songsWithingAPlayList.close();
}
}
but i am geting error
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.xample.playfromplaylist/com.xample.playfromplaylist.MainActivity}: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
what is the problem can anyone help?

Parsing URL error

It didn't seem like there was a post about this, so here goes. I've been working on a simple app to grab my time table from my school, and get it on my phone. Currently I'm working on the port on android but I've hit an issue. I get the error:
java.io.IOException: -1 error loading URL urladress.
Code:
public void updateTimeTable(){
//Get UID and Birthday
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String uid = prefs.getString("uid", "000000");
String fods = prefs.getString("fodsdag", "000000");
//Set URL
String url = "http://unv1.aalborg-stu.dk/cgi-bin/elevskema.pl?ugen=0&unavn=" + uid + "&fodsdag=" + fods;
try {
Document doc = Jsoup.connect(url).get();
Elements td = doc.getElementsByTag("td");
//ArrayList<String> tdArray = new ArrayList<String>();
// for (Element tds : td) {
// String tdText = tds.text();
// tdArray.add(tdText);
//}
//String[] data = tdArray.toArray(new String[tdArray.size()]);
} catch (IOException e ){
Log.e("Parser", "shite", e);
}
Context context = getApplicationContext();
CharSequence text = url;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
I've commented some lines out to identify where the issue is, and it seems it's at the actual parsing. Anywho, screenshot of the error I get:
Screenshot
I got about 4 days worth of Java experience so forgive me if it's something silly.
Best Regards
Hmm.. hard to say like that, but in a lucky guess, did you set the internet permission in the manifest.xml ?
<uses-permission
android:name="android.permission.INTERNET" />

Update doesn't work when using ContentResolver to update Contact Groups

I have this code for update:
public Boolean update() {
try {
data.put(ContactsContract.Groups.SHOULD_SYNC, true);
ContentResolver cr = ctx.getContentResolver();
Uri uri = ContentUris.withAppendedId(ContactsContract.Groups.CONTENT_URI, Long.parseLong(getId()));
int mid = cr.update(uri, data,_ID+"="+getId(), null);
// notify registered observers that a row was updated
ctx.getContentResolver().notifyChange(
ContactsContract.Groups.CONTENT_URI, null);
if (-1 == mid)
return false;
return true;
} catch (Exception e) {
Log.v(TAG(), e.getMessage(), e);
return false;
}
}
I have values in data, I double checked, and for some reason the values are nut pushed out. I also ran a cur.requery(); and I am having
<uses-permission android:name="android.permission.WRITE_CONTACTS"></uses-permission>
EDIT 1
One thing to mention, that I need to use:
data.put(ContactsContract.Groups.SHOULD_SYNC, 1);
as the true value there is not accepted, although that is returned when you check the ContentValues.
Ok, I figured it down too:
SQLiteException: no such column: res_package: , while compiling: UPDATE groups SET sync4=?, sync3=?, sync2=?, group_visible=?, system_id=?, sync1=?, should_sync=?, deleted=?, account_name=?, version=?, title=?, title_res=?, _id=?, res_package=?, sourceid=?, dirty=?, notes=?, account_type=? WHERE _id=20
The weird thing is that, this column is returned when you Query the content provider. I made the queries to use all returned columns, so I need to make this work somehow.
I just made something similar work. Instead of
int mid = cr.update(uri, data,_ID+"="+getId(), null);
use
int mid = cr.update(uri, data,null, null)
your uri already has embedded ID information.

Categories