I am trying to download the image from url and save it in a file. But it's not getting saved. So as I debug the code I found that bitmap is always null.
code:
public class ImageUserTask extends AsyncTask<Void, Void,String> {
String strURL, imageprofile;
Bitmap mBitmap = null;
Context mContext;
private File profileFile;
public ImageUserTask(Context context, String url) {
this.strURL = url;
this.imageprofile = imageprofile;
this.mContext = context;
}
#Override
protected String doInBackground(Void... params) {
Bitmap bitmap = null;
File directory = null;
try {
URL url = new URL(strURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
// InputStream input = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream()); //This bitmap is null always
directory = Environment.getExternalStorageDirectory();
// Create a new folder in SD Card
File dir = new File(Environment.getExternalStorageDirectory().getPath() + "/Profile");
if (!directory.exists() && !directory.isDirectory()) {
directory.mkdirs();
}
File mypath = new File(dir,"ProfileImage");
saveFile(mypath, bitmap);
} catch (MalformedURLException e) {
} catch (IOException e) {
}
return directory.getAbsolutePath();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result != null) {
imageprofile = result;
}
}
private void saveFile(File fileName, Bitmap bmp) {
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(fileName);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, outputStream); // 100 will be ignored
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
EDIT:
public class ImageUserTask extends AsyncTask<Void,Void,Bitmap> {
String strURL, imageprofile;
Bitmap mBitmap = null;
Context mContext;
private File profileFile;
public ImageUserTask(Context context, String url) {
this.strURL = url;
this.imageprofile = imageprofile;
this.mContext = context;
}
#Override
protected Bitmap doInBackground(Void... params) {
getImageFromUrl(strURL);
return mBitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if (result != null) {
Bitmap bitmap = result;
}
}
public Bitmap getImageFromUrl(String urlString) {
try {
URL url = new URL(urlString);
try {
if(mBitmap!=null) {
mBitmap.recycle();
mBitmap=null;
}
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoInput(true);
//Connected to server
connection.connect();
//downloading image
InputStream input = connection.getInputStream();
mBitmap = BitmapFactory.decodeStream(input);
convertBitmapToFile(mBitmap, urlString);
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return mBitmap;
}
public File convertBitmapToFile(Bitmap bitmap, String fileName) {
ContextWrapper cw = new ContextWrapper(mContext);
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
File mypath = new File(directory, fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return mypath;
}
}
What can be the reason? I have added Internet permissions too. Please help. Thank you..
class DownloadFile extends AsyncTask<String, Integer, String> {
String strFolderName;
String shareType;
String downloadPath = "";
Activity mContext;
public DownloadFile(Activity mContext) {
this.mContext = mContext;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
String fileName = "your filename with ext";
Log.d("TAG", fileName);
URL url = new URL("your url");
URLConnection conexion = url.openConnection();
conexion.connect();
String PATH = "your Path you want to store" + "/";
downloadPath = PATH + fileName;
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(downloadPath);
byte data[] = new byte[1024];
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String path) {
super.onPostExecute(path);
}
}
This code is work for me
Use the below methods
public Bitmap getImageFromUrl(String urlString) {
Bitmap bmp = null;
try {
URL url = new URL(urlString);
try {
if(bmp!=null) {
bmp.recycle();
bmp=null;
}
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
convertBitmapToFile(bmp, urlString);
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return bmp;
}
public File convertBitmapToFile(Bitmap bitmap, String fileName) {
ContextWrapper cw = new ContextWrapper(activityRef.getApplicationContext());
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
File mypath = new File(directory, fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return mypath;
}
Add android Permissions for internet and Storage
Please try this
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;
}
}
Related
I want to save image from url to storage through picasso, but i have a problem with my code.
i've a variable to save image.
String urlImage = "http://mylink/buzz/test2.jpg";
this one is worked
but when i use
fileUrl = fileName +"." + fileType;
String urlImage = "http://mylink/buzz/" + fileUrl;
not worked
content of fileUrl is test2.jpg
here is my code to save image
private Target picassoImageTarget(Context context, final String imageDir, final String imageName) {
Log.d("picassoImageTarget", " picassoImageTarget");
ContextWrapper cw = new ContextWrapper(context);
final File directory = cw.getDir(imageDir, Context.MODE_PRIVATE); // path to /data/data/yourapp/app_imageDir
return new Target() {
#Override
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
new Thread(new Runnable() {
#Override
public void run() {
final File myImageFile = new File(directory, imageName); // Create image file
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myImageFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Log.i("image", "image saved to >>>" + myImageFile.getAbsolutePath());
}
}).start();
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
if (placeHolderDrawable != null) {}
}
};
}
and its code for call picasso.
Picasso.with(DrawerActivity.this).load(url).into(picassoImageTarget(getApplicationContext(), "imageDir", fileUrl));
Hi,
I have an async task which downloads image via http request and shares it after completion. But if the user cancel the task, it should stop.
I'm calling it like this:
mShareImage = new shareAsync(PhotoEnlargeActivity.this).execute(imageUris.get(currentPosition));
And stopping it like this:
mShareImage.cancel(true);
But it doesn't seen to work. Async Task:
public class shareAsync extends AsyncTask<String, String, String> {
private Context mContext;
URL myFileUrl;
Bitmap bmImg = null;
Intent share;
File file;
boolean isCancelled = false;
public shareAsync(Context mContext) {
this.mContext = mContext;
}
#Override
protected void onCancelled() {
super.onCancelled();
isCancelled = true;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
showProgressDialog("Downloading High Resolution Image for Sharing...");
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
HttpURLConnection conn = null;
try {
if (!isCancelled()) {
myFileUrl = new URL(args[0]);
conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
} else {
if (conn != null) conn.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
String path = myFileUrl.getPath();
String idStr = path.substring(path.lastIndexOf('/') + 1);
File filepath = Environment.getExternalStorageDirectory();
File dir = new File(filepath.getAbsolutePath()
+ "/Google Image Wallpaper/");
dir.mkdirs();
String fileName = idStr;
file = new File(dir, fileName);
FileOutputStream fos = new FileOutputStream(file);
bmImg.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String args) {
// TODO Auto-generated method stub
progressDialog.dismiss();
share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
share.putExtra(Intent.EXTRA_STREAM, Uri.parse(file.getAbsolutePath().toString()));
mContext.startActivity(Intent.createChooser(share, "Share Image"));
}
}
Invoking the method "mShareImage.cancel(true)" will cause subsequent calls to isCancelled() to return true.
But you have to do few more things,
To ensure that a task is cancelled as quickly as possible, you should always check the return value of isCancelled() periodically inside doInBackground.
You have added the "!isCancelled()" check beginning of the method, so it is not working.
Network operation is a blocking operation, so once its started any operation you have to wait. That's why we always do network operation in a worker thread.
Following change would solve your issue,
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
HttpURLConnection conn = null;
try {
myFileUrl = new URL(args[0]);
conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
if (isCancelled()) return null;
conn.connect();
if (isCancelled()) return null;
InputStream is = conn.getInputStream();
if (isCancelled()) return null;
bmImg = BitmapFactory.decodeStream(is);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
}
try {
String path = myFileUrl.getPath();
String idStr = path.substring(path.lastIndexOf('/') + 1);
File filepath = Environment.getExternalStorageDirectory();
File dir = new File(filepath.getAbsolutePath()
+ "/Google Image Wallpaper/");
dir.mkdirs();
String fileName = idStr;
file = new File(dir, fileName);
FileOutputStream fos = new FileOutputStream(file);
if (isCancelled()) return null;
bmImg.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String args) {
// TODO Auto-generated method stub
progressDialog.dismiss();
share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
share.putExtra(Intent.EXTRA_STREAM, Uri.parse(file.getAbsolutePath().toString()));
if (isCancelled()) return;
mContext.startActivity(Intent.createChooser(share, "Share Image"));
}
I would like to download a large pdf file with jsoup. I have try to change timeout and maxBodySize but the largest file I could download was about 11MB. I think if there is any way to do something like buffering. Below is my code.
public class Download extends Activity {
static public String nextPage;
static public Response file;
static public Connection.Response res;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Bundle b = new Bundle();
b = getIntent().getExtras();
nextPage = b.getString("key");
new Login().execute();
finish();
}
private class Login extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try {
res = Jsoup.connect("http://www.eclass.teikal.gr/eclass2/")
.ignoreContentType(true).userAgent("Mozilla/5.0")
.execute();
SharedPreferences pref = getSharedPreferences(
MainActivity.PREFS_NAME, MODE_PRIVATE);
String username1 = pref.getString(MainActivity.PREF_USERNAME,
null);
String password1 = pref.getString(MainActivity.PREF_PASSWORD,
null);
file = (Response) Jsoup
.connect("http://www.eclass.teikal.gr/eclass2/")
.ignoreContentType(true).userAgent("Mozilla/5.0")
.maxBodySize(1024*1024*10*2)
.timeout(70000*10)
.cookies(res.cookies()).data("uname", username1)
.data("pass", password1).data("next", nextPage)
.data("submit", "").method(Method.POST).execute();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
String PATH = Environment.getExternalStorageDirectory()
+ "/download/";
String name = "eclassTest.pdf";
FileOutputStream out;
try {
int len = file.bodyAsBytes().length;
out = new FileOutputStream(new File(PATH + name));
out.write(file.bodyAsBytes(),0,len);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I hope somebody could help me!
I think, it's better to download any binary file via HTTPConnection:
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL("http://example.com/file.pdf");
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream("/sdcard/file_name.extension");
byte data[] = new byte[4096];
int count;
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
Jsoup is for parsing and loading HTML pages, not binary files.
at com.example.newpingziyi.stir.CheckSdcard$LoadImagesFromSDCard.doInBackground(CheckSdcard.java:316)
error lines was make Stronger!
First.show that's error like java.lang.OutOfMemoryError!
this's code...
class LoadImagesFromSDCard extends AsyncTask<Object, LoadedImage, Object> {
#Override
protected Object doInBackground(Object... params) {
Bitmap newBitmap = null;
File file = new File(localPath);
String[] filepath = file.list();
for (String str : filepath) {
String filename = str;
String imagePath = localPath + "/" + filename;
File files = new File(imagePath);
FileInputStream is = null;
BufferedInputStream bis = null;
try {
is = new FileInputStream(new File(imagePath));
bis = new BufferedInputStream(is);
//this line was wrong!
Bitmap bitmap = BitmapFactory.decodeStream(bis);//this lines was wrong!!
is.close();
bis.close();
if (bitmap != null) {
newBitmap = Bitmap.createScaledBitmap(bitmap, 70, 70,
true);
bitmap.recycle();
if (newBitmap != null) {
publishProgress(new LoadedImage(newBitmap));
}
}
} catch (IOException e) {
}
}
return null;
}
#Override
public void onProgressUpdate(LoadedImage... value) {
addImage(value);
}
#Override
protected void onPostExecute(Object result) {
imageAdapter.notifyDataSetChanged();
}
}
Bitmap bitmap = BitmapFactory.decodeStream(bis);//this lines was wrong!!
now i make change below code.still OutOfMemoryError yet!
class LoadImagesFromSDCard extends AsyncTask<Object, LoadedImage, Object> {
#Override
protected Object doInBackground(Object... params) {
Bitmap newBitmap = null;
File file = new File(localPath);
String[] filepath = file.list();
for (String str : filepath) {
String filename = str;
String imagePath = localPath + "/" + filename;
File files = new File(imagePath);
FileInputStream is = null;
BufferedInputStream bis = null;
try {
is = new FileInputStream(new File(imagePath));
bis = new BufferedInputStream(is);
bis.mark(0);
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeStream(bis, null, opts);
int sizes = (opts.outWidth * opts.outHeight);
if (sizes > 1024 * 1024 * 4) {
int zoomRate = 2;
if (zoomRate <= 0)
zoomRate = 1;
opts.inSampleSize = zoomRate;
}
opts.inJustDecodeBounds = false;
bis.reset();
//this line was wrong!
Bitmap bitmap = BitmapFactory.decodeStream(bis, null, opts);//this lines was wrong!!
is.close();
bis.close();
if (bitmap != null) {
newBitmap = Bitmap.createScaledBitmap(bitmap, 70, 70,
true);
bitmap.recycle();
if (newBitmap != null) {
publishProgress(new LoadedImage(newBitmap));
}
}
} catch (IOException e) {
}
}
return null;
}
#Override
public void onProgressUpdate(LoadedImage... value) {
addImage(value);
}
#Override
protected void onPostExecute(Object result) {
imageAdapter.notifyDataSetChanged();
}
}
Bitmap bitmap = BitmapFactory.decodeStream(bis, null, opts);//this lines!
Here is my working code for downloading Bitmap, maybe it will help :
private Bitmap downloadBitmap(String url) {
// Getting the url from the html
url = url.substring(url.indexOf("src=\"") + 5, url.length() - 1);
url = url.substring(0, url.indexOf("\""));
final DefaultHttpClient client = new DefaultHttpClient();
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
//check 200 OK for success
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode +
" while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
// getting contents from the stream
inputStream = entity.getContent();
// decoding stream data back into image Bitmap that android understands
final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
// You Could provide a more explicit error message for IOException
getRequest.abort();
Log.e("ImageDownloader", "Something went wrong while" +
" retrieving bitmap from " + url + e.toString());
}
return null;
}
I want to get user's facebook profile picture url and below is code for that.
Code :
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
StringBuilder res = new StringBuilder();
// fetch user profile picture url
URL url = null;
HttpURLConnection httpconn = null;
String strUrl = "http://graph.facebook.com/"
+ fbuser.getFacebookId()
+ "/picture?width=350&height=350";
try {
url = new URL(strUrl);
httpconn = (HttpURLConnection) url
.openConnection();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader input = new BufferedReader(
new InputStreamReader(httpconn
.getInputStream()));
String strLine = null;
while ((strLine = input.readLine()) != null) {
res.append(strLine);
}
input.close();
}
Log.e(TAG, "res : " + res);
JSONObject imageUrlObject = new JSONObject(
res.toString());
fbuser.setImageUrl(imageUrlObject
.getJSONObject("picture")
.getJSONObject("data")
.getString("url"));
// Call a method of an Activity to notify
// user info is received
((RS_LoginActivity) RS_Facebook.this.activity)
.FacebookUserInfoReceived();
// call login api
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
thread.start();
I log the string response and below is the screen shot of how that response looks like.
Any idea why this happens?
The API spec likely changed; use the following workaround:
fbuser.setImageUrl("http://graph.facebook.com/"
+ fbuser.getFacebookId()
+ "/picture?width=350&height=350");
That URL is what got you a JPEG image as of lately, so it's likely the URL you need.
public class Profile extends Activity {
ImageView iv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_profile);
iv= (ImageView)findViewById(R.id.imageView1);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String url = "http://graph.facebook.com/" + fbID+ "/picture?width=800&height=600";
BitmapFactory.Options bmOptions;
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
Bitmap bm = loadBitmap(url, bmOptions);
iv.setImageBitmap(bm);
}
public static Bitmap loadBitmap(String URL, BitmapFactory.Options options) {
Bitmap bitmap = null;
InputStream in = null;
try
{
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in, null, options);
in.close();
}
catch (IOException e1) {
}
return bitmap;
}
private static InputStream OpenHttpConnection(String strURL)
throws IOException {
InputStream inputStream = null;
URL url = new URL(strURL);
URLConnection conn = url.openConnection();
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
} catch (Exception ex) {
}
return inputStream;
}