Issue
I have an E-Store with Wordpress WooCommerce and my store working very well I mean all features like product add, product image gallery images upload, etc everything working very well. I have created an Android Webview Application and everything working good but I am not able to upload files like product images files I cant upload. When I access my website via Application there everything works well only I am not able to upload images or any files. but when I access my website on the browser on mobile everything works well including files or images upload everything works correctly.
Androidmanifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.store.storenisa">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.storenis"
android:usesCleartextTraffic="true">
<activity
android:name=".MainActivity"
android:exported="true" />
<activity
android:name=".SplashActivity"
android:exported="true"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity.java
package com.store.storenisa;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
public class MainActivity extends AppCompatActivity {
String websiteURL = "https://mystore.com/"; // sets web url
private WebView webview;
SwipeRefreshLayout mySwipeRefreshLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if( ! CheckNetwork.isInternetAvailable(this)) //returns true if internet available
{
//if there is no internet do this
setContentView(R.layout.activity_main);
//Toast.makeText(this,"No Internet Connection, Chris",Toast.LENGTH_LONG).show();
new AlertDialog.Builder(this) //alert the person knowing they are about to close
.setTitle("No internet connection found")
.setMessage("Please Check you're Mobile data or Wifi network.")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
//.setNegativeButton("No", null)
.show();
}
else
{
//Webview stuff
webview = findViewById(R.id.webView);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setDomStorageEnabled(true);
webview.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
webview.loadUrl(websiteURL);
webview.setWebViewClient(new WebViewClientDemo());
}
//Swipe to refresh functionality
mySwipeRefreshLayout = (SwipeRefreshLayout)this.findViewById(R.id.swipeContainer);
mySwipeRefreshLayout.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
webview.reload();
}
}
);
}
private class WebViewClientDemo extends WebViewClient {
@Override
//Keep webview in app when clicking links
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
mySwipeRefreshLayout.setRefreshing(false);
}
}
//set back button functionality
@Override
public void onBackPressed() { //if user presses the back button do this
if (webview.isFocused() && webview.canGoBack()) { //check if in webview and the user can go back
webview.goBack(); //go back in webview
} else { //do this if the webview cannot go back any further
new AlertDialog.Builder(this) //alert the person knowing they are about to close
.setTitle("EXIT")
.setMessage("Are you sure, You want to close this app?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
}
}
class CheckNetwork {
private static final String TAG = CheckNetwork.class.getSimpleName();
public static boolean isInternetAvailable(Context context)
{
NetworkInfo info = (NetworkInfo) ((ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (info == null)
{
Log.d(TAG,"no internet connection");
return false;
}
else
{
if(info.isConnected())
{
Log.d(TAG," internet connection available...");
return true;
}
else
{
Log.d(TAG," internet connection");
return true;
}
}
}
}
Thank you.
Solution
Add this Line and Check Please
package com.example.filechooser;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends Activity {
// variables para manejar la subida de archivos
private final static int FILECHOOSER_RESULTCODE = 1;
private ValueCallback<Uri[]> mUploadMessage;
// variable para manejar el navegador empotrado
WebView mainWebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// instanciamos el webview
mainWebView = findViewById(R.id.main_web_view);
// establecemos el cliente interno para que la navegacion no se salga de la aplicacion
mainWebView.setWebViewClient(new MyWebViewClient());
// establecemos el cliente chrome para seleccionar archivos
mainWebView.setWebChromeClient(new MyWebChromeClient());
// configuracion del webview
mainWebView.getSettings().setJavaScriptEnabled(true);
// cargamos la pagina
mainWebView.loadUrl("https://example.com");
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
// manejo de seleccion de archivo
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == mUploadMessage || intent == null || resultCode != RESULT_OK) {
return;
}
Uri[] result = null;
String dataString = intent.getDataString();
if (dataString != null) {
result = new Uri[]{ Uri.parse(dataString) };
}
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
// ====================
// Web clients classes
// ====================
/**
* Clase para configurar el webview
*/
private class MyWebViewClient extends WebViewClient {
// permite la navegacion dentro del webview
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
/**
* Clase para configurar el chrome client para que nos permita seleccionar archivos
*/
private class MyWebChromeClient extends WebChromeClient {
// maneja la accion de seleccionar archivos
@Override
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
// asegurar que no existan callbacks
if (mUploadMessage != null) {
mUploadMessage.onReceiveValue(null);
}
mUploadMessage = filePathCallback;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*"); // set MIME type to filter
MainActivity.this.startActivityForResult(Intent.createChooser(i, "File Chooser"), MainActivity.FILECHOOSER_RESULTCODE );
return true;
}
}
}
Answered By - Vijay S