guys. I have this code:
package com.example.httpprogress;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
public class MyPicGetTask extends AsyncTask<URL , Void, Bitmap>{
InputStream is = null;
BufferedInputStream bis = null;
Bitmap bmp = null;
#Override
protected Bitmap doInBackground(URL... urls) {
// TODO Auto-generated method stub
URL url = urls[0];
try {
URLConnection conn = url .openConnection();
conn.connect();
is = conn.getInputStream();
bis = new BufferedInputStream( is );
bmp = BitmapFactory.decodeStream( bis );
} catch (MalformedURLException e) {
} catch (IOException e) {
} finally {
try {
is.close();
bis.close();
} catch (IOException e) {
}
}
return bmp;
}
}
it fails, but if i use AsyncTask and describe this class as inner in my activity - it's ok . I can not say the reason because i can not debug, i can see that debug tab opens when it fails but it is not informative for me. Any ideas? Sorry for my noob question
that's my Activity:
package com.example.httpprogress;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
public class PicActivity extends Activity implements OnClickListener{
InputStream is = null;
BufferedInputStream bis = null;
Bitmap bmp = null;
private URL url;
//"http://192.168.0.30/03.jpg";
/*
private class getPicTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... s) {
// TODO Auto-generated method stub
try {
url = new URL("http://192.168.0.93/image.php");
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
URLConnection conn = url .openConnection();
conn.connect();
is = conn.getInputStream();
bis = new BufferedInputStream( is );
bmp = BitmapFactory.decodeStream( bis );
} catch (MalformedURLException e) {
} catch (IOException e) {
} finally {
try {
is.close();
bis.close();
} catch (IOException e) {
}
}
return null;
}
};
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pic);
final ImageView image = (ImageView) findViewById(R.id.imageView1);
image.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
///////////
try {
url = new URL("http://192.168.0.30/03.jpg");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new MyPicGetTask().execute(url);
image.setImageBitmap(bmp);
}
});
////////////////
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.pic, menu);
////////////////
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d("httpProgress", "Onclick()");
}
}
Add Log.d() code to doInBackground(...) to print out all exceptions that occur. That should tell you what's going wrong, e.g.
try {
URLConnection conn = url .openConnection();
conn.connect();
is = conn.getInputStream();
bis = new BufferedInputStream( is );
bmp = BitmapFactory.decodeStream( bis );
} catch (Exception e) {
Log.d("Async","EXCEPTION",e);
} finally {
try {
is.close();
bis.close();
} catch (IOException e) {
Log.d("Close","EXCEPTION",e);
}
}
When the MyPicGetTask is an inner class it has access to the bmp field. When you pulled it out of your activity it lost access to the bmp class field.
I would suggest reading Google's documentation and following their examples for AsyncTasks.
The bitmap you return from doInBackground should then be used to update your UI in onPostExecute.
protected void onPostExecute(Bitmap bitmap) {
image.setImageBitmap(bitmap);
}
Your asyncTask subclass needs access to image in order to update the UI, so having it as a inner class is one way to make sure it can do this.
Your AsyncTask if you're using it as a public class outside the activity in which you are calling it needs to recieve the context of that activity. There are a number of posts here, here and here that explain how to set this up.
Related
I am trying to download an image from the internet. Right now the app downloads only part of the image, but then it stops. I am using AsyncTask. Any suggestions on what to do?
The error I get is:
android.os.NetworkOnMainThreadException
at com.example.reynaldo.getimageserver.MainActivity$DownloadAsyncTask.onPostExecute(MainActivity.java:74)
W/System.err: at com.example.reynaldo.getimageserver.MainActivity$DownloadAsyncTask.onPostExecute(MainActivity.java:30)
This is the code I have:
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick (View view){
DownloadAsyncTask task = new DownloadAsyncTask();
task.execute(new String[] {"http://res.cloudinary.com/demo/image/upload/w_500,f_auto/sample.jpg" });
}
private class DownloadAsyncTask extends AsyncTask<String, Void, String> {
Bitmap bitmap = null;
InputStream in = null;
#Override
protected String doInBackground(String... urls){
int response = -1;
URL url;
try {
url = new URL("http://res.cloudinary.com/demo/image/upload/w_500,f_auto/sample.jpg");
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
System.out.println("This is wrong");
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
return "success";
}
}
catch (IOException e) {
System.out.println("IOException");
}
return "Download failed";
}
#Override
protected void onPostExecute(String result) {
//try {
bitmap = BitmapFactory.decodeStream(in);
/* in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}*/
ImageView img = (ImageView) findViewById(R.id.image);
img.setImageBitmap(bitmap);
}
}
}
try this if you dont want to use third party library
new DownloadImage(Imageview).execute(YourUrl);
Create a AsyncTask Class
public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
CircleImageView bmImage;
public DownloadImage(ImageView bmImage) {
this.bmImage = (CircleImageView) bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.d("Error", e.getStackTrace().toString());
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
i am trying to fetch an immage from url and setting it into a imageview
the image is small in size and i m using asynctask.
here is the main activity code.
i have tried multiple code from diff site but nothing seems to work.
plz don't suggest volly library.
package com.example.jsonimage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.widget.ImageView;
public class MainActivity extends Activity {
Thread t;
Bitmap bitmap;
ImageView iv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv=(ImageView)findViewById(R.id.imageView1);
//runthread();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class loadimage extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
URL url;
try {
url = new URL("http://wptrafficanalyzer.in//p//demo1//india.png");
InputStream is=url.openStream();
bitmap= BitmapFactory.decodeStream(is);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//HttpURLConnection huc =(HttpURLConnection)url.openConnection();
//huc.connect();
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
iv.setImageBitmap(bitmap);
}
}
}
You are not calling the Async task. On your MainActivity try:
new loadimage().execute();
Also you can use this function to get a bitmap from an URL if yours isn't working:
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
package com.lociiapp;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;
import com.androidquery.AQuery;
import com.example.imageslideshow.R;
public class recciverfullimageActivty extends Activity {
String reccvierid;
Context context;
ImageView recciverimage;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Intent myintent = getIntent();
reccvierid = myintent.getStringExtra("reccvierid");
recciverimage = (ImageView) findViewById(R.id.recciverImage);
String myfinalpathare = reccvierid;
Toast.makeText(getApplicationContext(), reccvierid, 10000).show();
String imagepathe = "http://api.lociiapp.com/TransientStorage/"
+ myfinalpathare + ".jpg";
try {
saveImage(imagepathe);
Log.e("****************************", "Sucess");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void saveImage(String urlPath) throws Exception {
String fileName = "test.jpg";
File folder = new File("/sdcard/LociiImages/");
// have the object build the directory structure, if needed.
folder.mkdirs();
final File output = new File(folder, fileName);
if (output.exists()) {
output.delete();
}
InputStream stream = null;
FileOutputStream fos = null;
try {
URL url = new URL(urlPath);
stream = url.openConnection().getInputStream();
// InputStreamReader reader = new InputStreamReader(stream);
DataInputStream dis = new DataInputStream(url.openConnection()
.getInputStream());
byte[] fileData = new byte[url.openConnection().getContentLength()];
for (int x = 0; x < fileData.length; x++) { // fill byte array with
// bytes from the data
// input stream
fileData[x] = dis.readByte();
}
dis.close();
fos = new FileOutputStream(output.getPath());
fos.write(fileData);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
This is My code I am trying to save Image which is coming from server we have Image Url . when i Run this Code then Folder is creating in Sd card But image is not downloading on Save in Sd care please help and tell where i am doing wrong .
Your checklist should be as follows:
A. Make sure you have the right permissions:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
B. Move networking and file IO logic to non-UI thread:
new AsyncTask<Params, Progress, Result>() {
#Override protected Result doInBackground() {
saveImage(imagepathe);
}
#Override protected void onPostExecute(String result) {
// update UI here
}
}.execute(params);
C. Do not read one byte at the time. It is probably not the source of your problem but it
does make your solution much slower than it can be:
Instead of:
for(;;) {
fileData[x] = dis.readByte();
}
Do this:
URL u = new URL(url);
URLConnection connection = u.openConnection();
byte[] buffer = new byte[connection.getContentLength()];
stream.readFully(buffer); // <------------- read all at once
stream.close();
D. And , finally, consider using Picasso for the job:
Picasso.with(context)
.load(url)
.resize(50, 50)
.centerCrop()
.into(imageView)
Nowadays you just no not need to write that much code to get were you're going..
Try this..
Call like below instead of saveImage(imagepathe);
myAsyncTask myWebFetch = new myAsyncTask();
myWebFetch.execute();
and myAsyncTask.class
class myAsyncTask extends AsyncTask<Void, Void, Void> {
public ProgressDialog dialog;
myAsyncTask()
{
dialog = new ProgressDialog(webview.this);
dialog.setMessage("Loading image...");
dialog.setCancelable(true);
dialog.setIndeterminate(true);
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
dialog.dismiss();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog.show();
}
protected Void doInBackground(Void... arg0) {
try {
InputStream stream = null;
URL url = new URL("http://api.lociiapp.com/TransientStorage/286.jpg");
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
File SDCardRoot = Environment.getExternalStorageDirectory();
File myDir = new File(SDCardRoot + "/LociiImages");
myDir.mkdirs();
File file = new File(myDir,"test.jpg");
FileOutputStream fileOutput = new FileOutputStream(file);
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = stream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
} catch (Exception ex) {
ex.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
EDIT
String imagePath = Environment.getExternalStorageDirectory().toString() + "/LociiImages/test.jpg";
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
imageview.setImageBitmap(bitmap);
I want to load an image from url on a button click & to show it on activity imageview.
how to do it?
I try the following code but it shows the system error like java.net.UnknownHostException Host is on resolved.
package com.v3.thread.fetchImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.http.HttpException;
import org.apache.http.conn.HttpHostConnectException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainThreadActivity extends Activity {
ImageView img_downloaded;
Button btn_download;
String fileurl = "http://variable3.com/files/images/email-sig.jpg";
Bitmap bmImg;
private ProgressDialog dialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//new MainThreadActivity().onPreExecute();
img_downloaded = (ImageView) findViewById(R.id.imageView1);
btn_download = (Button) findViewById(R.id.btnLoad);
btn_download.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
try {
downloadfile(fileurl);
} catch (HttpHostConnectException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public void AbstractProgressTask() {
dialog = new ProgressDialog(this);
}
protected void onPreExecute() {new MainThreadActivity().onPreExecute();
this.dialog.setMessage("Loading. Please wait...");
this.dialog.show();
}
/**
* method is called after the work is done.
*
* #param success result of #doInBackground method.
*/
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
// automatically done on worker thread (separate from UI thread)
protected Boolean doInBackground(final String... args) {
// here is your code
return true;
}
void downloadfile(String fileurl) throws HttpException,HttpHostConnectException {
URL myFileUrl = null;
try {
myFileUrl = new URL(fileurl);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
int length = conn.getContentLength();
if(length>0)
{
int[] bitmapData =new int[length];
byte[] bitmapData2 =new byte[length];
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
//img.setImageBitmap(bmImg);
}
else
{
int[] bitmapData =new int[length];
byte[] bitmapData2 =new byte[length];
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
}
}
catch(IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
please tell me where i hav to change
That seems like a lot of code just to show on an ImageView. Try this instead:
URL url = new URL("http://variable3.com/files/images/email-sig.jpg");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
img_downloaded.setImageBitmap(bmp);
Use the following code for that, it will help you
Drawable drawable = LoadImageFromWebOperations(backImgUrl);
bagImgBtn.setBackgroundDrawable(drawable);
private Drawable LoadImageFromWebOperations(String url) {
// TODO Auto-generated method stub
try
{
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
}catch (Exception e) {
if (LogD) {
Log.d(TAG, e.toString());
e.printStackTrace();
}
return null;
}
}
Create a new onClick method called downloadButton.
public void downloadButton(View view){
Log.i("Button Status", "Button Pressed");
downloadImage imagedownload = new downloadImage();
Bitmap image;
try {
image = imagedownload.execute("Paste URL address of an image").get();
imageView.setImageBitmap(image);
}catch (Exception e){
e.printStackTrace();
}
}
Create a class called downloadImage which extends AysncTask.
public class downloadImage extends AsyncTask<String, Void, Bitmap>{
#Override
protected Bitmap doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
InputStream inputStream = httpURLConnection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
}
Just call the following method on Button Click:
Drawable drawable_from_url(String url, String src_name) throws java.net.MalformedURLException, java.io.IOException
{
return Drawable.createFromStream(((java.io.InputStream)new java.net.URL(url).getContent()), src_name);
}
where url is the url to pass and src_name is any String(say "src")
Hope this will help you
I want to load an image from url on a button click & to show it on activity imageview
You have to do something like below within onPageFinished:
public void onPageFinished (WebView view, String url) {
wv.loadUrl(javascript);
view.getSettings().setLoadsImagesAutomatically(true);
wv.setVisibility(View.VISIBLE);
}
I am using the code below to download and show image from server to my ImageView
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
public class HTTPTest extends Activity {
ImageView imView;
String imageUrl="http://11.0.6.23/";
Random r= new Random();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
Button bt3= (Button)findViewById(R.id.get_imagebt);
bt3.setOnClickListener(getImgListener);
imView = (ImageView)findViewById(R.id.imview);
}
View.OnClickListener getImgListener = new View.OnClickListener()
{
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
//i tried to randomize the file download, in my server i put 4 files with name like
//png0.png, png1.png, png2.png so different file is downloaded in button press
int i =r.nextInt(4);
downloadFile(imageUrl+"png"+i+".png");
Log.i("im url",imageUrl+"png"+i+".png");
}
};
Bitmap bmImg;
void downloadFile(String fileUrl){
URL myFileUrl =null;
try {
myFileUrl= new URL(fileUrl);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
int length = conn.getContentLength();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
imView.setImageBitmap(bmImg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This code works file for all format of images but when it comes to PNG it wont let the image transparent after download and displaying on ImageView.
Any idea?
I dont know it will be a solution for you or not
But you can use a Drawable instead of Bitmap
Here is the code
void downloadFile(String fileUrl) {
try{
InputStream is = (InputStream) new URL(fileUrl).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
imgView.setImageDrawable(d);
} catch (IOException e) {
e.printStackTrace();
}
}
This will show a png correctly