System.err when fetching an image in Android - java

I'm using a messenger service to asynchronously fetch an image from a URL but LogCat is throwing a strange error message:
W/System.err(26180): Error reading from ./org/apache/harmony/awt/www/content/image/png.class
- or -
W/System.err(26180): Error reading from ./org/apache/harmony/awt/www/content/image/jpeg.class
The funny thing is that everything works. The image is successfully being decoded into a Bitmap on the first try.
Here is my code:
#Override
public void onHandleIntent(Intent i) {
int position = (Integer)i.getExtras().get(EXTRA_POSITION);
String imageUrl = (String)i.getExtras().get(EXTRA_URL);
Messenger messenger = (Messenger)i.getExtras().get(EXTRA_MESSENGER);
Message msg = Message.obtain();
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageUrl).getContent());
msg.arg1 = Activity.RESULT_OK;
msg.arg2 = position;
msg.obj = bitmap;
} catch(Exception e) {
Log.e("RSSForHC", "Exception getting image", e);
msg.arg1 = Activity.RESULT_CANCELED;
msg.obj = e;
}
try {
messenger.send(msg);
} catch (Exception e) {
Log.w("RSSForHC","Exception sending results to activity", e);
}
}
The error is definently being thrown on this line:
bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageUrl).getContent());
Since everything works my question is whether or not it's acceptable to ignore this error? Does anyone know why this error is being thrown and how I can possibly correct it or handle it?

This worked for me to get rid of those messages. Of course Michael may still be right that ignoring them is okay.
I replaced
Drawable.createFromStream(((InputStream)new URL(urlString).getContent()), "name");
with
Drawable.createFromStream((new URL(url)).openConnection().getInputStream(), "name");
Of course this isn't exactly your code, but I suspect that replacing getContent() with openConnection().getInputStream() would work for you too.

It's obviously an error in the Apache/Harmony framework.
I think you may ignore it, you can't change the code there, even if you want :)
It's kinda a logging stuff for the apache/harmony developers, you don't have to care about this.

Related

How can i get video thumbnail from remote url in android

I am trying to get thumbnail from a URL Example: "https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-mp4-file.mp4" It is possible in IOS using AVAssets. The way i am doing it is using the following function
public static Bitmap retriveVideoFrameFromVideo(String videoPath) throws Throwable {
Bitmap bitmap = null;
MediaMetadataRetriever mediaMetadataRetriever = null;
try {
mediaMetadataRetriever = new MediaMetadataRetriever();
if (Build.VERSION.SDK_INT >= 14)
mediaMetadataRetriever.setDataSource(videoPath, new HashMap<String, String>());
else
mediaMetadataRetriever.setDataSource(videoPath);
// mediaMetadataRetriever.setDataSource(videoPath);
bitmap = mediaMetadataRetriever.getFrameAtTime(1, MediaMetadataRetriever.OPTION_CLOSEST);
} catch (Exception e) {
e.printStackTrace();
throw new Throwable("Exception in retriveVideoFrameFromVideo(String videoPath)" + e.getMessage());
} finally {
if (mediaMetadataRetriever != null) {
mediaMetadataRetriever.release();
}
}
return bitmap;
}
But the issue is it's slow down the recycleview and load image again and again.
I have solve the issue by using GLide 4.x. I have find another solution by using MediaMetadataRetriever. But it's not feasible to use MediaMetadataRetriever in a recycle view because it runs on main thread and cause ANR. The code that works for me is below.
RequestOptions requestOptions = new RequestOptions();
Glide.with(context)
.load("Your URL")
.apply(requestOptions)
.thumbnail(Glide.with(context).load("Your URL"))
.into(holder.img_video_attachment_preview);
Your own answer worked for me, and tweaking it a little bit, I ended up with a slightly shorter version. Although you might have had your own reasons for doing it that way...
GlideApp.with(context)
.load(item.videoURL) // your video url
.into(image_view)

Error code (1, -2147483648) in Android MediaPlayer

I'm trying to implement a simple alarm in android by using the
MediaPlayer. However, every time I try to prepare() it, I get an error.
Here's my code. I'm a total beginner concerning Java and Android so
perhaps I'm doing something inherently wrong.
private void playDiscreteAlarm()
{
alarmSound = new MediaPlayer();
alarmSound.setAudioStreamType(AudioManager.STREAM_RING);
Resources res=context.getResources();
AssetFileDescriptor fd = res.openRawResourceFd(R.raw.discrete_alarm);
try {
alarmSound.setDataSource(fd.getFileDescriptor());
fd.close();
alarmSound.setLooping(true);
alarmSound.prepare();
alarmSound.start();
}
catch (IOException e)
{
Log.d("error\n");
}
}
The weird thing is that this worked once and after that stopped working.
It works when I use MediaPlayer.create() however I need to use the ringer volume instead of the media volume, and I believe this is the way to do it.
I fixed the problem, though I'm not sure what caused it. I just used a different and maybe slightly simpler method.
Here's what I did:
private void playDiscreteAlarm()
{
String filename = "android.resource://" + context.getPackageName() + "/raw/discrete_alarm";
alarmSound = new MediaPlayer();
alarmSound.setAudioStreamType(AudioManager.STREAM_RING);
try {
alarmSound.setDataSource(context, Uri.parse(filename));
alarmSound.setLooping(true);
alarmSound.prepare();
alarmSound.start();
}
catch (Exception e)
{
System.out.println(e);
}
}
Thanks !

Decoding Bitmap stream failed

I'm trying to work my through "Sam's Teach Yourself Android Application Development in 24 Hours" and have become stuck in hour 12. The problem appears to be in this section:
private Drawable getQuestionImageDrawable(int questionNumber) {
Drawable image;
URL imageUrl;
try {
// Create a Drawable by decoding a stream from a remote URL
imageUrl = new URL(getQuestionImageUrl(questionNumber));
InputStream stream = imageUrl.openStream();
Bitmap bitmap = BitmapFactory.decodeStream(stream);
image = new BitmapDrawable(getResources(), bitmap);
} catch (Exception e) {
Log.e(TAG, "Decoding Bitmap stream failed");
image = getResources().getDrawable(R.drawable.noquestion);
}
return image;
}
The questionNumber and getQuestionImageUrl() have been tested and are returning what I believe are the correct values(1 and http://www.perlgurl.org/Android/BeenThereDoneThat/Questions/q1.png). There is an image at that url, but I always get the exception. I have tried several variations but when none of them worked I went back to this code from the book. What am I doing wrong here?
I'm new to java and android, so I'm probably missing something simple. I have had many other problems with the code in the book and the updated code from the website (all of which have been solved either here or with developer.android.com). This is my first question, so if I failed to provide any information please let me know.
I would do the following and it might work:
private Drawable getQuestionImageDrawable(int questionNumber) {
Drawable image;
URL imageUrl;
try {
// Create a Drawable by decoding a stream from a remote URL
imageUrl = new URL(getQuestionImageUrl(questionNumber));
HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream stream = conn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(stream);
image = new BitmapDrawable(getResources(), bitmap);
} catch (Exception e) {
Log.e(TAG, "Decoding Bitmap stream failed");
image = getResources().getDrawable(R.drawable.noquestion);
}
return image;
}
Make sure you do this kind of heavy operations in a background thread insteaad of the main one and had INERNET permission to your application's manifest.
Let me know about your progress.
Probably the exception is because you are making a network connection form the app ui thread. That works on older Android versions but not in the newer.
Take a look to Android network operation section.
The main thing to do is use an AsyncTask

Java / Android: Get Facebook User Info From Graph Api, Display in TextView

I'm trying to learn Java right now and I've jumped in the deep end by starting with the Android Faceobok API. Right now, I'm trying to get some information from my graph data (a friend in this case) and display it in a text view. This seems rather trivial but it has been anything but.
JSONObject json_data = null;
try
{
JSONObject response = Util.parseJson(facebook.request("/me/friends", mBundle, "GET")); // Get a friend information from facebook
JSONArray jArray = response.getJSONArray("data");
json_data = jArray.getJSONObject(0);
String name = json_data.getString("name");
mText.setText(name);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (JSONException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (FacebookError e)
{
e.printStackTrace();
}
The TextView doesn't change when I do this and I'm not exactly sure where I've gone wrong.
As an aside, there is a shortage of good Android Facebook API tutorials out there. Most are hundreds of lines of code; I don't have the energy or patience to consume all of that.
I have a feeling your initial request isnt working properly. you should try this line instead:
JSONObject response = Util.parseJson(facebook.request("me/friends"));
Firstly I think in your initial request, it should be "me/friends" rather than "/me/friends". Secondly you dont necessarily need the mBundleor "GET" parameters in what you're trying to achieve. Have you even defined parameters in mBundle? You're also getting information from the request method, so the "GET" parameter isn't necessary.
Try the line i just wrote, as it is simpler and will get your friends information. The rest of your code is fine.
Your assertion about being "trivial" is essentially true, but generally speaking "jumping into the deep end" rarely results in anything other than a drowning.
I'm going to be "that guy" and recommend you actually get to the point of having a general understanding and minimal competency in Java before tackling someone else's API. Once you know how Java works - the "PME" ... properties, methods, and events - learning anyone's API becomes just a question of following the proper steps.
Besides that little bit of PS, answer the following:
1) received data from your source?
2) what thread are you invoking this on?
3) any of the objects null?
4) any exceptions being thrown when you look in the Console or Log (print those out to the Log versus your current implementation)?
And, not for nothing, but if you don't have the time or patience to learn the "how's and why's" of an API or software dev in general then this will be a long exercise for you if the work ever becomes non-trivial.
Just one man's opinion who also has attempted to drink from fire hose before.
Update: Here's all of my code:
public class FriendsActivity extends Activity {
/** Called when the activity is first created. */
Facebook facebook = new Facebook("194653157245506");
TextView mText;
Bundle mBundle;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mText = (TextView) this.findViewById(R.id.text);
facebook.authorize(this, new String[] {"offline_access", "user_interests", "friends_interests"},
new DialogListener() {
#Override
public void onComplete(Bundle values) {}
#Override
public void onFacebookError(FacebookError error) {}
#Override
public void onError(DialogError e) {}
#Override
public void onCancel() {}
});
JSONObject json_data = null;
try
{
JSONObject response = Util.parseJson(facebook.request("/me/friends", mBundle, "GET")); // Get a friend information from facebook
JSONArray jArray = response.getJSONArray("data");
json_data = jArray.getJSONObject(0);
String name = json_data.getString("name");
Log.i("friend is", name);
mText.setText(name);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (JSONException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (FacebookError e)
{
e.printStackTrace();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
}
I may be a little off key. but I have done facebook api development in C#, and i am wondering if you have had the client login.
Facebook works with OAuth to allow you to authorize through them for a client. (Even your own account as the client) therefore you may need to login.
Another thing to look at is, do you have the TextView that is in the Activity that is being displayed..
Try putting in a breakpoint and looking over the code as it is executing, Debug View is great for that.
see if your response is being populated.
make sure you have the Text from the Activity.
mText = (TextView)findViewById(R.id.TextView1); //or whatever you named it.
Also the LogCat should show you the stack trace for any errors that occur, maybe posting some of the output would help

Android Load Camera image as Bitmap

I am using BitmapFactory.decodeFile to load Bitmaps of images into my application. However, the function returns null on large images (such as those from the camera). The filepath is definitely correct, I just can't figure out why it would return null. I tried supersampling, but it didn't seem to help.
Does anyone have any idea why it would do this or how I could more easily load images taken from the camera into a Bitmap?
Here's the code I am using:
public static Bitmap loadBitmap(String filePath){
Bitmap result = BitmapFactory.decodeFile(filePath);
if(result == null){
if(filePath.contains(".jpg") || filePath.contains(".png")){
//This is the error that occurs when I attempt to load an image from the Camera DCIM folder or a large png I imported from my computer.
Utils.Toast("Could not load file -- too big?");
} else {
Utils.Toast("Could not load file -- image file type is not supported");
}
}
return result;
}
You will need to provide more info about your problem, such as a snippet of code that you are using. If you want to know when/why the BitmapFactory.decodeFile method would return null, you can read directly its source code: http://casidiablo.in/BitmapFactory
For example, one of the reasons that causes BitmapFactory.decodeFile to return null is if there's a problem while openning the file. Curiously, the developers dont't log anything with such a problem... look at the comment "do nothing. If the exception happened on open, bm will be null."
public static Bitmap decodeFile(String pathName, Options opts) {
Bitmap bm = null;
InputStream stream = null;
try {
stream = new FileInputStream(pathName);
bm = decodeStream(stream, null, opts);
} catch (Exception e) {
/* do nothing.
If the exception happened on open, bm will be null.
*/
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
// do nothing here
}
}
}
return bm;
}
As you can see, the BitmapFactory.decodeFile does not work standalone... but it uses some other methods of the BitmapFactory class (for instance, BitmapFactory.decodeStream, BitmapFactory.nativeDecodeStream, BitmapFactory.finishDecode, etc.). The problem could be on one of those methods, so if I were you, I would try to read and understand how they work so that I could know in which cases they return null.
Maybe inSampleSize option can help you?
Strange out of memory issue while loading an image to a Bitmap object
It may sound obvious, but check that your filePath actually points to a file. You mention that you are using a file manager to select the image to open - it's possible that the file manager is returning a path to a content provider instead of a file.
There is a more robust way to open files using the ContentResolver class, which can open an InputStream to a content provider, file, or resource, without you needing to know in advance what kind of path you are passing it.
The only catch is that you need to pass a Uri object on the call to openInputStream() instead of a String.
public static Bitmap loadBitmap(String filePath, Context c) {
InputStream inStream;
try {
inStream = c.getContentResolver().openInputStream( Uri.parse(filePath) );
} catch (FileNotFoundException e) {
// handle file not found
}
return BitmapFactory.decodeStream(inStream);
}
This also happens to be how the ImageView widget attempts to load images when you use its setImageURI method.

Categories

Resources