Input type file does not work in webview

7

I have an HTML page that has a form of uploading images in Chrome on your pc or in any browser works but in my application it has a WebView that opens this page then clicking choose file does nothing.

Is it possible to arrange this to choose a file or open the device's camera?

(choose only the file already solved)

Here is the code for my snippet:

public class F_Adm extends Fragment implements AdvancedWebView.Listener {

    private AdvancedWebView mWebView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.f_adm, container, false);

        mWebView = (AdvancedWebView) rootView.findViewById(R.id.webview);
        mWebView.setListener(getActivity(), this);

        mWebView.loadUrl("http://desapegogames.com.br/area-administrativa");

        return rootView;
    }

    @SuppressLint("NewApi")
    @Override
    public void onResume() {
        super.onResume();
        mWebView.onResume();
    }

    @SuppressLint("NewApi")
    @Override
    public void onPause() {
        mWebView.onPause();
        super.onPause();
    }

    @Override
    public void onDestroy() {
        mWebView.onDestroy();
        super.onDestroy();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        mWebView.onActivityResult(requestCode, resultCode, intent);
    }

    @Override
    public void onPageStarted(String url, Bitmap favicon) {
    }

    @Override
    public void onPageFinished(String url) {
    }

    @Override
    public void onPageError(int errorCode, String description, String failingUrl) {
        mWebView.loadUrl("file:///android_asset/offline.html");
    }

    @Override
    public void onDownloadRequested(String url, String suggestedFilename, String mimeType, long contentLength, String contentDisposition, String userAgent) {
    }

    @Override
    public void onExternalPageRequest(String url) {
    }
}
    
asked by anonymous 16.01.2017 / 17:36

1 answer

7

I will assist you in accordance with WebView documentation . Here is the schematic image of the visual component WebView :

Definingvariables:

privatestaticfinalStringTAG=TestActivity.class.getSimpleName();publicstaticfinalintINPUT_FILE_REQUEST_CODE=1;privateWebViewmeuWebView;privateValueCallback<Uri[]>mFilePathCallback;privateStringdiretorioFotoImagem;

DefiningamethodtostoreimagetemporarilyarmazenarImagemTemp():

privateFilearmazenarImagemTemp()throwsIOException{//CreateanimagefilenameStringtimeStamp=newSimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES);
    File imageFile = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );
    return imageFile;
}

Defining a method to adapt the default settings of WebView with the name setWebview :

 private void setWebview(WebView webView) {
    WebSettings set = webView.getSettings();

    // habilita javascript
    set.setJavaScriptEnabled(true);

    if(Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
        // oculta zoom no sdk HONEYCOMB+
        set.setDisplayZoomControls(false);
    }

    // habilita debugging remoto via chrome {inspect}
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        WebView.setWebContentsDebuggingEnabled(true);
    }
    meuWebView.setWebViewClient(new WebViewClient());
}

There can only be one onActivityResult() method in each Activity. This method is called following each call to startActivityForResult . When calling the startActivityForResult method, a requestCode is passed in the second parameter. See:

@Override
public void onActivityResult (int requestCode, int resultCode, Intent data) {
    if(requestCode != INPUT_FILE_REQUEST_CODE || mFilePathCallback == null) {
        super.onActivityResult(requestCode, resultCode, data);
        return;
    }

    Uri[] results = null;

    // verifica se a resposta esta ok com a variável estática {RESULT_OK} do Activity
    if(resultCode == Activity.RESULT_OK) {
        if(data == null) {
            // se não houver dados solicitará que tire uma foto
            if(diretorioFotoImagem != null) {
                results = new Uri[]{Uri.parse(diretorioFotoImagem)};
            }
        } else {
            String dataString = data.getDataString();
            if (dataString != null) {
                results = new Uri[]{Uri.parse(dataString)};
            }
        }
    }

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

Finishing with onCreate() which is the method responsible for loading layouts and other boot operations.

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test);

    // referencia o webview no layout/activity_main.xml
    meuWebView = (WebView) findViewById(R.id.webview);

    // define as configurações basicas
    setWebview(meuWebView);

    if (savedInstanceState != null) {
        // retaura o webview
        meuWebView.restoreState(savedInstanceState);
    }

    meuWebView.setWebChromeClient(new WebChromeClient() {
        public boolean onShowFileChooser(
                WebView webView, ValueCallback<Uri[]> filePathCallback,
                WebChromeClient.FileChooserParams fileChooserParams) {
            if(mFilePathCallback != null) {
                mFilePathCallback.onReceiveValue(null);
            }
            mFilePathCallback = filePathCallback;

            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                // cria local onde a foto deve ir
                File photoFile = null;
                try {
                    photoFile = armazenarImagemTemp();
                    takePictureIntent.putExtra("PhotoPath", diretorioFotoImagem);
                } catch (IOException ex) {
                    // Error occurred while creating the File
                    Log.e(TAG, "Unable to create Image File", ex);
                }

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

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

            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, INPUT_FILE_REQUEST_CODE);

            return true;
        }
    });

    // carrega a URL
    if(meuWebView.getUrl() == null) {
        meuWebView.loadUrl("http://192.168.0.3:8080/api.finan.com/");
    }
} 

Note: Do not forget to create WebView in your XLM.

To improve the code, check out in the documentation .

EDIT

As you pointed out in the comment the possibility of working in fragment , please do download here from the adaptation to work.

    
19.01.2017 / 17:50