I have an Android application that loading some information and one picture like a blog, but sometimes I got duplicates picture, I don't know what is the problem, but sometimes it works good.
Someone here can help me ?
Here's the code below:
"endereco" is the URL of picture and "view" is the context that I pass on the class that extends activity"
public void loadImg(final View view , final String endereco){
Thread nova = new Thread()
{
public void run() {
Bitmap img = null;
try
{
URL url = new URL(endereco);
HttpURLConnection conexao = (HttpURLConnection) url.openConnection();
InputStream input = conexao.getInputStream();
img = BitmapFactory.decodeStream(input);
Log.i("Funcionou","Foto: " + endereco);
} catch (Exception ex){
Log.i("Erro",ex.toString());
}
final Bitmap imgAux = img;
handler.post(new Runnable() {
#Override
public void run() {
ImageView imageView = (ImageView) view.findViewById(R.id.txtfoto);
imageView.setImageBitmap(imgAux);
}
});
}
};
nova.start();
nova.currentThread().interrupt();
}
If you are downloading an image from a wbepage or server i wouldnt do it in a thread give it its own AsyncTask it gives you a whole load of methods that allow you to better control over what you are downloading and what to do with it after it has been downloaded.
Check out the Android dev Docs http://developer.android.com/reference/android/os/AsyncTask.html
Related
I'm having a problem with android's camera2 API.
My end goal here is to have a byte array which I can edit using opencv, whilst displaying the preview to the user (e.g. an OCR with a preview).
I've create a capture request and added an ImageReader as a target. Then on the OnImageAvailableListener, i'm getting the image, transforming it to a bitmap and then display it on an ImageView (and rotating it).
My problem is that after a few seconds, the preview stalls (after gradually slowing down) and in the log om getting the following error: E/BufferItemConsumer: [ImageReader-1225x1057f100m2-18869-0] Failed to release buffer: Unknown error -1 (1)
As you can see in my code, I have already tried closing the img after getting my byte[] from it.
I've also tried clearing the buffer.
I've tried closing the ImageReader but that of course stopped me from getting any further images (throws an exception).
Can anyone please help me understand what im doing wrong? I've been scouring google to no avail.
This is my OnImageAvailableListener, do let me know if you need more of my code to assist:
private final ImageReader.OnImageAvailableListener mOnImageAvailableListener
= new ImageReader.OnImageAvailableListener() {
#Override
public void onImageAvailable(ImageReader reader) {
Image img = reader.acquireLatestImage();
final ImageView iv = findViewById(R.id.camPrev);
try{
if (img==null) throw new NullPointerException("null img");
ByteBuffer buffer = img.getPlanes()[0].getBuffer();
byte[] data = new byte[buffer.remaining()];
buffer.get(data);
final Bitmap b = BitmapFactory.decodeByteArray(data, 0, data.length);
runOnUiThread(new Runnable() {
#Override
public void run() {
iv.setImageBitmap(b);
iv.setRotation(90);
}
});
} catch (NullPointerException ex){
showToast("img is null");
}finally {
if(img!=null)
img.close();
}
}
};
Edit - adding cameraStateCallback
private CameraDevice.StateCallback mCameraDeviceStateCallback = new CameraDevice.StateCallback() {
#Override
public void onOpened(CameraDevice cameraDevice) {
mCameraDevice = cameraDevice;
showToast("Connected to camera!");
createCameraPreviewSession();
}
#Override
public void onDisconnected(CameraDevice cameraDevice) {
closeCamera();
}
#Override
public void onError(CameraDevice cameraDevice, int i) {
closeCamera();
}
};
private void closeCamera() {
if (mCameraDevice != null) {
mCameraDevice.close();
mCameraDevice = null;
}
}
You seem to have used setRepeatingRequest() for Jpeg format. This may not be fully supported on your device, also depends on the image resolution that you choose. Normally, we use createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW) in these cases, and get YUV or raw format from ImageReader.
I would try to choose low resolution for Jpeg: maybe this will be enough to keep the ImageReader running.
I want to display image to ImageView from "http://i.imgur.com/4GLKF4Q.jpg" but The image in image URL didn't display to imageview. Can I do this?
AsyncTask
class DownloadImageTask extends AsyncTask<String, Void, byte[]> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected byte[] doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
InputStream is = (InputStream) url.getContent();
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
while ((bytesRead = is.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
return output.toByteArray();
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
protected void onPostExecute(byte[] result) {
ByteArrayInputStream imageStream = new ByteArrayInputStream(result);
Bitmap bm = BitmapFactory.decodeStream(imageStream);
bmImage.setImageBitmap(bm);
}
}
in activity
new DownloadImageTask((ImageView) newView.findViewById(R.id.thumbnail))
.execute("http://i.imgur.com/4GLKF4Q.jpg");
The image in image URL didn't display to imageview.
in Logcat :
09-23 10:26:49.410 10591-10591/com.*** D/skia: --- SkImageDecoder::Factory returned null
Update from comment : changing image server to another one solve the issue. I guess it's a i.imgur.com issue.
You shouldn't use your own image loader task, it will leak somewhere.
Two good library exist :
- Fresco (from Facebook)
- Picasso (from Square up)
There is also UniversalImageLoader (UIL).
I would suggest you to checkout Image Management Library by Facebook that is Fresco that is pretty awesome and mature as compared to other Image Loading Library.
Fresco handles all the things caching of images with 3 Tier architecture ( BITMAP_MEMORY_CACHE, ENCODED_MEMORY_CACHE and DISK_CACHE). It also reduces OOM(Out Of Memory) issues. When image in a view goes out of screen it automatically recycles the bitmap, hence releasing the memory.
Now there is an official way to load an ImageView from a URL and that is NOT to use an ImageView.
NetworkImageView—builds on ImageLoader and effectively replaces ImageView for situations where your image is being fetched over the network via URL. NetworkImageView also manages canceling pending requests if the view is detached from the hierarchy.
Images are automatically loaded in a background thread and the view updated on the UI thread. It even supports caching.
I'm pretty new to native Android development. What my app is currently doing:
Download a JSON of image urls from our server
Add an ImageView to a ListView for each image
I've gotten the JSON and am now working on using an ImageAdapter (extends BaseAdapter) to populate the ListView, but I'm running into an error:
I'm getting println needs a message during creation of the InputStream in my OpenHttpGETConnection function.
Here's my code (in order of highest to lowest with unnecessary code removed):
Once JSON Is loaded my onPostExecute code'll run to start the adapter:
private class DownloadImagesTextTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls){
return getImages(urls[0]);
}
#Override
protected void onPostExecute(String result){
JSONArray images = null;
images = new JSONArray(result);
// TURN images into array of imageviews
ListView listView = (ListView) findViewById(R.id.list);
#here----> listView.setAdapter(new ImageAdapter(getBaseContext(), images));
Log.d("DownloadTextTask", images.toString());
}
}
Here's my ImageAdapter code:
public class ImageAdapter extends BaseAdapter {
private Context context;
private JSONArray images;
public ImageAdapter(Context c, JSONArray i){
context = c;
images = i;
}
// returns an imageview view
public View getView(int position, View convertView, ViewGroup parent){
ImageView imageView = new ImageView(context);
try {
String url = "http://www.example.com/" + images.get(position);
#here----> imageView.setImageBitmap(getImageBitmap(url));
} catch (Exception e){
Log.d("LoadImage", e.getLocalizedMessage());
}
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
return imageView;
}
}
Here's my getImageBitmap function:
private Bitmap getImageBitmap(String url){
Bitmap bitmap = null;
InputStream in = null;
try {
#here----> in = OpenHttpGETConnection(url);
} catch (Exception e) {
#i_get
#this ----> Log.wtf("OpenGET", e.getMessage() + ": " + url );
#error
}
bitmap = BitmapFactory.decodeStream(in);
in.close();
return bitmap;
}
And finally, here's my OpenHttpGETConnection function:
public static InputStream OpenHttpGETConnection(String url){
InputStream inputStream = null;
HttpClient httpClient = null;
HttpResponse httpResponse = null;
httpClient = new DefaultHttpClient();
httpResponse = httpClient.execute(new HttpGet(url));
inputStream = httpResponse.getEntity().getContent();
return inputStream;
}
And here's the pertaining LogCat line: (Happens for 3 images that came through the JSON file)
A/OpenGET﹕ println needs a message: http://www.example.com/image1.jpg
The weird thing is, I use the same OpenHttpGETConnection when I load my JSON data, so I'm pretty sure that's returning a correct InputStream object. Are there some caveats when using it for text vs. binary data (jpg)?
Thanks in advance!
First of all in the adapter, in the getView() method, you're not recycling the items. Have a look on the ViewHolder pattern (http://www.javacodegeeks.com/2013/09/android-viewholder-pattern-example.html).
Then, getImageBitmap() seems to be executed on the same thread, I wonder why it doesn't crash. I guess there you download the actual image. It should be done asynchronously, and you should send a reference of the ImageView and when the download is finished you should load it into it. Of course you'll have to care about if when you put the bitmap inside the ImageView you have the good ImageView on the screen (because it might have been recycled).
To get rid of all these concerns you could just use Picasso library (http://square.github.io/picasso/) and that will do all this for you.
Just two things, is this a good simple way to grab images? also when i do try it on the android AVD nothing gets displayed on screen as well as in log_cat, no errors or crashes. Here is my code:
public class MainActivity extends Activity {
Bitmap bitmap = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{
bitmap = getBitmap("https://twimg0-a.akamaihd.net/profile_images/2275552571/image_normal.jpg");
ImageView img = (ImageView) findViewById(R.id.img);
img.setImageBitmap(bitmap);
}catch(Exception e){
}
}
public Bitmap getBitmap(String bitmapUrl) {
try {
URL url = new URL(bitmapUrl);
return BitmapFactory.decodeStream(url.openConnection().getInputStream());
}catch(Exception ex) {return null;}
}
}
try : http://code.google.com/p/android-imagedownloader/ .
You can download remote images synchronously, Asynchronously, etc. it works really good
ImageDownloader imageDownloader = new ImageDownloader();
imageDownloader.setMode(ImageDownloader.Mode.CORRECT);
ImageView imageView = (ImageView) rowView.findViewById(R.id.picture);
imageView.setLayoutParams(new GridView.LayoutParams(140, 140));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(4, 4, 4, 4);
List<ImageSize> images = this.pictures.get(position).getImages();
imageDownloader.download(images.get(images.size()-3).getSource(), imageView);
It doesn't work because your picture's url starts with HTTPS. Try to use HttpGet. Something like that.
I am writing an Android app which can take pictures and save them on the SD card. Later, I need to display the pictures in a GridView and the user can select one. This is my code to save pictures:
Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera c) {
currentPictureName = (String) getResources().getText(R.string.username)
+ System.currentTimeMillis() + ".jpg";
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(sdcardPath + currentPictureName);
outStream.write(data);
outStream.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
mCamera.startPreview();
}
}
However, none of the saved images have thumbnails to show in the GridView. How do I automatically generate thumbnails for all images that I save and add everything to MediaStore so that they can be accessed later?
Try using scanFile() function.
You must implement a media scanner connection client
private class ImageScannerClient implements MediaScannerConnection.MediaScannerConnectionClient {
#Override
public void onMediaScannerConnected() {
// Start scanning files you have in a que
}
#Override
public void onScanCompleted(String path, Uri uri) {
// Run some code, then maybe initiate scan of next file in que
}
}
In onCreate you can connect to the media scanner like so:
// Connect to media scanner
this.mediaScanner = new MediaScannerConnection(getApplicationContext(), new ImageScannerClient() );
this.mediaScanner.connect();
And at some other point you must add files to a que or something to be scanned.
Found this. This works perfectly fine, all thumbnails are automatically generated