• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

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

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:

Java:
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class Ucuncu_ekran extends AppCompatActivity{
WebView webView;
private static final String TAG = Ucuncu_ekran.class.getSimpleName();
private String mCM;
private ValueCallback mUM;
private ValueCallback<Uri[]> mUMA;
private final static int FCR=1;


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


    super.onActivityResult(requestCode, resultCode, intent);
    if(Build.VERSION.SDK_INT >= 21){
        Uri[] results = null;
        //Check if response is positive
        if(resultCode== Activity.RESULT_OK){
            if(requestCode == FCR){
                if(null == mUMA){
                    return;
                }
                if(intent == null){
                    //camera selected
                    //Capture Photo if no image available
                    if(mCM != null){
                        results = new Uri[]{Uri.parse(mCM)};
                    }
                }else{
                    //gallery selected
                    String dataString = intent.getDataString();
                    if(dataString != null){
                        results = new Uri[]{Uri.parse(dataString)};
                    }
                }
            }
        }
        mUMA.onReceiveValue(results);
        mUMA = null;
    }else{
        if(requestCode == FCR){
            if(null == mUM) return;
            Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
            mUM.onReceiveValue(result);
            mUM = null;
        }
    }
}

AlertDialog.Builder builder;
String test = "";
Button closeButton;

@SuppressLint({"SetJavaScriptEnabled", "WrongViewCast"})
@Override
protected void onCreate(Bundle savedInstanceState){/*
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
    getSupportActionBar().hide();*/


    boolean b = uygulamaYukluMu("com.android.camera");
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_ucuncu_ekran);
    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)) {
        ActivityCompat.requestPermissions(Ucuncu_ekran.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 1);
    }

    webView = (WebView) findViewById(R.id.webView2);
    assert webView != null;
    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setAllowFileAccess(true);

    if(Build.VERSION.SDK_INT >= 21){
        webSettings.setMixedContentMode(0);
        webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
    }else if(Build.VERSION.SDK_INT >= 19){
        webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
    }else if(Build.VERSION.SDK_INT < 19){
        webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }
    webView.setWebViewClient(new Callback());
    webView.loadUrl("https://mywebsite.com/");
    webView.setWebChromeClient(new WebChromeClient(){
        //For Android 3.0+
        public void openFileChooser(ValueCallback<Uri> uploadMsg){
            mUM = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");
            Ucuncu_ekran.this.startActivityForResult(Intent.createChooser(i,"File Chooser"), FCR);
        }
        // For Android 3.0+, above method not supported in some android 3+ versions, in such case we use this
        public void openFileChooser(ValueCallback uploadMsg, String acceptType){
            mUM = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");
            Ucuncu_ekran.this.startActivityForResult(
                    Intent.createChooser(i, "File Browser"),
                    FCR);
        }
        //For Android 4.1+
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture){
            mUM = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");
            Ucuncu_ekran.this.startActivityForResult(Intent.createChooser(i, "File Chooser"), Ucuncu_ekran.FCR);
        }
        //For Android 5.0+
        @SuppressLint("QueryPermissionsNeeded")
        public boolean onShowFileChooser(
                WebView webView, ValueCallback<Uri[]> filePathCallback,
                FileChooserParams fileChooserParams){
            if(mUMA != null){
                mUMA.onReceiveValue(null);
            }
            mUMA = filePathCallback;
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if(takePictureIntent.resolveActivity(Ucuncu_ekran.this.getPackageManager()) != null){
                File photoFile = null;
                try{
                    photoFile = createImageFile();

                    takePictureIntent.putExtra("PhotoPath", mCM);
                }catch(IOException ex){
                    Log.e(TAG, "Failed create image", ex);
                }
                if(photoFile != null){
                    mCM = "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("*/*");
            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, "Select an action");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
            startActivityForResult(chooserIntent, FCR);
            return true;
        }

    });
}
public class Callback extends WebViewClient{
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
        Toast.makeText(getApplicationContext(), "Failed loading app!", Toast.LENGTH_SHORT).show();
    }
}

// Create an image file
private File createImageFile() throws IOException{
    @SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "img_"+timeStamp+"_";
    File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    return File.createTempFile(imageFileName,".jpg",storageDir);
}

@Override
public boolean onKeyDown(int keyCode, @NonNull KeyEvent event){
    if(event.getAction() == KeyEvent.ACTION_DOWN){
        switch(keyCode){
            case KeyEvent.KEYCODE_BACK:
                if(webView.canGoBack()){
                    webView.goBack();
                }else{
                    finish();
                }
                return true;
        }
    }
    return super.onKeyDown(keyCode, event);
}

@Override
public void onConfigurationChanged(Configuration newConfig){
    super.onConfigurationChanged(newConfig);
}

@Override
public void onBackPressed() {
    if (webView.canGoBack()) {
        webView.goBack();
    }
    else {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Exit app");
        builder.setMessage("Are you sure?");
        builder.setPositiveButton("No", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
            }
        });
        builder.setNegativeButton("Yes", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                Ucuncu_ekran.super.onBackPressed();
            }
        });
        builder.show();

        //super.onBackPressed();
    }
}
public boolean InternetKontrol() {
    ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    if (manager.getActiveNetworkInfo() != null && manager.getActiveNetworkInfo().isAvailable() && manager.getActiveNetworkInfo().isConnected()) {
        return true;
    }
    else {
        return false;
    }
}
}

Android Studio - requires manual Sync every startup

Hi - I have Android Studio 4.1.1
Every time I start the IDE, I need to click the Sync project with Gradle files otherwise I get the dreaded red errors everywhere. This seems to be a recent problem (since upgrading maybe?)

I also have to keep specifying the SDK each time (Module JDK is not defined)

(Alternatively I have to do an invalidate caches and restart each time after startup).
Any suggestions anyone?
Thanks and regards
Thanks
Russell

Netbook running Android 6

Hi.

I have just acquired a chinese non descript brand of netbook running Android 6 ( BDF HL-1088A3 that is all the info i have ).
Enclosed with it was a very scanty instructions leaflet.

I have tried unsuccessfully on the net to find a User manual for this netbook.

Has any one got any ideas please?

Thank you

Alistair Clarke
Usk
Wales
United Kingdom

Apps Academic Survey on App Development

Hello everyone - thank you for responding to our survey. As of last night, we had more responses than we have funding for gift cards so I've taken down the survey.

I'm a researcher at the University of Oklahoma. I'm working with graduate students on a research project about innovation and app development to be completed by US citizens who develop apps for android, but are not employed full time as app developers. We do not collect IP addresses. We can offer a $10 gift card (amazon) to US citizens that complete the survey – we collect name and email address to provide the gift card but that data is separated from the responses and only used to provide the gift card. Feel free to contact me if you have any issues. Thanks in advance to anyone that completes our survey!

End of the Note line?

There are a lot of posts in the blogs about rumours that Samsung will abandon the Galaxy Note line next year, instead adding the S-Pen to the Fold line (and, perhaps, to the Galaxy S Ultra - not clear whether that would mean S-Pen included or just compatible with the phone).

Now the Note has never been something I was going to buy, as big phones aren't my thing. But that range has probably been the most innovative thing Samsung have done, with the original Note starting the "phablet" concept itself and the S-Pen bringing a stylus to the smartphone. I'd argue that the Fold is less innovative, since foldables were something that was obvious long before the technology to make them was available, and hence several manufacturers developed these at the same time, whereas the Notes led the way in those two respects. So if the rumours are true I'll acknowledge its passing as significant, and miss it a bit even if I'd never own one.

But what I'm curious about is how Note fans here would feel? Would these rumoured replacements take its place for you, or will you feel that something has been lost (if it happens - we do seems to be talking about a single rumour, widely repeated)?

USB comms between Tablet and Ubuntu PC Exception

Hi

I have an Ubuntu laptop and a Android 9 Tablet (Samsung Active 2). The tablet is connected to the laptop with FTDI connectors and a NULL cable. The code to connect to the laptop through the FTDI connectors and NULL cable is below:
Java:
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialPort;
import com.hoho.android.usbserial.driver.UsbSerialProber;
.
.
.
try
{
   UsbManager usbManager = (UsbManager) view.getContext().getSystemService(Context.USB_SERVICE);
   if( usbManager != null )
   {
      Log.i("USB COMMS USBMANAGER", usbManager.toString());
      Map<String, UsbDevice> deviceList = usbManager.getDeviceList();
      Log.i("USB COMMS DeviceList Size: ", String.valueOf(deviceList.size()));
      UsbSerialDriver usbDriver = null;
      UsbSerialPort usbPort = null;
      UsbDeviceConnection usbConnection = null;
      for( UsbDevice usbDevice : deviceList.values() )
      {
          Log.i("USB COMMS UsbDevice: ", usbDevice.toString());
          String deviceName = usbDevice.getManufacturerName();
          Log.i("USB COMMS deviceName: ", deviceName);
          if( deviceName.toLowerCase().contains("ftdi") )
          {
              usbDriver = UsbSerialProber.getDefaultProber().probeDevice(usbDevice);
              Log.i("USB COMMS driver: ", usbDriver.toString());
              usbConnection = usbManager.openDevice(usbDriver.getDevice());
              if( usbConnection != null ) {
                  Log.i("USB COMMS connection: ", usbConnection.toString());
                  usbPort = usbDriver.getPorts().get(0);
                  Log.i("USB COMMS port: ", usbPort.toString());
                  usbPort.open(usbConnection);
                  Log.i("USB COMMS port is open ", "");
                  usbPort.setParameters(115200, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
              }
              else
              {
                  Log.i("USB COMMS connection is null", "");
              }
              break;
          }
      }
      if( usbPort != null )
      {
          Log.i("USB COMMS calling SerialMsgThread with port: ", usbPort.toString());
          SerialMsgThread st = new SerialMsgThread(usbPort, mapView);
          st.start();
      }
      else
      {
          Log.i("SerialMsgThread ", "USBSerialDriver is Null");
      }
   }
   else
   {
      Log.i("USB COMMS USBMANAGER", "IS NULL");
   }
}
catch(Exception e)
{
  Log.i("USB COMMS EXCEPTION: ", e.toString());
}

I have the following in my manifest.xml
HTML:
        <service
            android:name="com.android.notification.NotificationService"
            android:label="Plugin Notification Service">
            <intent-filter>
                <action android:name="com.android.notification.NotificationService"/>
            </intent-filter>
            <intent-filter>
                <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
            </intent-filter>
            <meta-data
                android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
                android:resource="@xml/accessory_filter" />
        </service>

I have the following device filter under res/
HTML:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- The following is the FTDI parameters -->
    <usb-device vendor-id="1027" product-id="24577" model="FT232" manufacturer="FTDI" version="6.0"/>
</resources>

This is the logcat output, including the exception:
Java:
2020-11-24 08:22:28.599 1578-1578/Â USBÂ COMMSÂ USBMANAGER: android.hardware.usb.UsbManager@7de64a6
2020-11-24 08:22:28.601 1578-1578/ USB COMMS DeviceList Size:: 1
2020-11-24 08:22:28.606 1578-1578/Â USBÂ COMMSÂ UsbDevice:: UsbDevice[mName=/dev/bus/usb/001/002,mVendorId=1027,mProductId=24577,mClass=0,mSubclass=0,mProtocol=0,mManufacturerName=FTDI,mProductName=USB Serial Converter,mVersion=6.00,mSerialNumber=FTBVMD1M,mConfigurations=[
    '-->UsbConfiguration[mId=1,mName=null,mAttributes=160,mMaxPower=22,mInterfaces=[
    '-->UsbInterface[mId=0,mAlternateSetting=0,mName=USB Serial Converter,mClass=255,mSubclass=255,mProtocol=255,mEndpoints=[
    '-->UsbEndpoint[mAddress=129,mAttributes=2,mMaxPacketSize=64,mInterval=0]
    '-->UsbEndpoint[mAddress=2,mAttributes=2,mMaxPacketSize=64,mInterval=0]]]]
2020-11-24 08:22:28.606 1578-1578/Â USBÂ COMMSÂ deviceName:: FTDI
2020-11-24 08:22:28.612 1578-1578/Â USBÂ COMMSÂ driver:: com.hoho.android.usbserial.driver.FtdiSerialDriver@abf9ee7
2020-11-24 08:22:28.617 1578-1578/ E/UsbManager: exception in UsbManager.openDevice
    java.lang.SecurityException: User has not given permission to device UsbDevice[mName=/dev/bus/usb/001/002,mVendorId=1027,mProductId=24577,mClass=0,mSubclass=0,mProtocol=0,mManufacturerName=FTDI,mProductName=USB Serial Converter,mVersion=6.00,mSerialNumber=FTBVMD1M,mConfigurations=[
    UsbConfiguration[mId=1,mName=null,mAttributes=160,mMaxPower=22,mInterfaces=[
    UsbInterface[mId=0,mAlternateSetting=0,mName=USB Serial Converter,mClass=255,mSubclass=255,mProtocol=255,mEndpoints=[
    UsbEndpoint[mAddress=129,mAttributes=2,mMaxPacketSize=64,mInterval=0]
    UsbEndpoint[mAddress=2,mAttributes=2,mMaxPacketSize=64,mInterval=0]]]]
        at android.os.Parcel.createException(Parcel.java:1966)
        at android.os.Parcel.readException(Parcel.java:1934)
        at android.os.Parcel.readException(Parcel.java:1884)
        at android.hardware.usb.IUsbManager$Stub$Proxy.openDevice(IUsbManager.java:614)
        at android.hardware.usb.UsbManager.openDevice(UsbManager.java:791)
        at android.view.View.performClick(View.java:7348)
        at android.widget.TextView.performClick(TextView.java:14215)
        at android.view.View.performClickInternal(View.java:7314)
        at android.view.View.access$3200(View.java:846)
        at android.view.View$PerformClick.run(View.java:27803)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7179)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)
     Caused by: android.os.RemoteException: Remote stack trace:
        at com.android.server.usb.UsbUserSettingsManager.checkPermission(UsbUserSettingsManager.java:243)
        at com.android.server.usb.UsbHostManager.openDevice(UsbHostManager.java:560)
        at com.android.server.usb.UsbService.openDevice(UsbService.java:368)
        at android.hardware.usb.IUsbManager$Stub.onTransact(IUsbManager.java:70)
        at android.os.Binder.execTransact(Binder.java:739)


Edit:
This is my rules files for USB devices (/etc/udev/rules.d/my-newrule.rules):
Code:
KERNEL=="ttyACM0", MODE="0777"
KERNEL=="ttyUSB0", MODE="0777"


Any suggestions as to how to fix this would be appreciated.

Thanks...

Is it possible to communicate among devices using bluetooth without pairing from same Xamarin app

I am new to Xamarin development. I wanted to know is it possible to read data using bluetooth among devices without pairing?
I will install Xamarin app on multiple devices. This app will store some data like, user name, email, phone number etc. I want to read this information from another device through bluetooth from same Xamarin app. During this process I don't want to ask user to pair with another device. Because, in a company if there are 100 employees, to communicate between devices among 100, every user need to pair for 99 times. So is there anyway to bypass this option?

Word Search

Classic word search game with thousands of levels to play

Features:

-Search words in different languages;
-Swipe words in any direction, horizontally, vertically, diagonally;
-Possible to change the background image;
-Possible to see hints;


screena10.jpg


This game can be specially useful between study sessions or work to distract the mind.
A good game for kids, girls, boys, adults everyone who loves word games, visual tests, brain puzzles, or basically want to test themselves.

Link: https://play.google.com/store/apps/details?id=com.neptunemobilegames.wordsearch

Micro SD card repeatedly corrupt

Hi,
My Micro SD card was getting corrupt files errors, so I took it out and scanned it on my PC, found nothing wrong, copied the files to the PC then reformatted the card and put it back in the phone.
Three days later the same thing happened, with the same results.
So, I bought a new card, put it in the phone on Saturday, then woke up this morning to see the corrupted files error yet again.
Can anyone offer any advice, please?
Many thanks.

Black Friday phone deals2020: the best early sales so far and what to expect?

The two biggest shopping days of the year are finally on the perspective, and anyone looking to save some serious cash is planning right now — or should be. If you've been eager to pick up a new phone, rest easy: Black Friday deals have come for phones, too. This year's Black Friday phone deals will get you a serious discount on new devices, from affordable phones to top flagships, including the much-awaited iPhone 12, Note 20 deals. With price cuts on Apple and Samsung models old and new, we're on track for some fantastic Black Friday phone deals this year. Here are some great examples of discounts on handsets that make our best phones list. visit our Official websites and get huge discounts on Black Friday and Cyber Monday deals.

Filter

Back
Top Bottom