logo
down
shadow

How to measure upload progress of a huge String with Retrofit 2?


How to measure upload progress of a huge String with Retrofit 2?

Content Index :

How to measure upload progress of a huge String with Retrofit 2?
Tag : android , By : Ansari
Date : November 20 2020, 04:01 AM

To fix this issue As in this example: Extend OkHttp3's RequestBody and overwrite writeTo(BufferedSink sink) for String yourHugeString instead of a file:
@Override
    public void writeTo(BufferedSink sink) throws IOException {
        StringReader in = new StringReader(yourHugeString);
        char[] buffer = new char[2048]; // you can modifiy the buffer
        try {
            int read;
            while ((read = in.read(buffer)) != -1) {
                sink.write(new String(buffer).getBytes(), 0, read);
                mListener.onProgressUpdate(read);
            }
        } finally {
            in.close();
            mListener.onFinish(uploaded);
        }
}
void postSpecialData(SpecialRequestBody base64, Callback callback);

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Is it possible to show progress bar when upload image via Retrofit 2?


Tag : android , By : Giles
Date : March 29 2020, 07:55 AM
I wish did fix the issue. First of all, you should use Retrofit 2 version equal to or above 2.0 beta2. Second, create new class extends RequestBody:
public class ProgressRequestBody extends RequestBody {
    private File mFile;
    private String mPath;
    private UploadCallbacks mListener;
    private String content_type;

  private static final int DEFAULT_BUFFER_SIZE = 2048;

    public interface UploadCallbacks {
        void onProgressUpdate(int percentage);
        void onError();
        void onFinish();
    }
public ProgressRequestBody(final File file, String content_type,  final  UploadCallbacks listener) {
    this.content_type = content_type;
    mFile = file;
    mListener = listener;            
}



@Override
    public MediaType contentType() {
        return MediaType.parse(content_type+"/*");
    }

@Override
public long contentLength() throws IOException {
  return mFile.length();
}

@Override
public void writeTo(BufferedSink sink) throws IOException {
    long fileLength = mFile.length();
    byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
    FileInputStream in = new FileInputStream(mFile);
    long uploaded = 0;

try {
            int read;
            Handler handler = new Handler(Looper.getMainLooper());
            while ((read = in.read(buffer)) != -1) {

            // update progress on UI thread
                handler.post(new ProgressUpdater(uploaded, fileLength));

                uploaded += read;
                sink.write(buffer, 0, read);
            }
        } finally {
            in.close();
        }
}

private class ProgressUpdater implements Runnable {
        private long mUploaded;
        private long mTotal;
        public ProgressUpdater(long uploaded, long total) {
            mUploaded = uploaded;
            mTotal = total;
        }

        @Override
        public void run() {
            mListener.onProgressUpdate((int)(100 * mUploaded / mTotal));            
        }
    }
}
@Multipart
    @POST("/upload")        
    Call<JsonObject> uploadImage(@Part MultipartBody.Part file);
class MyActivity extends AppCompatActivity implements ProgressRequestBody.UploadCallbacks {

        ProgressBar progressBar;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            progressBar = findViewById(R.id.progressBar);

            ProgressRequestBody fileBody = new ProgressRequestBody(file, this);
            MultipartBody.Part filePart = 

            MultipartBody.Part.createFormData("image", file.getName(), fileBody);

            Call<JsonObject> request = RetrofitClient.uploadImage(filepart);

             request.enqueue(new Callback<JsonObject>() {
             @Override
             public void onResponse(Call<JsonObject> call,   Response<JsonObject> response) {
                if(response.isSuccessful()){
                /* Here we can equally assume the file has been downloaded successfully because for some reasons the onFinish method might not be called, I have tested it myself and it really not consistent, but the onProgressUpdate is efficient and we can use that to update our progress on the UIThread, and we can then set our progress to 100% right here because the file already downloaded finish. */
                  }
            }

            @Override
            public void onFailure(Call<JsonObject> call, Throwable t) {
                      /* we can also stop our progress update here, although I have not check if the onError is being called when the file could not be downloaded, so I will just use this as a backup plan just in case the onError did not get called. So I can stop the progress right here. */
            }
        });

      }

        @Override
        public void onProgressUpdate(int percentage) {
            // set current progress
            progressBar.setProgress(percentage);
        }

        @Override
        public void onError() {
            // do something on error
        }

        @Override
        public void onFinish() {
            // do something on upload finished,
            // for example, start next uploading at a queue
            progressBar.setProgress(100);
        }

}

How to pass request string param using Retrofit for file Upload?


Tag : android , By : user157654
Date : March 29 2020, 07:55 AM
may help you . You can use @PartMap annotation to pass parameters along with File request. PartMap is a Map of "Key" and RequestBody. So first, you have to create RequestBody object of the parameter that you want to pass and then create Map object of it and pass it as argument.
For example your method in api interface would be,
@Multipart
    @POST("upload")
    Call<ResponseBody> uploadFileWithPartMap(
            @PartMap() Map<String, RequestBody> partMap,
            @Part MultipartBody.Part file);
MultipartBody.Part body = prepareFilePart("photo", fileUri);

// create a map of data to pass along
RequestBody token= RequestBody.create(
        MediaType.parse(MULTIPART_FORM_DATA), "token_string");
HashMap<String, RequestBody> map = new HashMap<>();  
map.put("token", token);  

-----------------

private MultipartBody.Part prepareFilePart(String partName, Uri fileUri) {  
    // https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java
    // use the FileUtils to get the actual file by uri
    File file = FileUtils.getFile(this, fileUri);

    // create RequestBody instance from file
    RequestBody requestFile =
        RequestBody.create(MediaType.parse(MULTIPART_FORM_DATA), file);

    // MultipartBody.Part is used to send also the actual file name
    return MultipartBody.Part.createFormData(partName, file.getName(), requestFile);
}
// finally, execute the request
Call<ResponseBody> call = service.uploadFileWithPartMap(map, body);  
call.enqueue(...);  

upload a file with retrofit and which has a progress bar


Tag : android , By : jrf
Date : March 29 2020, 07:55 AM
To fix the issue you can do If you are using Retrofit 2, maybe you could find this answer helpful Is it possible to show progress bar when upload image via Retrofit 2

How to measure Retrofit networking duration?


Tag : android , By : Tamizhvendan
Date : March 29 2020, 07:55 AM
wish help you to fix your issue You can use new OkHttp EventListener API: https://github.com/square/okhttp/wiki/Events
You can measure network duration with saving difference between callStart and callEnd

Retrofit 2 can't upload a file with two additional separate string parameters


Tag : android , By : ZsA
Date : March 29 2020, 07:55 AM
Related Posts Related QUESTIONS :
  • Hide title and action bar for splash screen and remove White screen in start
  • Why can not hashing key android for facebook
  • Can not create handler inside thread that has not called Looper.prepare()
  • ID of the child views in a custom view are same in Android
  • Android: unable to hide appbar on scrolling
  • Best layout for form-style screen
  • How To create multiple function in Adapter Class Android with Retrofit
  • Can the Android Flow virtual layout handle variable-width Views
  • How to fix "Unable to load class 'dagger.Multibindings'" due to problems with gradle
  • VpnService always-on "not supported by this app"
  • Android Studio - Gradle "Sync now" is not Available
  • How do i get my code to give my current location?
  • Could not initialize class sun.util.calendar.ZoneInfoFile while using Flutter firebase-notifications
  • How to implement circular to check / tick animation in Android?
  • Toolbar shadow not showing
  • Android Sqlite get rows where first character is not an Alphabet
  • why I receive "bad request" in my request by retrofit
  • Intercept NavigationUI.onNavDestinationSelected() to make backstack pop with "inclusive = true"
  • I have a problem with the navigation fragments in my proyect, it sais that I need a defaut nav host atribute but I alrea
  • How can I keep a BottomSheetDialogFragment height to always match_parent?
  • How to reference a timerPicker in android studio using kotlin
  • Firebase Crashlytics - get stacktrace info to display during CrashlyticsListener.crashlyticsDidDetectCrashDuringPrevious
  • Schedule a repeating alarm clock
  • Can't assign values outside onTouchListener
  • Is setContentView() needed to inflate a fragment?
  • Why instead of string method returns Kotlin.Unit?
  • Retrofit slash as Query
  • When does onCreateView() get called in this app?
  • Fragment is reloaded each time after rejecting location permission
  • How to read ViewModel data from sttrings.xml list of items
  • Flutter doctor does not see vs code ,VS code does not detect flutter/bin
  • How to build aar in flutter
  • Is displayMetrix xdpi and ydpi accurate?
  • How to detect doubletap on a View?
  • how to play an encrypted file in Android
  • Android: keytool error on the command line when locating debug.keystore
  • Android paint/canvas issue; drawing smooth curves
  • Problems with starting an activity in onStart
  • Performance of map overlay in conjunction with ItemizedOverlay is very poor
  • How to change android indeterminate ProgressBar color?
  • How do I change the Mobile Country Code (MCC) in the Android Emulator?
  • Stop Progressbar manual scrolling in Android
  • Android: download large file
  • Android : uploaded .apk file to server but cant download that .apk file
  • How do I distribute Android app to beta tester without using Market
  • Android Unable to launch the Inbox from a notification
  • Android: Ringer mode changed to silent doesn't stop the phone vibrating
  • Change the side the text appears on a radio button
  • Check the memory usage anp cpu and power of an application in android
  • What is the String 'volumeName' argument of MediaStore.Audio.Playlists.Members.getContentUri referring to?
  • Playing Multiple sounds at the same time in Android
  • Android: how to change the time in emulator?
  • close the soft key pad when i click on other views in android
  • Setting the position within a spinner
  • How to play ringtone/alarm sound in Android
  • How to adjust text font size to fit textview
  • "Android 2.x" vs "Google APIs" for Android AVD Setup
  • How to center buttons on screen horizontally and vertically plus equidistant apart?
  • Discrete seekbar in Android app?
  • Gradle Build Fails - Illegal exception table range in class file com/google/wireless/android/sdk/stats/GradleBuildMemory
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com