download images from FTP :Caused by: java.lang.OutOfMemoryError - java

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;
}

Related

Uploading a file from android take ages before calling a function

I'm having a hard time with calling a function when I select on the files.
When I select on a file, it start to take like 10 seconds before it start to call the UploadFile function and then connect to the server, so when I select more files to add, it will take like a minute or so before it start to call the UploadFile function and connect to the server which is wrong. It should have start to call the UploadFile function instantly and connect to the server when I am adding more than one files.
Below is the full code:
public class ComposeActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private static final int CHOOSE_FILE_REQUESTCODE = 1;
private RecyclerView mFilesDetailRecyclerView;
private ArrayList<String> mSelectedFilesList = new ArrayList<>();
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == CHOOSE_FILE_REQUESTCODE) {
try {
Uri uri = data.getData();
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
int index = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
Context context = getApplicationContext();
FilePath = RealPathUtil.getRealPath(context, uri);
cursor.moveToFirst();
//mSelectedFilesList.add(cursor.getString(index));
mSelectedFilesList.add(FilePath);
mAdapter.notifyItemInserted(mSelectedFilesList.size());
Log.e("message.......", "caught this.....");
upload_File = new File(FilePath);
FileName = upload_File.getName();
new UploadFile().execute();
} catch (Exception e) {
Toast.makeText(ComposeActivity.this, "Choose any other file", Toast.LENGTH_SHORT).show();
}
}
}
#SuppressLint("StaticFieldLeak")
private class UploadFile extends AsyncTask<Void, Void, Void> {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected Void doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
try {
String twoHyphens = "--";
String boundary = "*****" + System.currentTimeMillis() + "*****";
String lineEnd = "\r\n";
Log.e("message.......", "FileName...." + FileName);
URL url = new URL("https://www.example.com/fileupload1.php");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setUseCaches(false);
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setConnectTimeout(200);
urlConnection.setReadTimeout(200);
urlConnection.setRequestProperty("Connection", "Keep-Alive");
urlConnection.setRequestProperty("ENCTYPE", "multipart/form-data");
urlConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
urlConnection.setRequestProperty("uploaded_file", FileName);
FileInputStream fileInputStream = new FileInputStream(upload_File);
DataOutputStream dataOutputStream = new DataOutputStream(urlConnection.getOutputStream());
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file" +
"\"; filename=\"" + FileName + "\"" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
Log.e("message.......", "FileName...." + FileName);
//returns no. of bytes present in fileInputStream
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
//Thread.sleep(5000);
while (bytesRead > 0) {
//int percentage = (int) ((bytesRead / (float) size) * 100);
dataOutputStream.write(buffer, 0, bufferSize);
//dataOutputStream.flush(); //doesn't help
bytesAvailable = fileInputStream.available();
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
int code = urlConnection.getResponseCode();
StringBuilder result = new StringBuilder();
if (code == 200) {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
upload_success = result.toString();
}
} catch(SocketTimeoutException e) {
//e.printStackTrace();
if (urlConnection != null) {
urlConnection.disconnect();
cancel(true);
}
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
Log.e("message.......", "here....5");
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e("message.......", "here....6");
} catch (ConnectTimeoutException e) {
e.printStackTrace();
Log.e("message.......", "here....7");
}
catch (IOException ioException) {
ioException.printStackTrace();
Log.e("message.......", "here....2");
}
catch (Exception e) {
e.printStackTrace();
Log.e("message.......", "here....5");
if (failtoupload == false) {
failtoupload = true;
}
if (sendMail == true) {
sendMail = false;
}
if (UpdateDraft == true) {
UpdateDraft = false;
}
if (saveDraft == true) {
saveDraft = false;
}
Date dt = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String savedDate = dateFormat.format(dt);
draftDB = new DraftDB(mContext);
if (mSelectedFilesList.size() == 1) {
attachments = join("", mSelectedFilesList);
if (attachments.equals("")) {
attachments = null;
}
}
else
{
attachments = join(", ", mSelectedFilesList);
}
if (attachments == null) {
if (mSelectedFilesList.size() == 1) {
attachments = join("", mSelectedFilesList);
}
else
{
attachments = join(", ", mSelectedFilesList);
}
}
String isImportant = "true";
String isRead = "unread";
String UpdateDB = null;
String draftID = null;
if (to == null) {
to = "";
}
if (bcc == null) {
bcc = "";
}
if (cc == null) {
cc = "";
}
if (subject == null) {
subject = "";
}
if (message == null) {
message = "";
}
if (draft_id != null) {
draftID = draft_id;
UpdateDB = "yes";
}
else
{
draftID = "";
UpdateDB = "no";
}
if (draftDB_id == 0) {
draftDB.insertDraft(from, to, cc, bcc, subject, message, attachments, isImportant, isRead, UpdateDB, draftID, savedDate);
draftDB_id = draftDB.getID();
}
else
{
int id = draftDB_id;
draftDB.updateDraft(id, from, to, cc, bcc, subject, message, attachments, isImportant, isRead, UpdateDB, draftID, savedDate);
}
else
{
int id = draftDB_id;
draftDB.updateDraft(id, from, to, cc, bcc, subject, message, attachments, isImportant, isRead, UpdateDB, draftID, savedDate);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
Log.e("message.......", "here....6");
if (upload_success != null) {
if (upload_success.equals("success")) {
if (mSelectedFilesList.size() > 0) {
mSelectedFilesList.remove(0);
if (draft_id == null) {
new SaveDraft().execute();
}
else if (draft_id != null) {
if (attachment != null) {
if (mSelectedFilesList.size() >= 1) {
attid++;
for (int i = 0; i < mSelectedFilesList.size(); i++) {
String path = mSelectedFilesList.get(0);
FileName = path.substring(path.lastIndexOf("/") + 1);
attachment += " attid: " + String.valueOf(attid) + " filename: " + FileName;
}
}
}
Log.e("message........", "attachment......" + attachment);
new UpdateDrafts().execute();
}
if (mSelectedFilesList.size() >= 1) {
FilePath = mSelectedFilesList.get(0);
upload_File = new File(FilePath);
FileName = upload_File.getName();
new UploadFile().execute();
}
}
//Now time to check the upload_File
if (mSelectedFilesList.size() == 0) {
if (upload_File != null) {
upload_File = null;
}
if (FilePath != null) {
FilePath = null;
}
Log.e("message.......", "sendMail........." + sendMail);
}
if (upload_success != null) {
upload_success = null;
}
}
}
}
#Override
protected void onCancelled() {
super.onCancelled();
this.cancel(true);
}
}
What I am trying to do is when I select on the file and add more files on my mobile app, I want to call the UploadFile function instantly and connect to my server to upload the file in each time when I select on the file. If the server do not response for 10 seconds and the server is offline, I want to store the data in the sqlite database.
I have been told that I should use multi thread and I should also use retrofit. I am not sure if it would be possible to use HttpUrlConnection method with multi thread to connect to the server and upload the files.
Can you please show me an example of what is the best way I could use to get instantly call to a function and connect to the server using with HttpUrlConnection if that is possible??
You start already wrong with trying to get a real path for an uri.
Remove that code.
Then instead of opening a FileInputStream open an InputStream for the uri
InputStream is = getContentResolvet().openInputStream(uri);

When i select image from recent then image is broken in android | Multiple images from recent

This error occurs mostly times when select images from recent folder
class com.bumptech.glide.load.engine.GlideException: Received null model
Call multiple images select
Sample Preview
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
*gallery*.launch(i);
gallery basically startActivityForResult(i,123) and OnActivityResult method is deprecated, the gallery is alternative which is defined below
ActivityResultLauncher<Intent> gallery = choosePhotoFromGallery();
and choosePhotoFromGallery() is method which is define below
private ActivityResultLauncher<Intent> choosePhotoFromGallery() {
return registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
try {
if (result.getResultCode() == RESULT_OK) {
if (null != result.getData()) {
if (result.getData().getClipData() != null) {
ClipData mClipData = result.getData().getClipData();
for (int i = 0; i < mClipData.getItemCount(); i++) {
ClipData.Item item = mClipData.getItemAt(i);
Uri uri = item.getUri();
String imageFilePathColumn = getPathFromURI(this, uri);
productImagesList.add(imageFilePathColumn);
}
} else {
if (result.getData().getData() != null) {
Uri mImageUri = result.getData().getData();
String imageFilePathColumn = getPathFromURI(this, mImageUri);
productImagesList.add(imageFilePathColumn);
}
}
} else {
showToast(this, "You haven't picked Image");
productImagesList.clear();
}
} else {
productImagesList.clear();
}
} catch (Exception e) {
e.printStackTrace();
showToast(this, "Something went wrong");
productImagesList.clear();
}
});
}
and getPathFromURI() is method which define below
public String getPathFromURI(Context context, Uri contentUri) {
OutputStream out;
File file = getPath();
try {
if (file.createNewFile()) {
InputStream iStream = context != null ? context.getContentResolver().openInputStream(contentUri) : context.getContentResolver().openInputStream(contentUri);
byte[] inputData = getBytes(iStream);
out = new FileOutputStream(file);
out.write(inputData);
out.close();
return file.getAbsolutePath();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private byte[] getBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
and the getPath() is
private File getPath() {
File folder = new File(Environment.getExternalStorageDirectory(), "Download");
if (!folder.exists()) {
folder.mkdir();
}
return new File(folder.getPath(), System.currentTimeMillis() + ".jpg");
}
THANK YOU IN ADVANCE HAPPY CODING

How to convert Uri image into Base64?

I have write code to convert image from file location into base64. I can easily convert image into base64 from absolute file location like: C:/Users/Java Engineer/Desktop/test/gallery/magar/Kanuglam.jpg , but I can not convert from location like
. I want to convert image to use in android from web-service.
Here is code sample :
/**
* TEST JSON
*/
String convertToJsonArrayWithImageForMovieDetailTest(ResultSet rs) {
System.out.println("I am insied json converter");
JSONArray list = new JSONArray();
JSONObject obj ;
//File file;
File locatedFile;
FileInputStream fileInputStream;
try {
while (rs.next()) {
obj = new JSONObject();
System.out.println("inside RS");
System.out.println("date is there ha ha ");
obj.put("movie_name", rs.getString("name"));
obj.put("movie_gener", rs.getString("type"));
String is_free_stuff = rs.getString("is_free_stuff");
if (is_free_stuff == "no") {
is_free_stuff = "PAID";
} else {
is_free_stuff = "FREE";
}
obj.put("movie_type", is_free_stuff);
//String movie_image = rs.getString("preview_image");
//this does not work
String movie_image = "http://www.hamropan.com/stores/slider/2016-09-10-852311027.jpg";
//this works for me
// file = new File("C:/Users/Java Engineer/Desktop/Nike Zoom Basketball.jpg");
locatedFile = new File(movie_image);
// Reading a Image file from file system
fileInputStream = new FileInputStream(locatedFile);
if (locatedFile == null) {
obj.put("movie_image", "NULL");
} else {
byte[] iarray = new byte[(int) locatedFile.length()];
fileInputStream.read(iarray);
byte[] img64 = com.sun.jersey.core.util.Base64
.encode(iarray);
String imageString = new String(img64);
obj.put("movie_image", imageString);
}
list.add(obj);
}
} catch (Exception e) {
e.printStackTrace();
}
return list.toString();
}
this block of code works for me but it seem slow
public String imageConvertMethod(String url) throws Exception{
ByteArrayOutputStream output = new ByteArrayOutputStream();
try (InputStream input = new URL(url).openStream()) {
byte[] buffer = new byte[512];
for (int length = 0; (length = input.read(buffer)) > 0;) {
output.write(buffer, 0, length);
}
}
byte [] byte_array = output.toByteArray();
byte[] img64 = com.sun.jersey.core.util.Base64
.encode(byte_array);
String imageString = new String(img64);
return imageString;
}
Ok, try this
bitmap = getBitmapFromUrl(image_url);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] array = stream.getByteArray();
encoded_string = Base64.encodeToString(array, 0);
Method wo load image from url
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;
}
}
#thanks to Fabio Venturi Pastor
Try this:
ImageUri to Bitmap:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
final Uri imageUri = data.getData();
final InputStream imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
String encodedImage = encodeImage(selectedImage);
}
}
Encode Bitmap in base64
private String encodeImage(Bitmap bm)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG,100,baos);
byte[] b = baos.toByteArray();
String encImage = Base64.encodeToString(b, Base64.DEFAULT);
return encImage;
}
Encode from FilePath to base64
private String encodeImage(String path)
{
File imagefile = new File(path);
FileInputStream fis = null;
try{
fis = new FileInputStream(imagefile);
}catch(FileNotFoundException e){
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG,100,baos);
byte[] b = baos.toByteArray();
String encImage = Base64.encodeToString(b, Base64.DEFAULT);
//Base64.de
return encImage;
}
output:
reference :
Take picture and convert to Base64

Getting bitmap as null

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;
}
}

App says Image Downloaded Successfully but no image shows up in gallery

The app gets the image from the given URL and displays the image and on clicking the download button, it says that the image has been downloaded successfully but there is no image in the gallery. Can someone tell me how I can fix this?
This is my Image View and Download activity. I have also added proper permissions to the Android Manifest.
private Button btnImageDownload;
private ProgressDialog pd;
private ImageView viewDownloadImage;
private Images imageId;
private File folderName;
private String imageName;
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == 1) {
if (pd != null) {
pd.dismiss();
}
Utils.showNetworkAlert(ImageViewAndDownload.this);
} else if (msg.what == 2) {
if (pd != null) {
pd.dismiss();
}
Utils.displayMessage("Image downloade succesfully",
ImageViewAndDownload.this);
// Media scaning
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"
+ Environment.getExternalStorageDirectory())));
} else if (msg.what == 3) {
if (pd != null) {
pd.dismiss();
}
Utils.displayMessage("Image already downloaded ",
ImageViewAndDownload.this);
} else if (msg.what == 4) {
if (pd != null) {
pd.dismiss();
}
displayImageFromUrl((Bitmap) msg.obj);
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.imagedisplay);
viewDownloadImage = (ImageView) findViewById(R.id.viewImage);
btnImageDownload = (Button) findViewById(R.id.btnImageDownload);
imageId = new Images();
imageName = imageId.getImageId();
LoadImageFromWeb(Constant.IMAGE_BASE_URL + File.separator + imageName);
btnImageDownload.setOnClickListener(this);
}
public void onClick(View v) {
if (v == btnImageDownload) {
pd = ProgressDialog.show(ImageViewAndDownload.this, "",
"Downloading Image....", true, false);
new Thread(new Runnable() {
public void run() {
try {
String imageUrl = Constant.IMAGE_BASE_URL
+ File.separator + imageName;
String isDownloded = downloadImage(imageUrl, imageName);
if (isDownloded.equalsIgnoreCase("complete")) {
handler.sendEmptyMessage(2);
} else if (isDownloded.equalsIgnoreCase("")) {
handler.sendEmptyMessage(3);
} else {
handler.sendEmptyMessage(1);
}
} catch (Exception e) {
e.printStackTrace();
handler.sendEmptyMessage(1);
}
}
}).start();
}
}
// set display image to Imageview
public void displayImageFromUrl(Bitmap obj) {
viewDownloadImage.setImageBitmap(obj);
}
// image display from the webview
private void LoadImageFromWeb(final String url1) {
pd = ProgressDialog.show(ImageViewAndDownload.this, "",
"Loading Image....", true, false);
new Thread(new Runnable() {
public void run() {
try {
URL url = new URL(url1);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
InputStream is = connection.getInputStream();
Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, options);
if (options.outWidth > 3000 || options.outHeight > 2000) {
options.inSampleSize = 4;
} else if (options.outWidth > 2000
|| options.outHeight > 1500) {
options.inSampleSize = 3;
} else if (options.outWidth > 1000
|| options.outHeight > 1000) {
options.inSampleSize = 2;
}
// Do the actual decoding
options.inJustDecodeBounds = false;
is.close();
is = getHTTPConnectionInputStream(url1);
Bitmap myBitmap = BitmapFactory.decodeStream(is, null,
options);
is.close();
if (myBitmap != null) {
Message msg = new Message();
msg.obj = myBitmap;
msg.what = 4;
handler.sendMessage(msg);
} else {
handler.sendEmptyMessage(1);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
public InputStream getHTTPConnectionInputStream(String url1) {
URL url;
InputStream is = null;
try {
url = new URL(url1);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
is = connection.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
// image download code
public String downloadImage(String imageDownloadUrl, String imageName) {
// create directory in SDCARD
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED))
folderName = new File(Constant.STORE_IN_FOLDER);
else
folderName = getFilesDir();
if (!folderName.exists())
folderName.mkdirs();
String response = "";
// create file name and file.
File storeImageInSDCard = new File(folderName + File.separator
+ imageName);
if (!(storeImageInSDCard.exists() && storeImageInSDCard.length() > 0)) {
// start download image
response = downloadFile(imageDownloadUrl, imageName,
folderName.toString());
}
return response;
}
// start download image
public String downloadFile(final String url, final String name,
String foldername) {
File file;
FileOutputStream os = null;
Bitmap myBitmap;
try {
URL url1 = new URL(url.replaceAll(" ", "%20"));
System.out.println("Image url :::" + url1);
HttpURLConnection urlConnection = (HttpURLConnection) url1
.openConnection();
urlConnection.setDoOutput(false);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// here create a file which define folder name and image name with
// extension.
file = new File(foldername, name + ".jpg");
InputStream inputStream = urlConnection.getInputStream();
byte[] buffer = new byte[1024];
int bufferLength = 0;
os = new FileOutputStream(file);
while ((bufferLength = inputStream.read(buffer)) > 0) {
os.write(buffer, 0, bufferLength);
}
os.flush();
os.close();
// if image size is too large we can scale image than download.
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
myBitmap = BitmapFactory
.decodeFile(file.getAbsolutePath(), options);
if (options.outWidth > 3000 || options.outHeight > 2000) {
options.inSampleSize = 4;
} else if (options.outWidth > 2000 || options.outHeight > 1500) {
options.inSampleSize = 3;
} else if (options.outWidth > 1000 || options.outHeight > 1000) {
options.inSampleSize = 2;
}
options.inJustDecodeBounds = false;
myBitmap = BitmapFactory
.decodeFile(file.getAbsolutePath(), options);
os = new FileOutputStream(file);
myBitmap.compress(CompressFormat.JPEG, 90, os);
os.flush();
os.close();
myBitmap.recycle();
return "complete";
} catch (SQLException e) {
e.printStackTrace();
return "error";
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}
}
try this,
After saving the Image you have to use this
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
getApplicationContext().sendBroadcast(mediaScanIntent);
you have to send a broadcast to System ,changes to reflect in the Gallery , so that you image will be shown in the gallery , if not , you have to restart Device for check the downloaded images..
hope it helps you..
I think you have to use Aquery for image download it is very Useful for image download from net.
Here the link for Aquery

Categories

Resources