Home > Net >  Error while uploading images to Imgur with api in Android
Error while uploading images to Imgur with api in Android

Time:10-20

I am working with the Imgur API for uploading images. The image is clicked using a camera and stored as a bitmap which is further converted into Base-64 String.

I'm then passing the Base-64 string to a function which should upload the image to Imgur. But the code returns the Error: android.os.NetworkOnMainThreadException

Image capture and convert to Base-64:

ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        if (result.getResultCode() == Activity.RESULT_OK) {
                            //Bitmap part
                            Intent data = result.getData();
                            Bitmap captureImage=(Bitmap) data.getExtras().get("data");
                            //Base-64 part 
                            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                            captureImage.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
                            byte[] byteArray = byteArrayOutputStream .toByteArray();
                            String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);

                            upload(encoded);
                            //profilePic.setImageBitmap(captureImage);
                        }
                    }
                });
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Camera Capture
                Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                someActivityResultLauncher.launch(intent);
            }
        });

Code to upload:

public void upload(String encoded){
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("text/plain");
        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("image",encoded)
                .build();
        Request request = new Request.Builder()
                .url("https://api.imgur.com/3/image")
                .method("POST", body)
                .addHeader("Authorization", "Client-ID {{MY_ID}}")
                .build();
        try {
            Response response = client.newCall(request).execute();
            Log.wtf("RESPONSE","" response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

I'm using Android Studio and running the app on an AVD (API-30) if that matters.

CodePudding user response:

Run your upload() function on background thread:

ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            new ActivityResultCallback<ActivityResult>() {
                @Override
                public void onActivityResult(ActivityResult result) {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        //Bitmap part
                        Intent data = result.getData();
                        Bitmap captureImage=(Bitmap) data.getExtras().get("data");
                        //Base-64 part 
                        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                        captureImage.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
                        byte[] byteArray = byteArrayOutputStream .toByteArray();
                        String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);

new Thread(new Runnable() {
@Override
public void run() {
    upload(encoded);  //background stuff
    runOnUiThread(new Runnable() {
        public void run() {
            // do onPostExecute stuff
        }
    });
}
}).start();                        
                        //profilePic.setImageBitmap(captureImage);
                    }
                }
            })

Note:The above solution is not the best way of doing async task.The best option is Rxjava/RxAndroid for asynchronous task.

  • Related