0

I have just started using Android, but I have used the Java language in the past.

I have loaded a web application in an android WebWiew. The app was published successfully but the file browse buttons did not work. I have tried searching for many days, but most of the code that I tried, either did not work or is outdated.

Related, answers on the internet too, are for old Android versions or were answered many years ago. For example, startActivityForResult() is now deprecated.

The file selection dialog does open, but after selecting the file nothing happens. The ActivityResult.getResultCode() is always returned as 0) zero.

This is the string version of the result:

ActivityResult{resultCode=RESULT_CANCELED, data=null}

For now, I Just want the browse button file selections to work, so that these get uploaded with the form.

I have tried changing the permissions, and almost everything that I could.

Target SDK version is 33 Min SDK version is 25

I am posting the code that I have tried. For testing, I have replaced the app with a simple html page. I have tried accept='image/*' , attributes as well. Please let me know what I am missing?


    public class MainActivity extends AppCompatActivity {
    
        private WebView webView;
        private static final int FILE_CHOOSER_ACTIVITY_CODE = 1;
        private ValueCallback<Uri[]> filePath;
        private ActivityResultLauncher<Intent> activityResultLauncher;
    
        protected void onCreate(Bundle savedInstanceState) {
    
            String webUrl = getString(R.string.hosting_url);
            super.onCreate(savedInstanceState);
            if (getSupportActionBar() != null) {
                getSupportActionBar().hide();
            }
    
            setContentView(R.layout.activity_main);
            webView = findViewById(R.id.webView);
            WebSettings webSettings = webView.getSettings();
    
            webView.setWebViewClient(new CustomWebViewClient());
            webSettings.setJavaScriptEnabled(true);
            webSettings.setDomStorageEnabled(true);
            webSettings.setSupportZoom(false);
            //webSettings.setAllowFileAccess(true);
            //webSettings.setAllowContentAccess(true);
    
            webView.addJavascriptInterface(new WebAppInterface(this), "Android");
    
            activityResultLauncher = registerForActivityResult(
                    new ActivityResultContracts.StartActivityForResult(),
                    new ActivityResultCallback<ActivityResult>() {
                        @Override
                        public void onActivityResult(ActivityResult result) {
                            if (filePath != null) {
                                filePath.onReceiveValue(null);
                            }
                            System.out.println(result);
                            Log.d("info", "Result code is " + result.getResultCode());
                            if (result.getResultCode() == FILE_CHOOSER_ACTIVITY_CODE) {
                                Uri[] results = null;
    
                                Log.d("Info", "Result code  " + result.getResultCode());
                                //if (result.getResultCode() == Activity.RESULT_OK) {
                                Intent data = result.getData();
                                //Uri uri = new Uri(data.getData());
                                if (data != null) {
                                    if (null == filePath) {
                                        return;
                                    }
                                    results = new Uri[]{data.getData()};
                                    filePath.onReceiveValue(results);
                                    System.out.println(results.toString());
                                }
                                //} else {
                                //    filePath = null;
                                //}
                            }
    
                        }
                    }
    
            );
    
            webView.setWebChromeClient(new WebChromeClient() {
                @Override
                public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
                    filePath = filePathCallback;
                    if (checkPermissions()) {
                        Intent getContent = new Intent(Intent.ACTION_GET_CONTENT);
                        //getContent.addCategory(Intent.CATEGORY_OPENABLE);
                        getContent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        getContent.setType("*/*");
                        //String[] mimeTypes = {"text/*", "image/"};
                        //getContent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
                        //getContent.createChooser(getContent, "Choose a File");
    
                        activityResultLauncher.launch(getContent);
    
                        return true;
    
                    } else {
                        Toast.makeText(MainActivity.this, "Permissions are required", Toast.LENGTH_SHORT);
                    }
    
                    return false;
                }
    
            });
    
    
        }
    
        public boolean checkPermissions() {
    
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    //|| ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
            ) {
                String requiredPermissions[] = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
                ActivityCompat.requestPermissions(MainActivity.this, requiredPermissions, 1);
                return false;
            } else {
                return true;
            }
        }
    
         ....
         ....
    }

AndroidManifest.xml


    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools">
        <uses-permission android:name="android.permission.INTERNET"/>
        <uses-permission android:name="android.permission.STORAGE" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
        <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
        <!-- <uses-feature android:name="android.hardware.camera" android:required="true" />
        <uses-permission android:name="android.permission.CAMERA" /> -->
    
        <application
            android:allowBackup="true"
            android:dataExtractionRules="@xml/data_extraction_rules"
            android:fullBackupContent="@xml/backup_rules"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/Theme.abc"
            tools:targetApi="31"
            android:usesCleartextTraffic="true">
            <activity
                android:name=".MainActivity"
                android:exported="true"
                android:configChanges="orientation|screenSize"
                >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
    
    
        </application>
    
    </manifest>

test.html


    <html>
    <head>
        <title>
            Upload
        </title>
    </head>
    <body>
        <form method='post' enctype='multipart/form-data' action=''>
    <input type="file"/>
            <input type='submit' value='Upload Now' />
        </form>
    </body>
    </html>

Sukh
  • 13
  • 5
  • https://stackoverflow.com/questions/76319946/uploading-files-through-the-camera-is-0-bytes-but-if-its-via-the-gallery-its-o – blackapps May 24 '23 at 06:07
  • Thank you @blackapps. That question has helped. Thankfully, that question was posted today :-) I will work on it and post the result, or ask a question, if I face some problem. – Sukh May 24 '23 at 12:21

0 Answers0