1. Are you ready for the Galaxy S20? Here is everything we know so far!

[WebView] Uploading pictures from camera and gallery in Android application, need help

Discussion in 'Android Development' started by hk1337, Nov 25, 2020.

  1. hk1337

    hk1337 Lurker
    Thread Starter

    Hello, I'm building a webview application. There is a feature of uploading images through the form on the site. What I am trying to do is: When File input is clicked, the user is asked the option "Select from camera or gallery". I did this. Image can be uploaded from the gallery. But after taking a picture with the camera, the input remains blank. The picture disappears. It works fine on Android 5 version, but I have this problem on versions such as Android 10, 9, 8, 7, 6. I think the reason why it doesn't work on Android 10 is the removal of getExternalStoragePublicDirectory support. But it doesn't work on Android 6-7-8-9 version either. I'm a just back-end web developer. I'm not good at mobile programming. I would appreciate it if you can send source code or project. Please help me. Thank you!

    My code:

    Code (Java):
    1. import android.Manifest;
    2. import android.annotation.SuppressLint;
    3. import android.app.Activity;
    4. import android.app.AlertDialog;
    5. import android.content.Context;
    6. import android.content.DialogInterface;
    7. import android.content.Intent;
    8. import android.content.pm.ApplicationInfo;
    9. import android.content.pm.PackageManager;
    10. import android.content.res.Configuration;
    11. import android.net.ConnectivityManager;
    12. import android.net.Uri;
    13. import android.os.Build;
    14. import android.os.Bundle;
    15. import android.os.Environment;
    16. import android.provider.MediaStore;
    17. import android.util.Log;
    18. import android.view.KeyEvent;
    19. import android.view.View;
    20. import android.webkit.ValueCallback;
    21. import android.webkit.WebChromeClient;
    22. import android.webkit.WebSettings;
    23. import android.webkit.WebView;
    24. import android.webkit.WebViewClient;
    25. import android.widget.Button;
    26. import android.widget.Toast;
    27.  
    28. import androidx.annotation.NonNull;
    29. import androidx.appcompat.app.AppCompatActivity;
    30. import androidx.core.app.ActivityCompat;
    31. import androidx.core.content.ContextCompat;
    32.  
    33. import java.io.File;
    34. import java.io.IOException;
    35. import java.text.SimpleDateFormat;
    36. import java.util.Date;
    37. import java.util.List;
    38.  
    39. public class Ucuncu_ekran extends AppCompatActivity{
    40. WebView webView;
    41. private static final String TAG = Ucuncu_ekran.class.getSimpleName();
    42. private String mCM;
    43. private ValueCallback mUM;
    44. private ValueCallback<Uri[]> mUMA;
    45. private final static int FCR=1;
    46.  
    47.  
    48. @Override
    49. protected void onActivityResult(int requestCode, int resultCode, Intent intent){
    50.  
    51.  
    52.     super.onActivityResult(requestCode, resultCode, intent);
    53.     if(Build.VERSION.SDK_INT >= 21){
    54.         Uri[] results = null;
    55.         //Check if response is positive
    56.         if(resultCode== Activity.RESULT_OK){
    57.             if(requestCode == FCR){
    58.                 if(null == mUMA){
    59.                     return;
    60.                 }
    61.                 if(intent == null){
    62.                     //camera selected
    63.                     //Capture Photo if no image available
    64.                     if(mCM != null){
    65.                         results = new Uri[]{Uri.parse(mCM)};
    66.                     }
    67.                 }else{
    68.                     //gallery selected
    69.                     String dataString = intent.getDataString();
    70.                     if(dataString != null){
    71.                         results = new Uri[]{Uri.parse(dataString)};
    72.                     }
    73.                 }
    74.             }
    75.         }
    76.         mUMA.onReceiveValue(results);
    77.         mUMA = null;
    78.     }else{
    79.         if(requestCode == FCR){
    80.             if(null == mUM) return;
    81.             Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
    82.             mUM.onReceiveValue(result);
    83.             mUM = null;
    84.         }
    85.     }
    86. }
    87.  
    88. AlertDialog.Builder builder;
    89. String test = "";
    90. Button closeButton;
    91.  
    92. @SuppressLint({"SetJavaScriptEnabled", "WrongViewCast"})
    93. @Override
    94. protected void onCreate(Bundle savedInstanceState){/*
    95.     requestWindowFeature(Window.FEATURE_NO_TITLE);
    96.     this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
    97.     getSupportActionBar().hide();*/
    98.  
    99.  
    100.     boolean b = uygulamaYukluMu("com.android.camera");
    101.     super.onCreate(savedInstanceState);
    102.     setContentView(R.layout.activity_ucuncu_ekran);
    103.     if(Build.VERSION.SDK_INT >=23 && (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) {
    104.         ActivityCompat.requestPermissions(Ucuncu_ekran.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 1);
    105.     }
    106.  
    107.     webView = (WebView) findViewById(R.id.webView2);
    108.     assert webView != null;
    109.     WebSettings webSettings = webView.getSettings();
    110.     webSettings.setJavaScriptEnabled(true);
    111.     webSettings.setAllowFileAccess(true);
    112.  
    113.     if(Build.VERSION.SDK_INT >= 21){
    114.         webSettings.setMixedContentMode(0);
    115.         webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
    116.     }else if(Build.VERSION.SDK_INT >= 19){
    117.         webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
    118.     }else if(Build.VERSION.SDK_INT < 19){
    119.         webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    120.     }
    121.     webView.setWebViewClient(new Callback());
    122.     webView.loadUrl("https://mywebsite.com/");
    123.     webView.setWebChromeClient(new WebChromeClient(){
    124.         //For Android 3.0+
    125.         public void openFileChooser(ValueCallback<Uri> uploadMsg){
    126.             mUM = uploadMsg;
    127.             Intent i = new Intent(Intent.ACTION_GET_CONTENT);
    128.             i.addCategory(Intent.CATEGORY_OPENABLE);
    129.             i.setType("*/*");
    130.             Ucuncu_ekran.this.startActivityForResult(Intent.createChooser(i,"File Chooser"), FCR);
    131.         }
    132.         // For Android 3.0+, above method not supported in some android 3+ versions, in such case we use this
    133.         public void openFileChooser(ValueCallback uploadMsg, String acceptType){
    134.             mUM = uploadMsg;
    135.             Intent i = new Intent(Intent.ACTION_GET_CONTENT);
    136.             i.addCategory(Intent.CATEGORY_OPENABLE);
    137.             i.setType("*/*");
    138.             Ucuncu_ekran.this.startActivityForResult(
    139.                     Intent.createChooser(i, "File Browser"),
    140.                     FCR);
    141.         }
    142.         //For Android 4.1+
    143.         public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture){
    144.             mUM = uploadMsg;
    145.             Intent i = new Intent(Intent.ACTION_GET_CONTENT);
    146.             i.addCategory(Intent.CATEGORY_OPENABLE);
    147.             i.setType("*/*");
    148.             Ucuncu_ekran.this.startActivityForResult(Intent.createChooser(i, "File Chooser"), Ucuncu_ekran.FCR);
    149.         }
    150.         //For Android 5.0+
    151.         @SuppressLint("QueryPermissionsNeeded")
    152.         public boolean onShowFileChooser(
    153.                 WebView webView, ValueCallback<Uri[]> filePathCallback,
    154.                 FileChooserParams fileChooserParams){
    155.             if(mUMA != null){
    156.                 mUMA.onReceiveValue(null);
    157.             }
    158.             mUMA = filePathCallback;
    159.             Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    160.             if(takePictureIntent.resolveActivity(Ucuncu_ekran.this.getPackageManager()) != null){
    161.                 File photoFile = null;
    162.                 try{
    163.                     photoFile = createImageFile();
    164.  
    165.                     takePictureIntent.putExtra("PhotoPath", mCM);
    166.                 }catch(IOException ex){
    167.                     Log.e(TAG, "Failed create image", ex);
    168.                 }
    169.                 if(photoFile != null){
    170.                     mCM = "file:" + photoFile.getAbsolutePath();
    171.                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
    172.                 }else{
    173.                     takePictureIntent = null;
    174.                 }
    175.             }
    176.             Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
    177.             contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
    178.             contentSelectionIntent.setType("*/*");
    179.             Intent[] intentArray;
    180.             if(takePictureIntent != null){
    181.                 intentArray = new Intent[]{takePictureIntent};
    182.             }else{
    183.                 intentArray = new Intent[0];
    184.             }
    185.  
    186.             Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
    187.             chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
    188.             chooserIntent.putExtra(Intent.EXTRA_TITLE, "Select an action");
    189.             chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
    190.             startActivityForResult(chooserIntent, FCR);
    191.             return true;
    192.         }
    193.  
    194.     });
    195. }
    196. public class Callback extends WebViewClient{
    197.     public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
    198.         Toast.makeText(getApplicationContext(), "Failed loading app!", Toast.LENGTH_SHORT).show();
    199.     }
    200. }
    201.  
    202. // Create an image file
    203. private File createImageFile() throws IOException{
    204.     @SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    205.     String imageFileName = "img_"+timeStamp+"_";
    206.     File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    207.     return File.createTempFile(imageFileName,".jpg",storageDir);
    208. }
    209.  
    210. @Override
    211. public boolean onKeyDown(int keyCode, @NonNull KeyEvent event){
    212.     if(event.getAction() == KeyEvent.ACTION_DOWN){
    213.         switch(keyCode){
    214.             case KeyEvent.KEYCODE_BACK:
    215.                 if(webView.canGoBack()){
    216.                     webView.goBack();
    217.                 }else{
    218.                     finish();
    219.                 }
    220.                 return true;
    221.         }
    222.     }
    223.     return super.onKeyDown(keyCode, event);
    224. }
    225.  
    226. @Override
    227. public void onConfigurationChanged(Configuration newConfig){
    228.     super.onConfigurationChanged(newConfig);
    229. }
    230.  
    231. @Override
    232. public void onBackPressed() {
    233.     if (webView.canGoBack()) {
    234.         webView.goBack();
    235.     }
    236.     else {
    237.         AlertDialog.Builder builder = new AlertDialog.Builder(this);
    238.         builder.setTitle("Exit app");
    239.         builder.setMessage("Are you sure?");
    240.         builder.setPositiveButton("No", new DialogInterface.OnClickListener() {
    241.             public void onClick(DialogInterface dialog, int id) {
    242.             }
    243.         });
    244.         builder.setNegativeButton("Yes", new DialogInterface.OnClickListener() {
    245.             public void onClick(DialogInterface dialog, int id) {
    246.                 Ucuncu_ekran.super.onBackPressed();
    247.             }
    248.         });
    249.         builder.show();
    250.  
    251.         //super.onBackPressed();
    252.     }
    253. }
    254. public boolean InternetKontrol() {
    255.     ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    256.     if (manager.getActiveNetworkInfo() != null && manager.getActiveNetworkInfo().isAvailable() && manager.getActiveNetworkInfo().isConnected()) {
    257.         return true;
    258.     }
    259.     else {
    260.         return false;
    261.     }
    262. }
    263. }
     


    #1 hk1337, Nov 25, 2020
    Last edited: Nov 25, 2020

    1. Download the Forums for Android™ app!


      Download

       
Loading...

Share This Page

Loading...