Загрузка изображения в Cloudinary не удалась в Android - PullRequest
1 голос
/ 02 мая 2019

Я пытаюсь загрузить изображение в Cloudinary после нажатия на изображение с камеры. Камера работает нормально, но после нажатия на изображение приложение снова и снова падает. Пытался отладить его, но не получил, где у меня ошибка.

LOGCAT:
beginning of crash
05-03 00:29:58.243 4880-4880/com.example.maaz.taxit E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.maaz.taxit, PID: 4880
    java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=null} to activity {com.example.maaz.taxit/com.example.maaz.taxit.ImageDeleteTest}: android.os.NetworkOnMainThreadException
        at android.app.ActivityThread.deliverResults(ActivityThread.java:3699)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:3742)
        at android.app.ActivityThread.-wrap16(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1393)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
     Caused by: android.os.NetworkOnMainThreadException
        at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
        at java.net.InetAddress.lookupHostByName(InetAddress.java:431)
        at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
        at java.net.InetAddress.getAllByName(InetAddress.java:215)
        at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
        at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:188)
        at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:157)
        at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:100)
        at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:357)
        at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:340)
        at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330)
        at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:433)
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:114)
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:245)
        at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getOutputStream(DelegatingHttpsURLConnection.java:218)
        at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java)
        at com.cloudinary.android.MultipartUtility.<init>(MultipartUtility.java:52)
        at com.cloudinary.android.UploaderStrategy.callApi(UploaderStrategy.java:48)
        at com.cloudinary.Uploader.callApi(Uploader.java:22)
        at com.cloudinary.Uploader.upload(Uploader.java:55)
        at com.example.maaz.taxit.ImageDeleteTest.onActivityResult(ImageDeleteTest.java:63)
        at android.app.Activity.dispatchActivityResult(Activity.java:6428)
        at android.app.ActivityThread.deliverResults(ActivityThread.java:3695)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:3742) 
        at android.app.ActivityThread.-wrap16(ActivityThread.java) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1393) 
        at android.os.Handler.dispatchMessage(Handler.java:102) 
        at android.os.Looper.loop(Looper.java:148) 
        at android.app.ActivityThread.main(ActivityThread.java:5417) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

Я пытался жестко запрограммировать URL-адреса примеров изображений, но они все еще не работают. Может быть, проблема с этой линией cloudinary.uploader().upload(photoFile.getAbsolutePath(), ObjectUtils.emptyMap());

public static final int TAKE_PHOTO_REQUEST = 0;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == TAKE_PHOTO_REQUEST) {
            if (resultCode == RESULT_OK) {
                //File to upload to cloudinary
                Toast.makeText(this, "Pakistan Zinabad", Toast.LENGTH_SHORT).show();
                Map config = new HashMap();
                config.put("cloud_name", "nomancloud");
                config.put("api_key", "myKey");
                config.put("api_secret", "mySecretApi");
                Cloudinary cloudinary = new Cloudinary(config);

                try {
                    cloudinary.uploader().upload(photoFile.getAbsolutePath(), ObjectUtils.emptyMap());
                } catch (IOException e) {
                    e.printStackTrace();
                }

            } else if (resultCode == RESULT_CANCELED) {
                // User cancelled the image capture
                //finish();
            }
        }

    }


    private File createImageFile() throws IOException {
        // Create an image file name

        String imageFileName = "capturedImage";
        File storageDir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        return image;
    }

 @Override
    public void onClick(View v) {

        Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        if (takePhotoIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go
        photoFile = null;

        try {
        photoFile = createImageFile();
        }
        catch (IOException ex) {
        // Error occurred while creating the File
        }

        // Continue only if the File was successfully created
        if (photoFile != null) {
            takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT,
            Uri.fromFile(photoFile));
            startActivityForResult(takePhotoIntent, TAKE_PHOTO_REQUEST);
            }
        }
    }

1 Ответ

0 голосов
/ 03 мая 2019

Можете ли вы попробовать использовать:

Map uploadResult = cloudinary.uploader().upload("http://res.cloudinary.com/demo/image/upload/sample.jpg", ObjectUtils.emptyMap());

и распечатать RuntimeException / uploadResult?

...