example using uploadDirectory from android to S3 - java

Will someone please provide an example for uploading a bunch of photos to S3 using uploadDirectory? Say I have 300 photos in a directory named “special_photos” on my android device. And I want to upload all of these photos to Amazon S3. I figure uploadDirectory may be the best method for doing this. But being new to Amazon cloud, I don’t know how I might do it. All I have gleaned so far is that the method executes asynchronously and so can be called from the main thread. I keep finding php codes on the internet. But I don’t use PHP. Does anyone have a complete working example they don’t mind sharing with the community? I am using the SDK via gradle on Android Studio. Also, is there some kind of callback for knowing when all the photos have been uploaded? Say for instance I want to delete the photos and the directory once they have been uploaded.

There is no uploadDirectory but there is Multipart Upload. This will do your large data upload to S3. As stated HERE, the Multipart Upload Docs say:
Using the list multipart uploads operation, you can obtain a list of multipart uploads in progress. An in-progress multipart upload is an upload that you have initiated, but have not yet completed or aborted. Each request returns at most 1000 multipart uploads. If there are more than 1000 multipart uploads in progress, you need to send additional requests to retrieve the remaining multipart uploads.
To address the callback, there is a completion called once all of the TransferUtility items are uploaded. This open source adds listeners applied to the upload function. I would recommend breaking up your calls to 30 at a time, then delete the corresponding photos - in case there is a failure with the upload. There is a success and fail return, so obviously only delete in case of success.
HERE is the AWS documentation for Android Multipart Uploads
HERE is an article that will help migrate & understand the differences between TransferManager and TransferUtility
HERE is a good article on getting started with the Android TransferManager
And HERE is an open source demo - under the S3_TransferManager
Hope this helps!
Update:
The below code is all taken from #awslabs references
Create client:
public static AmazonS3Client getS3Client(Context context) {
if (sS3Client == null) {
sS3Client = new AmazonS3Client(getCredProvider(context.getApplicationContext()));
}
return sS3Client;
}
Create TransferUtility:
public static TransferUtility getTransferUtility(Context context) {
if (sTransferUtility == null) {
sTransferUtility = new TransferUtility(getS3Client(context.getApplicationContext()),
context.getApplicationContext());
}
return sTransferUtility;
}
Use TransferUtility to get all upload transfers:
observers = transferUtility.getTransfersWithType(TransferType.UPLOAD);
Add your records: - you could iterate over the file names in your directory
HashMap<String, Object> map = new HashMap<String, Object>();
Util.fillMap(map, observer, false);
transferRecordMaps.add(map);
This starts everything:
private void beginUpload(String filePath) {
if (filePath == null) {
Toast.makeText(this, "Could not find the filepath of the selected file",
Toast.LENGTH_LONG).show();
return;
}
File file = new File(filePath);
TransferObserver observer = transferUtility.upload(Constants.BUCKET_NAME, file.getName(),
file);
observers.add(observer);
HashMap<String, Object> map = new HashMap<String, Object>();
Util.fillMap(map, observer, false);
transferRecordMaps.add(map);
observer.setTransferListener(new UploadListener());
simpleAdapter.notifyDataSetChanged();
}
This is your completion:
private class GetFileListTask extends AsyncTask<Void, Void, Void> {
// The list of objects we find in the S3 bucket
private List<S3ObjectSummary> s3ObjList;
// A dialog to let the user know we are retrieving the files
private ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(DownloadSelectionActivity.this,
getString(R.string.refreshing),
getString(R.string.please_wait));
}
#Override
protected Void doInBackground(Void... inputs) {
// Queries files in the bucket from S3.
s3ObjList = s3.listObjects(Constants.BUCKET_NAME).getObjectSummaries();
transferRecordMaps.clear();
for (S3ObjectSummary summary : s3ObjList) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("key", summary.getKey());
transferRecordMaps.add(map);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
dialog.dismiss();
simpleAdapter.notifyDataSetChanged();
}
}

You can send a List to your service that is using TransferUtility to upload multiple images. At least that is how I was able to make it work.

Related

How to generate access token in Java for Google AutoML Vision API without gcloud?

I am making an Android App that will utilize the Google AutoML Vision API. I am looking for a way to get a permanent access token or generate them in code so that I do not need to use gcloud everytime I want to use my app. How would I go about doing this?
I have created the AutoML model, set up my service account, and coded my app in Android Studio so that it makes the request to the API using Volley. The problem is, they require you to generate and pass an access token using gcloud. I can generate the token and put it in my code but it only lasts for an hour and then it expires. The REST API requires the access token as shown below.
curl -X POST -H "Content-Type: application/json" \
-H "Authorization: Bearer $(gcloud auth application-default print-access-
token)"
I have looked into different ways around this problem. For example, there are some Google Client Libraries for Java and Google Cloud Applications that show how to add the service account credentials into the code. I am confused how I would add the Json key file into the code when running it from a phone. I have also read that Firebase could be used but I am unfamiliar about what the process for that would be.
Currently, I will open up gcloud on my computer, generate the access token, paste it into my code and run the app as follows with the header and this returns the desired results for up to an hour until the access code expires.
#Override
public Map<String, String> getHeaders() throws AuthFailureError{
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "Bearer " + accesstoken);
return headers;
}
I would like this to be a stand alone application that can run on an Android phone. What is the best way to go about doing this?
UPDATE:
I was able to add the file into Android Studio and then use some functions to get an access token and it appears to work in the Emulator. I am not sure how secure this method is though because the json file with the key needs to be kept private.
InputStream is = getAssets().open("app.json");
GoogleCredentials credentials =
GoogleCredentials.fromStream(i).createScoped(Lists.newArrayList(scope));
credentials.refreshIfExpired();
AccessToken accesstoken = credentials.getAccessToken();
Add firebase to you android project. https://firebase.google.com/docs/android/setup You will create a project in Firebase and download a json file for configuration and add it in app directory. Add also dependencies in gradle files.
On Firebase console go to ML Kit section and create a AUTML model with your photos.
Train the model
When the training is finished you can download your model and downloaded 3 files in your assets/model directory. And it is ready to use. By this way you will use Firebase AutoML SDK and you dont need to generate the token.
Use your model and do predictions from application.
Steps are :
Prepare image for prediction
Prepare the model
Get the image labeler
Process the image for classification
public void findLabelsWithAutoML() {
Bitmap bitmap = null;
File file = new File(currentPhotoPath);
System.out.println("file "+file);
try {
bitmap = MediaStore.Images.Media
.getBitmap(getContentResolver(), Uri.fromFile(file));
} catch (Exception e) {
e.printStackTrace();
}
FirebaseVisionImageMetadata metadata = new FirebaseVisionImageMetadata.Builder()
.setWidth(480) // 480x360 is typically sufficient for
.setHeight(360) // image recognition
.setFormat(FirebaseVisionImageMetadata.IMAGE_FORMAT_NV21)
.setRotation(FirebaseVisionImageMetadata.ROTATION_0)
.build();
FirebaseVisionImage firebaseVisionImage = FirebaseVisionImage.fromBitmap(bitmap);
System.out.println("firebaseVisionImage :"+firebaseVisionImage);
FirebaseAutoMLLocalModel localModel = new FirebaseAutoMLLocalModel.Builder()
.setAssetFilePath("model/manifest.json")
.build();
FirebaseVisionOnDeviceAutoMLImageLabelerOptions labelerOptions = new FirebaseVisionOnDeviceAutoMLImageLabelerOptions.Builder(localModel)
.setConfidenceThreshold(0.65F) // Evaluate your model in the Firebase console
// to determine an appropriate value.
.build();
FirebaseVisionImageLabeler firebaseVisionImageLabeler = null;
try {
firebaseVisionImageLabeler = FirebaseVision.getInstance().getOnDeviceAutoMLImageLabeler(labelerOptions);
} catch (Exception e) {
e.printStackTrace();
}
firebaseVisionImageLabeler.processImage(firebaseVisionImage)
.addOnSuccessListener(new OnSuccessListener<List<FirebaseVisionImageLabel>>() {
#Override
public void onSuccess(List<FirebaseVisionImageLabel> labels) {
for (FirebaseVisionImageLabel label : labels) {
System.out.println("label " + label.getText() + " score: " + (label.getConfidence() * 100));
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
//
}
});
}

I want show upload percent

I have an app that users can upload file. Right now it works.
They can upload files and it received in server side.
Now I want show upload percent to users while uploading.
I used below code to upload files on server.
here is my java code:
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
new MaterialFilePicker().
withActivity(AddActivity.this).
withRequestCode(10).
start();
}
catch (Exception e){
return;
}
}
});
and this is my method:
ProgressDialog progress;
#Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
if (requestCode==10 && resultCode==RESULT_OK){
progress = new ProgressDialog(AddActivity.this);
progress.setTitle("Uploading");
progress.setMessage("please wait...");
progress.show();
Thread t = new Thread(new Runnable() {
#Override
public void run() {
File f = new File(data.getStringExtra(FilePickerActivity.RESULT_FILE_PATH));
String content_type = getMimeType(f.getPath());
String file_path = f.getAbsolutePath();
file_size = String.valueOf(f.length()/1024);
OkHttpClient client = new OkHttpClient();
RequestBody file_body = RequestBody.create(MediaType.parse(content_type),f);
RequestBody request_body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("type",content_type)
.addFormDataPart("upload_file",code+file_path.substring(file_path.lastIndexOf(".")),file_body)
.build();
code2 = code+file_path.substring(file_path.lastIndexOf("."));
Request request = new Request.Builder()
.url("http://api.mysite.com/api/uploadfile")
.post(request_body)
.build();
try {
Response response = client.newCall(request).execute();
Log.d("msg",request_body.toString());
Log.d("msg",f.getPath().toString());
Log.d("msg",getMimeType(f.getPath()));
Log.d("msg33",code+file_path.substring(file_path.lastIndexOf(".")));
if (!response.isSuccessful()){
throw new IOException(("Error:"+response));
}
progress.dismiss();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t.start();
}
}
Please help me to add upload percentage.
Thank you
You are doing a lot of things wrong here:
Logic responsible for uploading file should not be located in onActivityResult()
You should seperate it into different method
Using thread like that is not a good idea
If you want to upload file or large file you should do it in IntentService class (You will have to create Your own class and extend IntentService), it is something that is meant for things like that. I suggest You to learn about Retrofit2 and OkHttp library cause it will make it a lot of easier.
An example where you can find a one of the ways how to do it is here: Is it possible to show progress bar when upload image via Retrofit 2?
Asking ppl at stackoverflow to write code completly for you is not a good way to improve your skills. Check this link which I gave You.
Good luck
EDIT:
Android Services: http://www.vogella.com/tutorials/AndroidServices/article.html and https://developer.android.com/training/run-background-service/create-service
Retrofit 2: http://www.vogella.com/tutorials/Retrofit/article.html
OkHttp: https://www.journaldev.com/13629/okhttp-android-example-tutorial
Sample: Is it possible to show progress bar when upload image via Retrofit 2?
These link provides all the information You need in order to write this functionality. I don't have videos on YouTube with things like this. I'm never using YouTube to get this kind of information.

Drive REST API V3 Java Wrapper - upload with progress

I'm trying to upload a new file to a drive account using the V3 API and get upload progress. My current(working) code is the following:
val fileMetadata = File()
fileMetadata.name = newItemName
fileMetadata.parents = mutableListOf(destFolder.remoteId)
val osFile = java.io.File(filePath)
val mediaContent = FileContent(getMimeType(filePath), osFile)
val file = googleDriveService.files().create(fileMetadata, mediaContent)
.setFields("*")
.execute()
Is it possible to add some kind of a progress listener to a current solution or i need to use another service(like MediaHttpUploader)?
You may refer with this documentation which uses the CustomProgressListener class.
class CustomProgressListener implements MediaHttpDownloaderProgressListener {
public void progressChanged(MediaHttpDownloader downloader) {
switch (downloader.getDownloadState()) {
case MEDIA_IN_PROGRESS:
System.out.println(downloader.getProgress());
break;
case MEDIA_COMPLETE:
System.out.println("Download is complete!");
}
}
}
OutputStream out = new FileOutputStream("/tmp/driveFile.jpg");
DriveFiles.Get request = drive.files().get(fileId);
request.getMediaHttpDownloader().setProgressListener(new CustomProgressListener());
request.executeMediaAndDownloadTo(out);
Here are additional references you can use:
How to get progress of a file being downloaded from google drive using REST API?
File Upload with Java (with progress bar)
Google Drive API Progress Bar Bug

I need to download several images to directory so that content can be accessed offline

I get some JSON data which contains some food menu items
Please note: this is just a sample, there are more than 2 images sometimes and many more menu items in the array!
{
"menu": [
{
"url": "/api/v1/menu/1",
"name": "Best Food",
"description": "really nice food",
"opening_time": "every day from 9am to 6pm",
"contact_email": "info#food.com",
"tel_number": "+54 911 3429 5762",
"website": "http://bestfood.com",
"images": [
{
"url": "https://blahblah/image1.jpg"
},
{
"url": "https://blahblah/image2.jpg"
}
]
},
]
}
Each item has some info and an array of image URLs.
I am using the Glide image library to process these images and Retrofit 2.0 to download the JSON data from the endpoint. All is well at this point.
However, I need to store this downloaded data for offline access.
Currently, I am using ORM Lite on my existing models to store all the JSON data in a database. This part is OK.
However, in my database I only store the image URLs as I was told that it is not good approach to store images (as blob) in the database.
So there is a section in my app to view the saved menu's with an option to download it for offline access if the user chooses to.
It is worth mentioning at this point, that I already have the raw menu information in the database because the user would have to view the menu in the first place to get it in DB.
But the problem is the images.
This is where I do not know how to proceed, but I list the solutions and problems that I am thinking about and was hoping people could advise me on what is the best course of action is.
Use a service to download the images. This I feel is mandatory because I do not know how many images there will be, and I want the download to proceed even if user exits the app
Glide has a download only option for images and you can configure where its cache is located (internal private or external public) as I read here and here. Problem is I do not feel comfortable with setting the cache size as I do not know what is required. I would like to set unlimited.
I need to be able to delete the saved menu data especially if its saved on the external public directory as this is not removed when the app is deleted etc. or if the user chooses to delete a saved menu from within the app. I was thinking I could store the file image URIs or location of the entire saved menu in database for this but not sure if this is a good way
I read in different sources and answers that in this use case for just caching images to SD card etc. that I should specifically use a network library to do so to avoid the allocation of a bitmap to heap memory. I am using OK HTTP in my app at the moment.
I'm using ormlite to store objects with urls too, I have a synchronization after the "sign in" screen on my app, on my experience I really recommend this library https://github.com/thest1/LazyList
It's very simple:
ImageLoader imageLoader=new ImageLoader(context);
imageLoader.DisplayImage(url, imageView);
This library saves the image using the url on the external sd with basic and simple configuration about the memory issues, so if you actually have two or more items with the same url this library works perfectly, the url and imageView are the parameters, if the image is not on the phone begins a new task and put the image in the view when the download is finish, and btw this library also saves the images encoded, so these pictures don't appear on the gallery.
Actually you only need these files to implement the library:https://github.com/thest1/LazyList/tree/master/src/com/fedorvlasov/lazylist
If you wanna manipulate some files, you can change the folder name in the FileCache class:
public FileCache(Context context){
//Find the dir to save cached images
...
cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"LazyList");
...
}
Where "LazyList" is the folder name, and them you can delete, move, etc.
Delete sample:
/**
* This method delete a file if exist
*/
public static void deleteFile(File file){
if(file!=null && file.exists()) {
file.delete();
}
}
Now I learned more about memory cache and the allocation of a bitmap to heap memory, for the first time manipulating images online and offline, I recommend this library, also when you learn more about it, you can implement and edit the library to your needs.
1: Use an IntentService to do your downloads.
http://developer.android.com/reference/android/app/IntentService.html
2: Set up your IntentService using AlarmManager so that it runs even if the
application is not running. You register with the AlarmManager
http://developer.android.com/reference/android/app/AlarmManager.html
There are a variety of ways you can have the AlarmManager start your
intent.
For Example:
// Register first run and then interval for repeated cycles.
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + DEFAULT_INITIAL_RUN,
DEFAULT_RUN_INTERVAL, pi);
3: Storing Data
There are several options here depending on how public you want your
pictures/data to be.
http://developer.android.com/reference/android/os/Environment.html
Example: External Public Storage
File dirBackup = Environment.getExternalStoragePublicDirectory(
"YourDirectory" );
4: Downloading
Your option here. You can using anything from your current API to a
basic URLConnection.
You may want to look at:
http://developer.android.com/reference/android/app/DownloadManager.html
Also, watch your permissions you will need to add
and
Hope this points you in a useful direction.
Try out this library to manage images loading.
Use a service to download the images. This I feel is mandatory because
I do not know how many images there will be, and I want the download
to proceed even if user exits the app
All downloading done in worker threads so it's alive while application process is alive. There may a problem appear: application dies while loading is in progress. To workaround this I suggest to use AlarmManager in combination with Service. Set it up to start by timer, check you database or UIL cache for image files being not loaded and start their loading again.
Glide has a download only option for images and you can configure
where its cache is located (internal private or external public) as I
read here and here. Problem is I do not feel comfortable with setting
the cache size as I do not know what is required. I would like to set
unlimited.
UIL has several disc cache implementations out of the box including unlimited one. It also provides you cache interface so you can implement your own.
I need to be able to delete the saved menu data especially if its
saved on the external public directory as this is not removed when the
app is deleted etc. or if the user chooses to delete a saved menu from
within the app. I was thinking I could store the file image URIs or
location of the entire saved menu in database for this but not sure if
this is a good way
UIL generates unique filename for each loaded file using provided file link. You can delete any loaded image or cancel any download using link from your JSON.
I read in different sources and answers that in this use case for just
caching images to SD card etc. that I should specifically use a
network library to do so to avoid the allocation of a bitmap to heap
memory. I am using OK HTTP in my app at the moment.
UIL does it OK. It manages memory very accurately also provide you several options for memory management configuration. For example you can choose between several memory cache implementations out of the box.
In conclusion I suggest you to the visit the link above and read library documentation/description by yourself. It's very flexible and contatins lots of useful features.
Using a service can be a good option if you want the downloads to continue even if the user exits. Images that are stored in directories created using getExternalStorageDirectory() are automatically deleted when your app is uninstalled. Moreover you can check if the internal memory is large enough to store images. If you use this methods these images will be deleted upon the uninstallion of the app.
I use this class when downloading images, it caches the images, next time you will be downloading them it will just load from external memory, it manages the cache for you as well so you wont have to worry about setting cache to limited or unlimited, pretty efficient and fast.
public class ImageLoader {
MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews = Collections
.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
// Handler to display images in UI thread
Handler handler = new Handler();
public ImageLoader(Context context) {
fileCache = new FileCache(context);
executorService = Executors.newFixedThreadPool(5);
}
final int stub_id = R.drawable.placeholder;
public void DisplayImage(String url, ImageView imageView) {
imageViews.put(imageView, url);
Bitmap bitmap = memoryCache.get(url);
if (bitmap != null)
imageView.setImageBitmap(bitmap);
else {
queuePhoto(url, imageView);
imageView.setImageResource(stub_id);
}
}
private void queuePhoto(String url, ImageView imageView) {
PhotoToLoad p = new PhotoToLoad(url, imageView);
executorService.submit(new PhotosLoader(p));
}
private Bitmap getBitmap(String url) {
File f = fileCache.getFile(url);
Bitmap b = decodeFile(f);
if (b != null)
return b;
// Download Images from the Internet
try {
Bitmap bitmap = null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageUrl
.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
conn.disconnect();
bitmap = decodeFile(f);
return bitmap;
} catch (Throwable ex) {
ex.printStackTrace();
if (ex instanceof OutOfMemoryError)
memoryCache.clear();
return null;
}
}
// Decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream stream1 = new FileInputStream(f);
BitmapFactory.decodeStream(stream1, null, o);
stream1.close();
// Find the correct scale value. It should be the power of 2.
// Recommended Size 512
final int REQUIRED_SIZE = 70;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
FileInputStream stream2 = new FileInputStream(f);
Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
stream2.close();
return bitmap;
} catch (FileNotFoundException e) {
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
// Task for the queue
private class PhotoToLoad {
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i) {
url = u;
imageView = i;
}
}
class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
PhotosLoader(PhotoToLoad photoToLoad) {
this.photoToLoad = photoToLoad;
}
#Override
public void run() {
try {
if (imageViewReused(photoToLoad))
return;
Bitmap bmp = getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
if (imageViewReused(photoToLoad))
return;
BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
handler.post(bd);
} catch (Throwable th) {
th.printStackTrace();
}
}
}
boolean imageViewReused(PhotoToLoad photoToLoad) {
String tag = imageViews.get(photoToLoad.imageView);
if (tag == null || !tag.equals(photoToLoad.url))
return true;
return false;
}
// Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable {
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
bitmap = b;
photoToLoad = p;
}
public void run() {
if (imageViewReused(photoToLoad))
return;
if (bitmap != null)
photoToLoad.imageView.setImageBitmap(bitmap);
else
photoToLoad.imageView.setImageResource(stub_id);
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
}
To use it Just create an instance of it like
ImageLoader Imageloaer = new ImageLoader(getBaseContext());
Imageloaer.DisplayImage(imageUrl, imageView);
You should try downloading with this,
class DownloadFile extends AsyncTask<String,Integer,Long> {
ProgressDialog mProgressDialog = new ProgressDialog(MainActivity.this);// Change Mainactivity.this with your activity name.
String strFolderName;
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.setMessage("Downloading Image ...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setCancelable(false);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.show();
}
#Override
protected Long doInBackground(String... aurl) {
int count;
try {
URL url = new URL((String) aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
String targetFileName="downloadedimage.jpg";//Change name and subname
int lenghtOfFile = conexion.getContentLength();
String PATH = Environment.getExternalStorageDirectory()+"/myImage/";
File folder = new File(PATH);
if(!folder.exists()){
folder.mkdir();//If there is no folder it will be created.
}
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(PATH+targetFileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress ((int)(total*100/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(Integer... progress) {
mProgressDialog.setProgress(progress[0]);
if(mProgressDialog.getProgress()==mProgressDialog.getMax()){
mProgressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Download Completed !", Toast.LENGTH_LONG).show();
}
}
protected void onPostExecute(String result) {
}
}
This code will let you to download all the url of images,
new DownloadFile().execute("https://i.stack.imgur.com/w4kCo.jpg");
.....
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Change Folder Name as you desired and try to set this images to app bitmap and also avoiding rotate error of images by using this.
The important things to think about here is
Thread , Service ,File , Json, Context,Receiver & if else & for
maybe i did not understand your question but this is not a big deal sir,
your programm your app to work in way where your app starts when the os broadcast onBootCompleted, then create a Thread where you are going to do a lot of code - getting your json file-(when you need it), since its an array you get your jsonObject images, whether its a thousand or million you just iterate it and use any approach to download it, i'd say use the traditional way of downloading your images so as you better control it.
With the help of File class you save it alongside Context you can get your app's cache's directory, which is an internal memory save it there and create a column in your database where you can save the path to the file in your database as String.
When your app start in onPrepareOptionsMenu() check if your app's cache's directory is empty-if not you have some files, now since you have every file and its respective path you can check if it exists with File.exist() if it does no need to download.
if you need pace you can always create new Threads. The Reciever was to be the guy who gets notified when your device boots, if else for a lot of logic checking, for for your loopings, Service to be able to do long running work and have a way to communicate between the UI and background thread.
sorry for the last paragraph i was just trying to buy space :)

Network error from google services in Android

I am developing an app in which i have an integrated google drive. I want to store images captured by the device under a folder in google drive.
By doing so in result.getstatus() method from google service is returning {statusCode=Failed to retrieve item from a network}
I am using following function,
final ResultCallback<DriveIdResult> idCallback = new ResultCallback<DriveIdResult>() {
#Override
public void onResult(DriveIdResult result) {
System.out.println("result.getStatus()----"+ result.getStatus());
System.out.println("result.getStatus() code----"+ result.getStatus().getStatusCode());
if (!result.getStatus().isSuccess()) {
showMessage("Cannot find DriveId. Are you authorized to view this file?");
return;
}
DriveFolder folder = Drive.DriveApi
.getFolder(getGoogleApiClient(), result.getDriveId());
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle("NewFolder").build();
folder.createFolder(getGoogleApiClient(), changeSet)
.setResultCallback(createFolderCallback);
}
};
In first println---> I am getting {statusCode=Failed to retrieve item from a network}
In second println--> I am getting 7
Please help me...
I have the same status code when the file is permanently deleted. Remove any cached DriveId / resource id and create the new file.

Categories

Resources