• 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

Contact Tracing apps are acceptable from Google

Oh!, is there any article that I can refer about this?

Some information here, for Google, Amazon, and Apple.
https://www.cnet.com/news/apple-google-amazon-block-nonofficial-coronavirus-apps-from-app-stores/
Apple and Amazon are only accepting COVID-19 and coronavirus-related apps from "recognized entities,"

Are you a "recognized entity", i.e. like a government health organisation, health NGO, etc.?

Robot Pepper programming

What is the salary of a fresher with ccna?
It's about 18 to 25K USD and
If you’re working toward your CCNA certification, you’ll probably want to review some CCNA books that can help you learn the material before your exam. We’ve put together a list of the five best CCNA exam preparation books to help you become increasingly proficient in the knowledge areas that will appear on the CCNA exam. 1. CCNA Preparation Library (640-801) 2. Cisco Certified Network Associate Study Guide (640-802) 3. Cisco CCNA Exam Flash Card Practice Library (640-607) 4. CCNA Exam Certification Guide (640-607) 5. CCNA Practical Studies (640-607). Because the Cisco CCNA exam is relatively difficult, most candidates find the best value in combining the information from the references listed above with online training courses. To know more about CCNA certification training or register with the training program, explore SPOTO's CCNA certification training course. SPOTO training course is a blend of all these book developing important notes and test papers via the E-learning platform.

Accessories HELP

If you bought it new, as the first user, then the IMEI should not be blacklisted. Blacklisting is normally done to render a stolen phone inoperative (note that "stolen" includes "someone bought the phone at a subsidised price as part of a contract then decided to stop paying the contract payments and sold the phone" - the service provider considers that to be theft, since they broke the contract before paying off the phone, and blacklists the handset).

A much rarer reason is if someone "clones" your IMEI. If two phones with the same IMEI are detected on the network this will be seen as a sign of wrongdoing, and most likely blacklist that IMEI (blocking both phones). This is why you never post your IMEI in public.

Unfortunately if it is blacklisted it can be very hard to do anything about it. Providers are usually unwilling or even unable to remove a blacklisting if the reason is that the phone is listed as stolen (for obvious reasons: there's no disincentive to theft if someone can just call up and get the blacklisting removed). Ironically the main reason for "cloning" (reprogramming the IMEI) is because the original IMEI has been blacklisted - I should add tha the practice is also illegal in many countries, and I do not recommend that as a solution! Hopefully your problem will not be due to blacklisting.

I suggest speaking to your service provider to check whether they have any idea what the problem is. You can also tell them your IMEI and ask them to check it isn't blacklisted.

Filter

Back
Top Bottom