I want show upload percent - java

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.

Related

how to (integrate)call post API with 2 parameters and 1 PDF file in android java

How to attach PDF file to post API with two parameter? I am using Fast android networking library.
I am able to call API but I when user touched button my API called in my API have three parameters like this:
message = "Test"
receiver_Email = "#gmail.com"
File = text.PDF;
Sy API allows only PDF form met with message and email. I am using Fast android networking library. I try to call API but I am not able to do it.
I also looked at some examples but it couldn't help me out.
just call this method from your onCreate this is the easy way to call API with file and parameter I hope it helps you
//method used to call API to send email
enter code here
#RequiresApi(API = Build.VERSION_CODES.LOLLIPOP_MR1)
public void call_Api()
{
final String key = "file";
final File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "/test.pdf");
AndroidNetworking.initialize(this);
AndroidNetworking.upload("your API")
.setPriority(Priority.HIGH)
.addMultipartParameter("message", "test")
.addMultipartParameter("receiverEmail","testrg0017#gmail.com")
.addMultipartFile(key, file)
.setPriority(Priority.HIGH)
.build()
.getAsJSONObject(new JSONObjectRequestListener()
{
#Override
public void onResponse(JSONObject response)
{
Log.d("res ",response.toString());
if(file.exists())
{
Toast.makeText(PdfGeneration.this, "API call successfully",
Toast.LENGTH_SHORT).show();
}
}
#Override
public void onError(ANError anError)
{
anError.printStackTrace();
Log.d("res12 ",anError.toString());
if(!file.exists())
{
Toast.makeText(PdfGeneration.this, "file not available",
Toast.LENGTH_SHORT).show();
}
}
});
}

Keep receiving this error "Failed to initialize detector". Am I not loading the tflite model correctly?

I am trying to setup an ImageAnalyzer with my Android app so I can run object classification using Google's ML Kit API. The issue I am currently facing, as the title suggests, is constantly seeing the error "Failed to initialize detector".
I've reread this tutorial about three times now and followed this post about someone facing the same error (although for a different reason) to no avail. I've also made sure everything with the CameraX API (except the ImageAnalyzer code that I will show in a second) works as expected.
As mentioned in the ML Kit documentation, here is the code I have regarding setting up a LocalModel, a CustomObjectDetectorOptions, and an ObjectDetector:
LocalModel localModel = new LocalModel.Builder()
.setAssetFilePath("mobilenet_v1_1.0_224_quantized_1_metadata_1.tflite")
.build();
CustomObjectDetectorOptions customObjectDetectorOptions =
new CustomObjectDetectorOptions.Builder(localModel)
.setDetectorMode(CustomObjectDetectorOptions.STREAM_MODE)
.enableClassification()
.setClassificationConfidenceThreshold(0.5f)
.setMaxPerObjectLabelCount(3)
.build();
ObjectDetector objectDetector = ObjectDetection.getClient(customObjectDetectorOptions);
Here is the ImageAnalyzer code I have, which basically makes a call to the ML Kit API by way of the processImage helper method:
// Creates an ImageAnalysis for analyzing the camera preview feed
ImageAnalysis imageAnalysis = new ImageAnalysis.Builder()
.setTargetResolution(new Size(224, 224))
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
.build();
imageAnalysis.setAnalyzer(ContextCompat.getMainExecutor(this),
new ImageAnalysis.Analyzer() {
#Override
public void analyze(#NonNull ImageProxy imageProxy) {
#SuppressLint("UnsafeExperimentalUsageError") Image mediaImage =
imageProxy.getImage();
if (mediaImage != null) {
Log.i(TAG, "Obtained ImageProxy object");
processImage(mediaImage, imageProxy)
.addOnCompleteListener(new OnCompleteListener<List<DetectedObject>>() {
#Override
public void onComplete(#NonNull Task<List<DetectedObject>> task) {
imageProxy.close();
}
});
}
}
});
Here is the processImage helper method, where I actually call objectDetector.process(...), the line of code that actually runs the tflite model.
private Task<List<DetectedObject>> processImage(Image mediaImage, ImageProxy imageProxy) {
InputImage image =
InputImage.fromMediaImage(mediaImage,
imageProxy.getImageInfo().getRotationDegrees());
return objectDetector.process(image)
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
String error = "Failed to process. Error: " + e.getMessage();
Log.i(TAG, error);
}
})
.addOnSuccessListener(new OnSuccessListener<List<DetectedObject>>() {
#Override
public void onSuccess(List<DetectedObject> results) {
String success = "Object(s) detected successfully!";
Log.i(TAG, success);
for (DetectedObject detectedObject : results) {
Rect boundingBox = detectedObject.getBoundingBox();
Integer trackingId = detectedObject.getTrackingId();
for (DetectedObject.Label label : detectedObject.getLabels()) {
String text = label.getText();
int index = label.getIndex();
float confidence = label.getConfidence();
Log.i(TAG, "Object detected: " + text + "; "
+ "Confidence: " + confidence);
}
}
}
});
}
Essentially, once I run the app, logcat just keeps logging these two lines on repeat. I know it means the ImageAnalyzer is continuously trying to analyze the image input, but for some reason the LocalModel just cannot process the input
2021-01-21 22:02:24.020 9328-9328/com.example.camerax I/MainActivity: Obtained ImageProxy object
2021-01-21 22:02:24.036 9328-9328/com.example.camerax I/MainActivity: Failed to process. Error: Failed to initialize detector.
I have only just started to work with Android, especially ML in Android, so any sort of help would be appreciated!
I managed to fix my issue before anyone answered, but in case anyone who just started to learn Android like me I'll leave my solution here.
Basically, remember to create an asset folder in the /src/main directory rather than the /src/androidTest directory :P
Once I did that, the model loaded correctly and now I just have to figure out how to display the results in my application.
// Do NOT compress tflite model files (need to call out to developers!)
aaptOptions {
noCompress "tflite"
}
add this line in build gradle for app under android tag

Google Play Games Services: Writing saved games

Due to the recent changes in the Google Play Games Service API I'm forced to replace all the deprecated code in my Android app. I'm following the Google guide in https://developers.google.com/games/services/android/savedgames and it's not clear for me how to pass the snapshot to this function that writes the data to be saved.
private Task writeSnapshot(Snapshot snapshot, byte[] data, Bitmap coverImage, String desc) {
// Set the data payload for the snapshot
snapshot.getSnapshotContents().writeBytes(data);
// Create the change operation
SnapshotMetadataChange metadataChange = new SnapshotMetadataChange.Builder()
.setCoverImage(coverImage)
.setDescription(desc)
.build();
SnapshotsClient snapshotsClient =
Games.getSnapshotsClient(this, GoogleSignIn.getLastSignedInAccount(this));
// Commit the operation
return snapshotsClient.commitAndClose(snapshot, metadataChange);
}
Can you help me? I think an example of use of this function should be added to the documentation to make everything clearer and to help developers who need to learn this from scratch.
Ok, I realized how to do it. Basically, when you open the snapshot client, you must use continueWith and obtain the snapshot from the task.
Considering you have a proper cover image and description and a Google account where you signed in
mAccount = GoogleSignIn.getLastSignedInAccount(activity);
this is the code:
SnapshotsClient snapshotsClient = Games.getSnapshotsClient(activity, mAccount);
int conflictResolutionPolicy = SnapshotsClient.RESOLUTION_POLICY_MOST_RECENTLY_MODIFIED;
snapshotsClient.open(getSaveFileName(), true, conflictResolutionPolicy)
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e(TAG, "Error", e);
}
}).continueWith(new Continuation<SnapshotsClient.DataOrConflict<Snapshot>, byte[]>() {
#Override
public byte[] then(#NonNull Task<SnapshotsClient.DataOrConflict<Snapshot>> task)
throws Exception {
Snapshot snapshot = task.getResult().getData();
snapshot.getSnapshotContents().writeBytes(getSaveGameData());
SnapshotMetadataChange metadataChange = new SnapshotMetadataChange.Builder()
.setCoverImage(coverImage)
.setDescription(desc)
.build();
SnapshotsClient snapshotsClient = Games.getSnapshotsClient(activity, mAccount);
snapshotsClient.commitAndClose(snapshot, metadataChange);
return null;
}
});

ProgressDialog not showing while uploading images into server with StrictMode.ThreadPolicy

ProgressDialog is showing only if I am sending text but when I sent images it gave me an error which tells that there are lot of activities running or the app can't handle all of it, the solution is to add StrictMode.ThreadPolicy before invoking those tasks but the problem is ProgressDialog is not showing anymore which is important to tell the user about the ongoing process.
I believe it is StrictMode.ThreadPolicy that causes the ProgressDialog to disappear. I am not using Asynctask that's why I haven't found solution on the Internet yet because most of them are using it. I am also planning to use Asynctask but my boss did not approve it, he's afraid that it will ruin the app.
{
private void upLoadImage(String path){
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder().permitAll().penaltyDialog().build();
StrictMode.setThreadPolicy(policy);
uploadMedia(path);}}
{
private void uploadMedia(String path) {
String ImageName = "image_name";
String ImagePath = "image_path";
try {
String charset = "UTF-8";
File uploadFile1 = new File(path);
String requestURL= "http://myurl";
MultipartUtility multipart = new MultipartUtility(requestURL,
charset);
multipart.addFormField(ImageName, "iName");
multipart.addFormField(ImagePath, "iPath");
multipart.addFilePart("uploadedfile", uploadFile1);
List<String> response = multipart.finish();
Log.v("rht", "SERVER REPLIED:");
for (String line : response) {
Log.v("rht", "Line : "+line);
if(line=="true"||line=="Saved"){
progressDialog.dismiss();
}
}
// Toast.makeText(this, ""+response, Toast.LENGTH_SHORT).show();
finish();
} catch (Exception e) {
e.printStackTrace();
}
}
}
if you access Network in UI thread the error is shown.You cannot do the network operations in the main thread.It is better to use a worker thread or ayntask. But if you are willing to accept the consequences, and must do network operations on the main thread, you can override the default behavior:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

example using uploadDirectory from android to S3

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.

Categories

Resources