Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Webview File chooser not open in LG G2 (4.4.2 version) #71

Closed
rkandroid opened this issue Jul 29, 2016 · 1 comment
Closed

Webview File chooser not open in LG G2 (4.4.2 version) #71

rkandroid opened this issue Jul 29, 2016 · 1 comment

Comments

@rkandroid
Copy link

I have one problem with LG G2 running Kitkat. On other devices running Kitkat, the problem does not appear

My Problem is that File Chooser doesn't show with the mentioned devices.

What I'm currently doing:

private WebView web;

@OverRide
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_event);

    web = (WebView) findViewById(R.id.webView_addEvent);
    web.loadUrl(tempURL);

    startWebViewForLolipop();

}

private void startWebViewForLolipop() {

//CODING FOR LOLIPOP VERSION

// Create new webview Client to show progress dialog
// Called When opening a url or click on link
// You can create external class extends with WebViewClient
// Taking WebViewClient as inner class

web.setWebViewClient(new WebViewClient() {
    // ProgressDialog progressDialog;

    //If you will not use this method url links are open in new brower not in webview
    public boolean shouldOverrideUrlLoading(WebView view, String url) {

        // Check if Url contains ExternalLinks string in url
        // then open url in new browser
        // else all webview links will open in webview browser
        if (url.contains("google")) {

            // Could be cleverer and use a regex
            //Open links in new browser
            view.getContext().startActivity(
                    new Intent(Intent.ACTION_VIEW, Uri.parse(url)));

            // Here we can open new activity

            return true;

        } else {

            // Stay within this webview and load url
            view.loadUrl(url);
            return true;
        }

    }


    //Show loader on url load
    public void onLoadResource(WebView view, String url) {

        // if url contains string androidexample
        // Then show progress  Dialog
      /*  if (progressDialog == null *//*&& url.contains("androidexample")*//*
                ) {

            // in standard case YourActivity.this
            progressDialog = new ProgressDialog(AddEvent.this);
            progressDialog.setMessage("Loading...");
            progressDialog.show();
        }*/
    }

    // Called when all page resources loaded
    public void onPageFinished(WebView view, String url) {

        try {
            // Close progressDialog

            if (probressbar.isShown())
                probressbar.setVisibility(View.GONE);

        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }

});


// You can create external class extends with WebChromeClient
// Taking WebViewClient as inner class
// we will define openFileChooser for select file from camera or sdcard

web.setWebChromeClient(new WebChromeClient() {

    // openFileChooser for Android 3.0+
    public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {

        // Update message
        mUploadMessage = uploadMsg;

        try {

            // Create ImgDir Folder at sdcard

            File imageStorageDir = new File(
                    Environment.getExternalStoragePublicDirectory(
                            Environment.DIRECTORY_PICTURES)
                    , "ImgDir");

            if (!imageStorageDir.exists()) {

                // Create AndroidExampleFolder at sdcard
                imageStorageDir.mkdirs();

            } else {

                //Delete Old Content
                if (imageStorageDir.isDirectory()) {

                    String[] children = imageStorageDir.list();
                    for (int i = 0; i < children.length; i++) {
                        new File(imageStorageDir, children[i]).delete();
                    }
                }

                imageStorageDir.delete();

                // Create AndroidExampleFolder at sdcard
                imageStorageDir.mkdirs();

            }

            // Create camera captured image file path and name
            File file = new File(
                    imageStorageDir + File.separator + "IMG_"
                            + String.valueOf(System.currentTimeMillis())
                            + ".jpg");

            mCapturedImageURI = Uri.fromFile(file);

            // Camera capture image intent
            final Intent captureIntent = new Intent(
                    android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

            captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);

            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");

            // Create file chooser intent
            Intent chooserIntent = Intent.createChooser(i, "Image Chooser");

            // Set camera intent to file chooser
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS
                    , new Parcelable[]{captureIntent});

            // On select image call onActivityResult method of activity
            startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);

        } catch (Exception e) {
            Toast.makeText(getBaseContext(), "Exception:" + e,
                    Toast.LENGTH_LONG).show();
        }

    }

    // openFileChooser for Android < 3.0
    public void openFileChooser(ValueCallback<Uri> uploadMsg) {
        openFileChooser(uploadMsg, "");
    }

    //openFileChooser for other Android versions
    public void openFileChooser(ValueCallback<Uri> uploadMsg,
                                String acceptType,
                                String capture) {

        openFileChooser(uploadMsg, acceptType);
    }


    // The webPage has 2 filechoosers and will send a
    // console message informing what action to perform,
    // taking a photo or updating the file

    public boolean onConsoleMessage(ConsoleMessage cm) {

        onConsoleMessage(cm.message(), cm.lineNumber(), cm.sourceId());
        return true;
    }

    public void onConsoleMessage(String message, int lineNumber, String sourceID) {
        Log.d("androidruntime", "Show console messages, Used for debugging: " + message);

    }
});   // End setWebChromeClient

/*

web.setWebChromeClient(new WebChromeClient() {

    public boolean onShowFileChooser(
            WebView webView, ValueCallback<Uri[]> filePathCallback,
            WebChromeClient.FileChooserParams fileChooserParams) {

        // Double check that we don't have any existing callbacks
        if (mFilePathCallback != null) {
            mFilePathCallback.onReceiveValue(null);
        }
        mFilePathCallback = filePathCallback;

       */

/* File imageStorageDir = new File(
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES)
, "ImgDir/addEvent");

        if (!imageStorageDir.exists()) {
            // Create ImgDir/addEvent  Folder at sdcard
            imageStorageDir.mkdirs();
        }

        // Create camera captured image file path and name
        File file = new File(
                imageStorageDir + File.separator + "IMG_"
                        + String.valueOf(System.currentTimeMillis())
                        + ".jpg");


        mCapturedImageURI = Uri.fromFile(file);*//*

       */

/* if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mFilePathCallback = filePathCallback;

            try {
                Intent intent = fileChooserParams.createIntent();
                startActivityForResult(intent, 1);
            } catch (Exception e) {
                // TODO: when open file chooser failed
            }
        } else {*//*

            // Set up the take picture intent
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(AddEvent.this.getPackageManager()) != null) {
                // Create the File where the photo should go

                File photoFile = null;

                try{

                    photoFile = createImageFile();
                    takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);


                } catch (IOException e){
                    e.printStackTrace();

                    Log.e("TAG", "Unable to create Image File", e);
                }


                // Continue only if the File was successfully created
                if (photoFile != null) {
                    mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                            Uri.fromFile(photoFile));
                } else {
                    takePictureIntent = null;
                }
            }

            // Set up the intent to get an existing image
            Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
            contentSelectionIntent.setType("image*/

/*");

            // Set up the intents for the Intent chooser
            Intent[] intentArray;
            if (takePictureIntent != null) {
                intentArray = new Intent[]{takePictureIntent};
            } else {
                intentArray = new Intent[0];
            }

            Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
            chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
            chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);

            startActivityForResult(chooserIntent, 1);
       // }
        return true;
    }


});
*/

}

@OverRide
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {

if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {

    super.onActivityResult(requestCode, resultCode, intent);

    if (requestCode == FILECHOOSER_RESULTCODE) {

        if (null == this.mUploadMessage) {
            return;

        }

        Uri result = null;

        try {
            if (resultCode != RESULT_OK) {

                result = null;

            } else {

                // retrieve from the private variable if the intent is null
                //result = intent == null ? mCapturedImageURI : intent.getData();

                Log.d("TAG", "Image File Path : " + mCapturedImageURI);
                String test = intent.toString();
                if (intent == null) {

                    String temp  = decodeFile(mCapturedImageURI.getPath(), getImageName(mCapturedImageURI.getPath()));
                    result = Uri.parse("file:///"+temp);
                    //result = mCapturedImageURI;

                } else {
                    if (test.equals("Intent {  }")) {
                        String temp  = decodeFile(mCapturedImageURI.getPath(), getImageName(mCapturedImageURI.getPath()));
                        result = Uri.parse("file:///"+temp);
                        //result = mCapturedImageURI;
                    } else {
                        String temp  = decodeFile(intent.getData().toString(), getImageName(intent.getData().toString()));
                        result = Uri.parse("file:///"+temp);

                        result = Uri.parse(decodeFile(intent.getData().toString(), getImageName(intent.getData().toString())));
                        //result = intent.getData();
                    }
                }

               /* // retrieve from the private variable if the intent is null
                String test = intent.toString();
                if (intent == null) {

                    result = mCapturedImageURI;
                } else {
                    if (test.equals("Intent {  }")) {
                        result = mCapturedImageURI;
                    } else
                        result = intent.getData();
                }*/
            }
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), "activity :" + e,
                    Toast.LENGTH_LONG).show();
        }

        mUploadMessage.onReceiveValue(result);
        mUploadMessage = null;
    }

} else {

/* if (requestCode == 1 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mFilePathCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, intent));
mFilePathCallback = null;
return;
} else {*/

    if (requestCode == FILECHOOSER_RESULTCODE) {

        //// TODO: 23/6/16 temporary comment this code
        /*if (requestCode != 1 || mFilePathCallback == null) {
            super.onActivityResult(requestCode, resultCode, intent);
            return;
        }*/

        if (null == this.mUploadMessage) {
            return;
        }

        Uri result = null;

        try {
            if (resultCode != RESULT_OK) {

                result = null;
            } else {
                // retrieve from the private variable if the intent is null
                //result = intent == null ? mCapturedImageURI : intent.getData();

                Log.d("TAG", "Image File Path : " + mCapturedImageURI);

                if (intent == null) {

                    String temp  = decodeFile(mCapturedImageURI.getPath(), getImageName(mCapturedImageURI.getPath()));
                    result = Uri.parse("file:///"+temp);
                    //result = mCapturedImageURI;

                } else {
                    String test = intent.toString();

                    if (test.equals("Intent {  }")) {
                        String temp  = decodeFile(mCapturedImageURI.getPath(), getImageName(mCapturedImageURI.getPath()));
                        result = Uri.parse("file:///"+temp);
                        //result = mCapturedImageURI;
                    } else {
                        String temp  = decodeFile(intent.getData().toString(), getImageName(intent.getData().toString()));
                        result = Uri.parse("file:///"+temp);

                        result = Uri.parse(decodeFile(intent.getData().toString(), getImageName(intent.getData().toString())));
                        //result = intent.getData();
                    }
                }
            }
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), "activity :" + e, Toast.LENGTH_LONG).show();
        }
        mUploadMessage.onReceiveValue(result);
        mUploadMessage = null;

       /* Uri[] results = null;

        // Check that the response is a good one
        if (resultCode == Activity.RESULT_OK) {
            if (intent == null) {
                // If there is not data, then we may have taken a photo
                if (mCameraPhotoPath != null) {
                    results = new Uri[]{Uri.parse(mCameraPhotoPath)};
                }
            } else {
                String dataString = intent.getDataString();
                if (dataString != null) {
                    results = new Uri[]{Uri.parse(dataString)};
                }
            }
        }

        mFilePathCallback.onReceiveValue(results);
        mFilePathCallback = null;
        return;*/
        //  }
    }
}

}

@ocram
Copy link
Contributor

ocram commented Jul 30, 2016

My Problem is that File Chooser doesn't show with the mentioned devices.

Yes, that's because it does not work on Android 4.4 due to a bug in the operating system, see #4

On other devices running Kitkat, the problem does not appear

That would be strange. See above.

@ocram ocram closed this as completed Jul 30, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants