I have recyclerview and in every recyclerview item, I have images. I also have a download button in every recyclerview item.
If the user will click on download button, images of that recyclerview item will download and store it.
Till here it works fine, now the issue is that, if a user is downloading an image of the first product, and the user will download another image for the next product, images in the gallery is being replaced.
public class DownloadImage extends AsyncTask<String, Void, Void> {
private Context context;
private DownloadImage(Context context) {
this.context = context;
}
#Override
protected Void doInBackground(String... params) {
int ii = 0;
for (int k=0;k<resellerProductLists.get(imgpos).getProductImageDtoList().size();k++) {
//Toast.makeText(context,resellerProductLists.get(0).getProductImageDtoList().get(k).getImageUrl(),Toast.LENGTH_SHORT).show();
Log.e("Image",resellerProductLists.get(imgpos).getProductImageDtoList().get(k).getImageUrl());
ii++;
String img = "IMG-";
String mPath = Environment.getExternalStorageDirectory().toString() + "/Temp/" + img + ii + ".jpg";
File Directory = new File(Environment.getExternalStorageDirectory().toString() + "/Temp");
Directory.mkdirs();
try {
File file = Glide.with(context)
.load(resellerProductLists.get(imgpos).getProductImageDtoList().get(k).getImageUrl())
.downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
.get();
File imageFile = new File(mPath);
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(file));
out = new BufferedOutputStream(new FileOutputStream(mPath));
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.flush();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
} catch (InterruptedException | ExecutionException | IOException e) {
hideLoading();
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Void res) {
super.onPostExecute(res);
//prodImageUri1.addAll(prodImageUri);
// hideLoading();
Toast.makeText(context,"Download Complete Successfully", Toast.LENGTH_SHORT).show();
}
}
Can anyone assist me with this problem?
Image in the gallery is being replaced because both images have same name. This is because your variable 'ii' is initiliazed inside the 'doInBackgroud()' function hence name of image always become "../temp/IMG-1.jpg". To prevent replacing of old Images you can do either of the Following :
Make ' ii ' a Global Variable, so that ii is not initiliazed every time.
Replace int ii=0 with String ii = System.currentTimeMillis().toString(), This will gurantee that ii is unique every time .
Add this to your code and test again:
String timeStamp = new SimpleDateFormat("HHmmss", Locale.US).format(new Date());
String mPath = Environment.getExternalStorageDirectory().toString() + "/Temp/" + img + ii +timeStamp+ ".jpg";
timeStamp will generate unique time based name for every item you download. you can replace this time stamp with everything you want. but it must be unique for every item.
For example you can create a getter/setter in your model class and setImageName accordingly.
public String getImageName() {
return imageName;
}
public void setImageName(String imageName) {
this.imageName = imageName;
}
private String imageName;
And use it like this:
String uniqueName = resellerProductLists.get(imgpos).getProductImageDtoList().get(k).getImageName());
Related
I am making an app which utilizes the camera, and has the ability to take a picture to use a simple image recognition API on it. I can use the gallery just fine to upload images, but straight from the camera is giving me massive issues. I have basically just copied the android dev documentation for most of the image creation, though may have needed to change some items here and there.
Here is the total code:
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + "Image_for_Stack" + "_";
File storageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM), "Camera");
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = "file: " + image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
try {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
Log.v(TAG, "IO Exception " + ex);
}
// Continue only if the File was successfully created
if (photoFile != null) {
photoURI = FileProvider.getUriForFile(getContextOfApplication(),
BuildConfig.APPLICATION_ID + ".provider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, IMAGE_CAPTURE);
}
}
} catch (Exception e) {
Log.v(TAG, "Exception in dispatch " + e);
}
}
private void galleryAddPic() {
try {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(currentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
getContextOfApplication().sendBroadcast(mediaScanIntent);
} catch (Exception e) {
Log.v(TAG, "Exception " + e);
}
}
And in a separate class, this is called:
public static byte[] getByteArrayFromIntentData(#NonNull Context context, #NonNull Intent data) {
InputStream inStream = null;
Bitmap bitmap = null;
try {
inStream = context.getContentResolver().openInputStream(data.getData());
Log.v(TAG, "Instream works");
bitmap = BitmapFactory.decodeStream(inStream);
final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
return outStream.toByteArray();
} catch (FileNotFoundException e) {
Log.v("FileOP Debug", "Exception " + e);
return null;
} finally {
if (inStream != null) {
try {
inStream.close();
} catch (IOException ignored) {
}
}
if (bitmap != null) {
bitmap.recycle();
}
}
}
Now, the image is created without issue. I can go to the emulator, look through the photo's app, and get:
.
However, I get this error when the code gets to giving inStream a value:
java.io.FileNotFoundException: /file:
/storage/emulated/0/DCIM/Camera/JPEG_Image_for_Stack_3248071614992872091.jpg
(No such file or directory) .
I don't exactly understand how this could be. The item clearly exists, and is saved on the phone. The app does request and is given the permission to write to external storage, and I have checked in the emulator permissions that it is given. Write also comes with read, so that shouldn't be an issue as far as I'm aware either.
Edit
To show where this code is being called from.
else if (requestCode == IMAGE_CAPTURE) {
galleryAddPic();
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(currentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
final ProgressDialog progress = new ProgressDialog(getContextOfApplication());
progress.setTitle("Loading");
progress.setMessage("Identify your flower..");
progress.setCancelable(false);
progress.show();
if (!CheckNetworkConnection.isInternetAvailable(getContextOfApplication())) {
progress.dismiss();
Toast.makeText(getContextOfApplication(),
"Internet connection unavailable.",
Toast.LENGTH_SHORT).show();
return;
}
client = ClarifaiClientGenerator.generate(API_KEY);
final byte[] imageBytes = FileOp.getByteArrayFromIntentData(getContextOfApplication(), mediaScanIntent);
As of right now, imageBytes will be null as the the FileNotFound exception is thrown on that method call.
You can try this code...
public class Images extends Activity
{
private Uri[] mUrls;
String[] mFiles=null;
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.images);
File images = Environment.getDataDirectory();
File[] imagelist = images.listFiles(new FilenameFilter(){
#override
public boolean accept(File dir, String name)
{
return ((name.endsWith(".jpg"))||(name.endsWith(".png"))
}
});
mFiles = new String[imagelist.length];
for(int i= 0 ; i< imagelist.length; i++)
{
mFiles[i] = imagelist[i].getAbsolutePath();
}
mUrls = new Uri[mFiles.length];
for(int i=0; i < mFiles.length; i++)
{
mUrls[i] = Uri.parse(mFiles[i]);
}
Gallery g = (Gallery) findViewById(R.id.gallery);
g.setAdapter(new ImageAdapter(this));
g.setFadingEdgeLength(40);
}
public class ImageAdapter extends BaseAdapter{
int mGalleryItemBackground;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount(){
return mUrls.length;
}
public Object getItem(int position){
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent){
ImageView i = new ImageView(mContext);
i.setImageURI(mUrls[position]);
i.setScaleType(ImageView.ScaleType.FIT_XY);
i.setLayoutParams(new Gallery.LayoutParams(260, 210));
return i;
}
private Context mContext;
}
}
when I upload my captured webveiw(bitmap image), I use this :
public static void saveBitmaptoPng(Bitmap bitmap, String folder, String name) {
String ex_storage = Environment.getExternalStorageDirectory().getAbsolutePath();
// Get Absolute Path in External Sdcard
String foler_name = "/" + folder + "/";
String file_name = name + ".png";
String string_path = ex_storage + foler_name;
File file_path;
try {
file_path = new File(string_path);
if (!file_path.isDirectory()) {
file_path.mkdirs();
}
FileOutputStream out = new FileOutputStream(string_path + file_name);
**bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);**
out.close();
} catch (FileNotFoundException exception) {
Log.e("FileNotFoundException", exception.getMessage());
} catch (IOException exception) {
Log.e("IOException", exception.getMessage());
}
}
It is working well. but when I change 90 to 100 of Bitmap.CompressFormat,
I got an error whe getresponseCode
int serverResponseCode = connection.getResponseCode();
if (serverResponseCode == HttpURLConnection.HTTP_OK) {
is = new BufferedInputStream(connection.getInputStream());
} else {
is = new BufferedInputStream(connection.getErrorStream());
return null;
}
when changing from 90 to 100, process flow errorStream.... but I don't know any reasons.... even 95 is also not working well..
I am using string array to hold images, i am fetching the imaes from the URLs. I have one imageview which when swipped changes the images in it. Now i want to download and save any image i want on the SD card and want it to appear in the phone gallery in a new folder.
I am using the following code but it is not working, it is showing no error at all.
private class ImageDownloadAndSave extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... arg0) {
downloadImagesToSdCard("", "");
return null;
}
private void downloadImagesToSdCard(String downloadUrl, String imageName) {
try {
URL url = new URL(thumb[j]);
/* making a directory in sdcard */
String sdCard = Environment.getExternalStorageDirectory()
.toString();
File myDir = new File(sdCard, "test.jpg");
/* if specified not exist create new */
if (!myDir.exists()) {
myDir.mkdir();
Log.v("", "inside mkdir");
}
/* checks the file and if it already exist delete */
String fname = imageName;
File file = new File(myDir, fname);
if (file.exists())
file.delete();
/* Open a connection */
URLConnection ucon = url.openConnection();
InputStream inputStream = null;
HttpURLConnection httpConn = (HttpURLConnection) ucon;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
FileOutputStream fos = new FileOutputStream(file);
int totalSize = httpConn.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fos.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
Log.i("Progress:", "downloadedSize:" + downloadedSize
+ "totalSize:" + totalSize);
}
fos.close();
Log.d("test", "Image Saved in sdcard..");
} catch (IOException io) {
io.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
And i am executing it by
new ImageDownloadAndSave().execute("");
the name of my string array is "thumb" which is holding all the URLs. What am i doing wrong?
You should add image to gallery after save and then scan it. Please check the following topics:
Image, saved to sdcard, doesn't appear in Android's Gallery app
MediaScannerConnection
The file needs to be added to the Android MediaStore. This can be done easily by using below function.
public void scanFile(final File file) {
try {
new MediaScannerConnectionClient() {
private MediaScannerConnection mMs;
public void init() {
mMs = new MediaScannerConnection(myContext, this);
mMs.connect();
}
#Override
public void onMediaScannerConnected() {
mMs.scanFile(file.getAbsolutePath(), null);
mMs.disconnect();
}
#Override
public void onScanCompleted(String path, Uri uri) {
}
}.init();
} catch(Exception e) {
// Device does not support adding files manually.
// Sending Broadcast to start MediaScanner (slower than adding manually)
try {
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
} catch(Exception ee) {
// Something went terribly wrong.
// Can't add file to MediaStore and can't send Broadcast to start MediaScanner.
}
}
}
You just need to add one line to your code:
// .....
fos.close();
Log.d("test", "Image Saved in sdcard..");
scanFile(file); // <------------- add this
In my app I get base64 data of a file (doc, pdf, jpeg,...) and write it with FileWriter.
The file is now in my app-directory. But I need to move it to the Download directory of Android device.
Is it not possible to get access with this code:
window.resolveLocalFileSystemURL('content:///storage/emulated/0/Download', function(a) {},fail};
I always get error code 1.
In my android manifest.xml I currently just have WRITE_EXTERNAL_STORAGE permission. Is this enough?
Thanks. By the way I use cordova3.4 and android 4.3.
The sdcard path changes from device to device.
I suggest you read the File System plugin doc for complete information.
If you haven't modified config.xml to add <preference name="AndroidPersistentFileLocation" value="Internal" />, I'd say that this should do the job :
window.resolveLocalFileSystemURI('/Download', function(dirEntry) {},fail};
Or an other way :
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
function (fs) {
fs.root.getDirectory("/Download", {
create : false,
exclusive : false
}, function (dirEntry) { //success
//do here what you need to do with Download folder
}, function () {
//error getDirectory
});
},
function () {
//error requestFileSystem
}
);
this ll help u in Cordova to store file to ur requrired destination
public class FileDownload extends CordovaPlugin {
int serverResponseCode = 0;
ProgressDialog dialog = null;
String upLoadServerUri = null;
final String DownloadFilePath = null;
final String DownloadFileNameOne = null;
private final String PATH = "/storage/sdcard0/DestinationFoloder/";
public static final String ACTION_FILE_UPLOAD = "fileUploadAction";
#Override
public boolean execute(String action, JSONArray args,CallbackContext callbackContext) throws JSONException {
try {
if (ACTION_FILE_UPLOAD.equals(action)) {
File dir = new File("/storage/sdcard0/Destination");
if (dir.mkdir()) {
Log.e("Directory created","DC");
} else {
Log.e("Directory Not created","DNC");
}
JSONObject arg_object = args.getJSONObject(0);
String DownloadFilePath = arg_object.getString("path");
String DownloadFileNameOne = arg_object.getString("NameDwn");
fdownload(DownloadFilePath,DownloadFileNameOne);
callbackContext.success("Attachment Download Sucessfully!");
}
return false;
} catch (Exception e) {
System.err.println("Exception: " + e.getMessage());
callbackContext.error(e.getMessage());
return false;
}
}
private boolean fdownload(String downloadFilePath2, String downloadFileNameOne2) {
File FileCheck = new File(PATH+"/"+downloadFileNameOne2);
if(FileCheck.exists()){
return false;
}else{
try {
URL url = new URL(downloadFilePath2); // you can write here
// any
// link
Log.e("FilePath", "" + PATH + "" + downloadFileNameOne2);
File file = new File("" + PATH + "" + downloadFileNameOne2);
long startTime = System.currentTimeMillis();
URLConnection ucon;
ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to
* read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
return true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
}
}
Why not just use the Cordova plugin: cordova-plugin-file. The specific file location is: cordova.file.externalRootDirectory + "Download/". So apply window.resolveLocalFileSystemURL() to that.
Hey i am new in android application development.i currently develop
application, in some phase of that application deal with the image
store , retrieve and delete
how can i store whole image in android ? and how can i retrieve more
than one images which i uploaded in SQLite wants in gallery view?
please give me some guidance or link of blogs which deal with such
image processing in android
If u are dealing with images copy the image to separate folder and store the path in database OR store the image bytearray in db if size of image is small.
try this
public class ImageConvertScreen extends Activity implements OnClickListener {
/** Called when the activity is first created. */
Button img_byte,byte_img;
ImageView image;
TextView value;
public ByteArrayOutputStream bos;
public Bitmap bm;
public byte[] bitmapdata;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nextr);
image = (ImageView) findViewById(R.id.img_convert);
value=(TextView)findViewById(R.id.convert_txt);
img_byte =(Button)findViewById(R.id.img_byte);
byte_img =(Button)findViewById(R.id.byte_img);
img_byte.setOnClickListener(this);
byte_img.setOnClickListener(this);
String imgName = "ic_launcher";
String KEY_IMG = "/mnt/sdcard/DCIM/Camera/IMG_20121021_150153.jpg";
File f = new File(Environment.getExternalStorageDirectory(), KEY_IMG);
String path =Environment.getExternalStorageDirectory().getPath()+"/image4.png";
//bm = BitmapFactory.decodeFile(path);
bm = BitmapFactory.decodeResource(getResources(),getResId(imgName, R.drawable.class));
bos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 20 , bos);
}
public void onClick(View v) {
if (v == img_byte) {
bitmapdata = bos.toByteArray();
Log.w("Image Conversion", String.valueOf(bitmapdata.length));
String converted_txt="";
Toast.makeText(getBaseContext(), ""+bitmapdata.length,1).show();
for (int i = 0; i < bitmapdata.length; i++) {
Log.w("Image Conversion", String.valueOf(bitmapdata[i]));
converted_txt=converted_txt+bitmapdata[i];
}
saveImageOnSDCard1("testingImg",bitmapdata);
value.setText(converted_txt);
value.setVisibility(View.VISIBLE);
image.setVisibility(View.INVISIBLE);
} else if (v==byte_img){
bm = BitmapFactory.decodeByteArray(bitmapdata , 0, bitmapdata .length);
image.setImageBitmap(bm);
image.setVisibility(View.VISIBLE);
value.setText("");
value.setVisibility(View.INVISIBLE);
Log.w("Image Conversion", "converted");
}
}
public int getResId(String variableName, Class<?> c) {
Field field = null;
int resId = 0;
try {
field = c.getField(variableName);
try {
resId = field.getInt(null);
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return resId;
}
public static void saveImageOnSDCard1(String imageName, byte[] data) {
File file1 = new File(Environment.getExternalStorageDirectory()
+ "/isus/");
if (!file1.exists()) {
boolean isCreated = file1.mkdirs();
Log.e("Directory Created", "Directory Created " + isCreated);
}
File file = new File(Environment.getExternalStorageDirectory()
+ "/isus/" + imageName + ".png");
Log.i("path",""+file.getAbsolutePath().toString());
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(data);
} catch (Exception e) {
Log.i("err",""+e.getLocalizedMessage());
} finally {
try {
fileOutputStream.close();
} catch (Exception e2) {
}
}
}
}