How to use getContentResolver().query for file? - java

I have one java.io.File pointed to /storage/files/pic.jpg (for brevity) called mFile
When I try to query for the file using
Uri photoUri = Uri.fromFile(mFile);
Cursor cursor = context.getContentResolver().query(photoUri,
new String[] { MediaStore.Images.ImageColumns.ORIENTATION }, null, null, null);
cursor ends up null, would expect cursor not not be null.
photoUri.to_String returns file:///storage/files/pic.jpg
I know the file exists, since i can load it with
BitmapFactory.decodeFile(mFile.getAbsolutePath());
or open an InputStream with the same Uri
InputStream is = context.getContentResolver().openInputStream(photoUri);
I get the feeling that photoUri is malformed somehow, I have seen posts saying it should be content://..., but they also refers to obsolete versions of the android sdk.

Related

Cordova captureImage Fails FileNotFoundException

I'm having trouble getting capture.captureImage to work. Using Cordova 3.5.0, org.apache.cordova.file-1.3.0, org.apache.cordova.media-capture-0.3.3. Debugging in Eclipse shows that
that.cordova.getActivity().getContentResolver().insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
in onActivityResult returns uri = content://media/external/images/media/nnnn but
OutputStream os = that.cordova.getActivity().getContentResolver().openOutputStream(uri)
throws a FileNotFoundException
It appears that the issue is that the uri returned by the insert method is not properly resolved by openOutputStream. What worked for me was instead of calling openOutputStream, do the following:
String dfname = getRealPathFromURI(uri);
File df = new File(dfname);
File dfolder = df.getParentFile();
if(!dfolder.exists()) dfolder.mkdirs();
if(!df.exists()) df.createNewFile();
FileOutputStream os = new FileOutputStream(df);
private String getRealPathFromURI(Uri contentURI) {
Cursor cursor = this.cordova.getActivity().getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
return contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
}
You'll need to import java.io.FileOutputStream, if not already done. I thank Isaac Zais for his answer that pointed me in the right direction and for the getRealPathFromURI code.
It would be great if a Cordova developer could explain if this is a bug in org.apache.cordova.media-capture or somewhere else or if there is a way to get this to work without having to modify the latest version of the plugin.
Tested on Samsung Galaxy S5, Android 4.4.4.
I don't have enough reputation to comment on your answer, but dp22193's patch works great! Please see https://issues.apache.org/jira/browse/CB-7768 for the bug report and the patch attached to it.

How to get access to object

I am new to java.
I have a directory with a txt file (R.raw). I want to get access with a command
InputStream in_s = res.openRawResource(R.raw.itemname);
where itemname is a dynamic string with a filename from a previous activity.
How do I can get open file in R.raw by a string "n0.txt"?
In javascript I can implement it like R.raw["n0.txt"] or R.raw.itemname.
Thanks in advance.
You need to use method getIdentifier().
Context context;
Resources res;
int itemId = res.getIdentifier("itemname", "raw", context.getPackageName());
InputStream is = res.openRawResource(itemId);
Original post here.

ServiceManager.getServiceNames() returns null. Why?

I had a little app which was able to save and load files. Then I decided to try Java Web Start, so that I needed to rewrite JFileChooser usage to jnlp stuff.
Looking at http://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/uiswing/examples/components/JWSFileChooserDemoProject/src/components/JWSFileChooserDemo.java I've tried to rewrite my code.
Here what I came with
FileSaveService fss = null;
FileContents fileContents = null;
ByteArrayInputStream is = new ByteArrayInputStream(
(new String("Saved by JWSFileChooserDemo").getBytes()));
try {
String[] services = ServiceManager.getServiceNames();
fss = (FileSaveService)ServiceManager.
lookup("javax.jnlp.FileSaveService");
}
catch (UnavailableServiceException exc) { }
if (fss != null) {
try {
fileContents = fss.saveFileDialog(null, null, is, null);
}
and so on.
At first there were no ServiceManager.getServiceNames call, and my the ServiceManager.lookup returned null. So I decided to get the service list, and getServiceNames returns null also.
How can I make it to find FileSaveService? Where does the method looks for this service, and shouldn't I write some extra stuff somewhere to declare that I need that service?
UPD: I've tried to run JWSFileChooserDemo from the oracle's link above, and it doesn't work. Same thing with ServiceManager.lookup that returns null.

How do I check if ringtone pointed by uri exists?

I'm able to play a ringtone using the following code
rone = RingtoneManager.getRingtone(this.getContext(), Uri.parse(one));
rone.play();
How do I check if the audio file pointed by uri exists? When the user deletes a file from their phone, I'm not able to play the ringtone and it crashes.
getRingtone() will return null if the ringtone does not exist.
Always check that a returned value is not null, this is a good practice whenever you call methods that might return null value. This will prevent a whole lot of NullPointerException
Try to use getRingtonePosition() method instead of getRingtone():
final RingtoneManager rm = new RingtoneManager(preference.getContext());
final Uri loadedRingtoneUri = Uri.parse(ringtoneUriString);
final int pos = rm.getRingtonePosition(loadedRingtoneUri);
// if loaded ringtone uri is valid, use it or use default
final Ringtone ringtone = RingtoneManager.getRingtone(preference.getContext(),
(pos != -1) ? loadedRingtoneUri :
Settings.System.DEFAULT_RINGTONE_URI);

Android set ringtone failure

I try the following code and it doesn't set the ringtone. The logcat entry for "ff" says null so I guess the URI isnt being concatenated properly?, I cant seem to figure out where in my code I am going wrong.
String filepath =Environment.getExternalStorageDirectory().toString()+"//media//audio//ringtones//bluemoon.mp3";
File ringtoneFile = new File(filepath);
ContentValues content = new ContentValues();
content.put(MediaStore.MediaColumns.DATA,ringtoneFile.getAbsolutePath());
content.put(MediaStore.MediaColumns.TITLE, "test");
content.put(MediaStore.MediaColumns.SIZE, 215454);
content.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mpeg");
content.put(MediaStore.Audio.Media.ARTIST, "artist");
content.put(MediaStore.Audio.Media.DURATION, 230);
content.put(MediaStore.Audio.Media.IS_RINGTONE, true);
content.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
content.put(MediaStore.Audio.Media.IS_ALARM, false);
content.put(MediaStore.Audio.Media.IS_MUSIC, false);
Log.i("BOOM", "the absolute path of the file is :"+ringtoneFile.getAbsolutePath());
Uri uri = MediaStore.Audio.Media.getContentUriForPath(
ringtoneFile.getAbsolutePath());
Uri newUri = getApplicationContext().getContentResolver().insert(uri, content);
Uri ringtoneUri = newUri;
Log.i("ff","the ringtone uri is :"+ringtoneUri);
RingtoneManager.setActualDefaultRingtoneUri(getApplicationContext(),
RingtoneManager.TYPE_RINGTONE,newUri);
Its possible data is not accurate for the file and its causing a problem. You may need to change:
audio/mpeg to audio/mp3
and duration to the actual duration of the file.
Another thing you may want to fix is your ringtone file declaration statement, try changing it to match this:
File k = new File(path, "mysong.mp3");
Also, I have a feeling your path is broken too..
Environment.getExternalStorageDirectory().toString()+"//media//audio//ringtones//bluemoon.mp3"
why with the two "//"?
It should be (for example):
../sdcard/media/ringtone

Categories