Upload image from android application to server like a facebook application - android

I want to add facebook image browse functionality to my android application.
More precisialy,I want when user will click to browse button,he will see two options:
browse image frome phone(card) memory .
do photo shoot and upload image.
I want to add,that i don't use webview.
Thanks.

The official Facebook for Android SDK is open source, have a look
http://github.com/facebook/facebook-android-sdk

I was having the same case and solved the problem by implementing a webview client and webchrome client as shown below. I have done a sample demonstrating the same how to upload photos on your android application. Try these code and it will definitely work for you. You can download a working demo from here
package com.whatsonline.androidphotouploadonfacebook;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.ViewGroup;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
/**
* Created by sada on 6/17/2016.
*/
public class upload extends Activity {
WebView web;
private ValueCallback<Uri> mUploadMessage;
private final static int FILECHOOSER_RESULTCODE=1;
LinearLayout ln1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.upload);
web = new WebView(this);
web.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
ln1=(LinearLayout) findViewById(R.id.ln1);
WebSettings settings=web.getSettings();
settings.setJavaScriptEnabled(true);
web.loadUrl("http://www.facebook.com");
web.setWebViewClient(new myWebClient());
web.setWebChromeClient(new WebChromeClient() {
//The undocumented magic method override
//Eclipse will swear at you if you try to put #Override here
// For Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
upload.this.startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
}
// For Android 3.0+
public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
upload.this.startActivityForResult(
Intent.createChooser(i, "File Browser"),
FILECHOOSER_RESULTCODE);
}
//For Android 4.1
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
upload.this.startActivityForResult(Intent.createChooser(i, "File Chooser"), upload.FILECHOOSER_RESULTCODE);
}
});
ln1.addView(web);
}
public class myWebClient extends WebViewClient
{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
}
//flipscreen not loading again
#Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if(requestCode==FILECHOOSER_RESULTCODE){
if (null == mUploadMessage) return;
Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
}
Besides, add the permissions for internet access, read from external storage and camera capture.

Related

choose files dont work on the phone using webview

I have a button choose files in website, when you press the button on your computer it works and when you press the button on the phone does not work what solution, the site shows using WebView
mywebsite = (WebView)findViewById(R.id.mywebsite);
pd_loading = (ProgressBar)findViewById(R.id.pd_loading);
mywebsite.getSettings().setLoadsImagesAutomatically(true);
mywebsite.getSettings().setJavaScriptEnabled(true);
mywebsite.setWebViewClient(new WebViewClient());
mywebsite.loadUrl(Information.URL_Home);
mywebsite.setWebViewClient(new WebViewClient(){
public void onPageFinished(WebView view ,String url)
{
pd_loading.setVisibility(View.GONE);
mywebsite.setVisibility(View.VISIBLE);
}
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
Toasty.error(Home.this,"",Toast.LENGTH_SHORT,true).show();
}
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i, "File Chooser"), 101);
mUploadMessage = uploadMsg;
}
// For Android > 4.1 - undocumented method
#SuppressWarnings("unused")
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
openFileChooser(uploadMsg, "");
}
// For Android > 5.0
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
startActivityForResult(fileChooserParams.createIntent(), 101);
return true;
}
});
onActivittyResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
switch (requestCode) {
case 101:
if (resultCode == RESULT_OK) {
Uri result = intent == null || resultCode != RESULT_OK ? null
: intent.getData();
if (mUploadMessage != null) {
mUploadMessage.onReceiveValue(result);
} else if (afterLolipop != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
afterLolipop.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, intent));
afterLolipop = null;
}
}
mUploadMessage = null;
}
}
}
these codes don't work I just want to choose a picture of a computer I hope help me thanks
When I faced a similar kind of issue, I have made use of setWebChromeClient() method found from this souce.
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;
import org.apache.http.util.EncodingUtils;
public class BrowserScreen extends Activity {
private WebView webView;
private String url = "url";
private ValueCallback<Uri> mUploadMessage;
private final static int FILECHOOSER_RESULTCODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.browser_activity);
initFields();
setListeners();
}
public void initFields() {
// TODO Auto-generated method stub
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setAllowFileAccess(true);
}
public void setListeners() {
// TODO Auto-generated method stub
webView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
webView.loadUrl("about:blank");
view.clearHistory();
}
});
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
}
//The undocumented magic method override
//Eclipse will swear at you if you try to put #Override here
// For Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
}
// For Android 3.0+
public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
startActivityForResult(
Intent.createChooser(i, "File Browser"),
FILECHOOSER_RESULTCODE);
}
//For Android 4.1
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
}
});
webView.loadUrl(url);
final MyJavaScriptInterface myJavaScriptInterface
= new MyJavaScriptInterface(this);
webView.addJavascriptInterface(myJavaScriptInterface, "AndroidFunction");
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
if (webView.canGoBack() == true) {
webView.goBack();
} else {
super.onBackPressed();
}
}
public class MyJavaScriptInterface {
Context mContext;
MyJavaScriptInterface(Context c) {
mContext = c;
}
#JavascriptInterface
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
// webView.loadUrl("javascript:document.getElementById(\"Button3\").innerHTML = \"bye\";");
}
#JavascriptInterface
public void openAndroidDialog() {
AlertDialog.Builder myDialog
= new AlertDialog.Builder(BrowserScreen.this);
myDialog.setTitle("DANGER!");
myDialog.setMessage("You can do what you want!");
myDialog.setPositiveButton("ON", null);
myDialog.show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == mUploadMessage) return;
Uri result = intent == null || resultCode != RESULT_OK ? null
: intent.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
}

HTML input type 'file' is not working on webview in android. Is there any way to upload file using webview android?

this is my browsing code of html.
This is my android code which load html file for browse file and upload on server.
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
System.out.println(AndroidConstants.MAIN_URL());
toast(AndroidConstants.MAIN_URL());
webView.loadUrl(AndroidConstants.MAIN_URL());
webView.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
// TODO Auto-generated method stub
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
WebViewActivity.this.startActivityForResult(Intent.createChooser(i,"Image Chooser"), 2533);
}
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
openFileChooser(uploadMsg);
}
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
openFileChooser(uploadMsg);
}
});
}
});
JavaScriptInterface jsInterface = new JavaScriptInterface(this);
webView.getSettings().setJavaScriptEnabled(true);
i want upload video file using html5 on android application.
This is work for me. Also work for Nugget and Marshmallow
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
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.Toast;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity{
WebView webView;
private static final String TAG = MainActivity.class.getSimpleName();
private String mCM;
private ValueCallback<Uri> 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){
//Capture Photo if no image available
if(mCM != null){
results = new Uri[]{Uri.parse(mCM)};
}
}else{
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;
}
}
}
#SuppressLint({"SetJavaScriptEnabled", "WrongViewCast"})
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 1);
}
webView = (WebView) findViewById(R.id.ifView);
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://infeeds.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("*/*");
MainActivity.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("*/*");
MainActivity.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("*/*");
MainActivity.this.startActivityForResult(Intent.createChooser(i, "File Chooser"), MainActivity.FCR);
}
//For Android 5.0+
public boolean onShowFileChooser(
WebView webView, ValueCallback<Uri[]> filePathCallback,
WebChromeClient.FileChooserParams fileChooserParams){
if(mUMA != null){
mUMA.onReceiveValue(null);
}
mUMA = filePathCallback;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(takePictureIntent.resolveActivity(MainActivity.this.getPackageManager()) != null){
File photoFile = null;
try{
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCM);
}catch(IOException ex){
Log.e(TAG, "Image file creation failed", 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, "Image Chooser");
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);
}
}
This issue has already been asked and answered here: File Upload in WebView
Also check this:
https://code.google.com/p/android/issues/detail?id=62220
You can use this class: https://github.com/delight-im/Android-AdvancedWebView
This code is working for me.....
Here, no need to ask storage permissions to the user....
package app.qarya.in.upsc4u.questions.answers;
import android.annotation.SuppressLint;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
public class WebPageMain extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
String webAddress = "https://qarya.in/";
public static final int REQUEST_SELECT_FILE = 100;
WebView webView;
ProgressBar progressBar;
FrameLayout frameLayout;
SwipeRefreshLayout swipeRefreshLayout;
ProgressDialog pd;
static int count=0;
AdView adView;
AdRequest adRequest;
InterstitialAd interstitialAd;
private ValueCallback<Uri[]> uploadMessage;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.web_page);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
MobileAds.initialize(this, "ca-app-pub-3940256099942544~3347511713");
pd = new ProgressDialog(this);
pd.setMessage("Loading please wait...");
pd.show();
swipeRefreshLayout = findViewById(R.id.srl);
swipeRefreshLayout.setOnRefreshListener(this);
frameLayout = findViewById(R.id.framLayout);
progressBar = findViewById(R.id.progressBar);
assert webView != null;
progressBar.setMax(100);
webView = findViewById(R.id.webView);
webView.setWebViewClient(new Callback());
webView.getSettings().setJavaScriptEnabled(true);
webView.setVerticalFadingEdgeEnabled(false);
webView.loadUrl(webAddress);
progressBar.setProgress(0);
adView = findViewById(R.id.adView);
adRequest = new AdRequest.Builder().build();
//adView.loadAd(adRequest);
interstitialAd = new InterstitialAd(this);
interstitialAd.setAdUnitId(getResources().getString(R.string.inter));
//interstitialAd.loadAd(adRequest);
//showInterAd();
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView webView,int progress)
{
frameLayout.setVisibility(View.VISIBLE);
progressBar.setProgress(progress);
//setTitle("Loading...");
if(progress==100)
{
frameLayout.setVisibility(View.GONE);
pd.dismiss();
//setTitle(webView.getTitle());
}
else if(progress==70)
{
pd.dismiss();
count+=1;
if(count%5==0) {
interstitialAd.loadAd(adRequest);
showInterAd();
}
adView.loadAd(adRequest);
}
//Log.d("progress",progress+"");
super.onProgressChanged(webView,progress);
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
// make sure there is no existing message
if (uploadMessage != null) {
uploadMessage.onReceiveValue(null);
uploadMessage = null;
}
uploadMessage = filePathCallback;
Intent intent = fileChooserParams.createIntent();
try {
startActivityForResult(intent, REQUEST_SELECT_FILE);
} catch (ActivityNotFoundException e) {
uploadMessage = null;
Toast.makeText(getApplicationContext(), "Cannot open file chooser", Toast.LENGTH_LONG).show();
return false;
}
return true;
}
});
}
#SuppressLint("NewApi")
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if (requestCode == REQUEST_SELECT_FILE) {
if (uploadMessage == null) return;
uploadMessage.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
uploadMessage = null;
}
}
#Override
public void onRefresh() {
webView.reload();
swipeRefreshLayout.setRefreshing(false);
//adView.loadAd(adRequest);
}
void showInterAd()
{
interstitialAd.setAdListener(new AdListener(){
#Override
public void onAdLoaded() {
if(interstitialAd.isLoaded())
interstitialAd.show();
}
});
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode== KeyEvent.KEYCODE_BACK)
{
if(webView.canGoBack()) {
webView.goBack();
adView.loadAd(adRequest);
}else
{
final AlertDialog alert = new AlertDialog.Builder(this).create();
alert.setTitle("Exit");
alert.setMessage("Are You Sure you want to Exit.");
alert.setButton(AlertDialog.BUTTON_POSITIVE,"Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alert.setButton(AlertDialog.BUTTON_NEGATIVE,"Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
alert.dismiss();
}
});
alert.setButton(AlertDialog.BUTTON_NEUTRAL, "Home", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
webView.loadUrl("https://qarya.in/");
alert.dismiss();
}
});
alert.show();
}
return true;
}
return super.onKeyDown(keyCode, event);
}
// Open previous opened link from history on webview when back button pressed
#Override
// Detect when the back button is pressed
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
} else {
// Let the system handle the back button
super.onBackPressed();
}
}
public class Callback extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
pd.dismiss();
if(!url.contains("qarya") || url.contains("facebook.com") || url.contains("twitter.com") || url.contains("linkedin.com") ||url.contains("whatsapp.com"))
{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
}
else
{
view.loadUrl(url);
}
return true;
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(getApplicationContext(), "Failed loading app!", Toast.LENGTH_SHORT).show();
pd.dismiss();
}
}
}
I'm new to Andriod and struggled with this also. According to Google Reference Guide WebView.
By default, a WebView provides no browser-like widgets, does not enable JavaScript and web page errors are ignored. If your goal is only to display some HTML as a part of your UI, this is probably fine; the user won't need to interact with the web page beyond reading it, and the web page won't need to interact with the user. If you actually want a full-blown web browser, then you probably want to invoke the Browser application with a URL Intent rather than show it with a WebView.
Example code I executed in MainActvity.java.
Uri uri = Uri.parse("https://www.example.com");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
Excuted
package example.com.myapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.content.Intent;
import android.net.Uri;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Uri uri = Uri.parse("http://www.example.com/");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
getSupportActionBar().hide();
}}

can't open file chooser in WebView Android 4.4.2 using WebChromeClient

In my webview by clicking "Choose File" button In samsung 7 inch tablet I want to open a File Browser, but I can't open this in Android Version 4.4.2.
So can u plz help me for this?
Here is my Code.
WebViewDemo.java
package com.example.webviewdemo;
import java.io.File;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.webkit.ConsoleMessage;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings.PluginState;
import android.widget.ProgressBar;
import android.widget.Toast;
public class WebViewDemo extends Activity {
/** Called when the activity is first created. */
WebView web;
private ValueCallback<Uri> mUploadMessage;
private final static int FILECHOOSER_RESULTCODE=1;
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if(requestCode==FILECHOOSER_RESULTCODE)
{
if (null == mUploadMessage) return;
Uri result = intent == null || resultCode != RESULT_OK ? null
: intent.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_web_view);
web = (WebView) findViewById(R.id.webView1);
web = new WebView(this);
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl("file:///android_asset/select.html");
web.setWebViewClient(new myWebClient());
web.setWebChromeClient(new WebChromeClient()
{
//The undocumented magic method override
//Eclipse will swear at you if you try to put #Override here
// For Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
WebViewDemo.this.startActivityForResult(Intent.createChooser(i,"File Chooser"), FILECHOOSER_RESULTCODE);
}
// For Android 3.0+
public void openFileChooser( ValueCallback uploadMsg, String acceptType ) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
WebViewDemo.this.startActivityForResult(
Intent.createChooser(i, "File Browser"),
FILECHOOSER_RESULTCODE);
}
//For Android 4.1
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture){
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
WebViewDemo.this.startActivityForResult( Intent.createChooser( i, "File Chooser" ), WebViewDemo.FILECHOOSER_RESULTCODE );
}
});
setContentView(web);
}
public class myWebClient extends WebViewClient
{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
}
}
//flipscreen not loading again
#Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
}
// To handle "Back" key press event for WebView to go back to previous screen.
/*#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && web.canGoBack()) {
web.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}*/
}
Inside assets/select.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div data-role="page" id="pageone">
<div data-role="header">
<h1>PRODUCT DETAIL</h1>
</div>
<div data-role="content">
<form method="get" action="">
<div data-role="fieldcontain">
<label for="name">Open File Chosser And Select File From Camera :</label>
<input type="file" name="text" id="name" type="image/*" >
</div>
<div data-role="fieldcontain">
<label for="name">Email:</label>
<input type="text" name="text" id="name" value="" placeholder="What's Your Name?">
</div>
<div data-role="fieldcontain">
<label for="search">Looking for anything?</label>
<input type="search" name="search" id="search" value="" placeholder="Search for content"/>
</div>
<div data-role="fieldcontain">
<label for="colors">Open link in webview browser.</label>
<br>
<br>
<label for="colors">Open link in new browser.</label>
</div>
</div>
</form>
</div>
</div>
</body>
</html>
This will worked definitely, because i have already tried it...
public class MyWb extends Activity {
/** Called when the activity is first created. */
WebView web;
ProgressBar progressBar;
private ValueCallback<Uri> mUploadMessage;
private final static int FILECHOOSER_RESULTCODE=1;
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if(requestCode==FILECHOOSER_RESULTCODE)
{
if (null == mUploadMessage) return;
Uri result = intent == null || resultCode != RESULT_OK ? null
: intent.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
web = (WebView) findViewById(R.id.webview01);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
web = new WebView(this);
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl("http://www.script-tutorials.com/demos/199/index.html");
web.setWebViewClient(new myWebClient());
web.setWebChromeClient(new WebChromeClient()
{
//The undocumented magic method override
//Eclipse will swear at you if you try to put #Override here
// For Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
MyWb.this.startActivityForResult(Intent.createChooser(i,"File Chooser"), FILECHOOSER_RESULTCODE);
}
// For Android 3.0+
public void openFileChooser( ValueCallback uploadMsg, String acceptType ) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
MyWb.this.startActivityForResult(
Intent.createChooser(i, "File Browser"),
FILECHOOSER_RESULTCODE);
}
//For Android 4.1
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture){
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
MyWb.this.startActivityForResult( Intent.createChooser( i, "File Chooser" ), MyWb.FILECHOOSER_RESULTCODE );
}
});
setContentView(web);
}
public class myWebClient extends WebViewClient
{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
}
}
//flipscreen not loading again
#Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
}
// To handle "Back" key press event for WebView to go back to previous screen.
/*#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && web.canGoBack()) {
web.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}*/
}
Try with
// Work on Android 4.4.2 Zenfone 5
public void showFileChooser(ValueCallback<String[]> filePathCallback,
String acceptType, boolean paramBoolean){
// TODO Auto-generated method stub
}
and...
public void showFileChooser(ValueCallback<String[]> uploadFileCallback,
FileChooserParams fileChooserParams) {
// TODO Auto-generated method stub
}
link : http://src.chromium.org/svn/trunk/src/android_webview/java/src/org/chromium/android_webview/AwContentsClient.java
I hope this helpful to you!
The problem here is that in Android 4.4 the file input is not implemented and it will never work through the standard WebView interface.
What I did in my project has been to use CrossWalk project to make it work fine.
It has required quite a bit of work to change the default WebView from the standard Android one to CrossWalk, however it really served my needs quite well.
Basically you need to replace the normal Android WebView with the CrossWalk webView. This had few advantages for us, including the fact that Chrome will be updated even on Android 4.0, 4.1 etc, giving us a much better support and fewer bugs.
I documented how I implemented it here: http://blog.maurizionapoleoni.com/blog/implementing-a-file-input-with-camera-support-in-android-with-crosswalk/
This code is running fine on my side.
private class MyWebChromeClient extends WebChromeClient {
//The undocumented magic method override
//Eclipse will swear at you if you try to put #Override here
// For Android 3.0+
public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
MainActivity1.this.startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE);
}
//For Android 4.1+ only
protected void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture)
{
mUploadMessage = uploadMsg;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, "File Browser"), FILECHOOSER_RESULTCODE);
}
protected void openFileChooser(ValueCallback<Uri> uploadMsg)
{
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
}
// For Lollipop 5.0+ Devices
public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
if (uploadMessage != null) {
uploadMessage.onReceiveValue(null);
uploadMessage = null;
}
uploadMessage = filePathCallback;
Intent intent = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
intent = fileChooserParams.createIntent();
}
try {
startActivityForResult(intent, REQUEST_SELECT_FILE);
} catch (ActivityNotFoundException e) {
uploadMessage = null;
Toast.makeText(getApplicationContext(), "Cannot Open File Chooser", Toast.LENGTH_LONG).show();
return false;
}
return true;
}
Hope it will work for you...

button does not respond in Webview

Everything in the android web app is working as expected except the html file input fields coded as <input type="file" name="filn"/> in webpage.When i click on the button supposed to load the resources in which the files can be chosen from, it does not respond. Meanwhile in google browser, it works fine. My webview android code is as follows:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webview =(WebView)findViewById(R.id.webView1);
webview.setWebViewClient(new WebViewClient());
webview .getSettings().setJavaScriptEnabled(true);
webview.loadUrl("website");
}
What can i do to make it work?
present class which does not work also. I am trying to load a file from html file input in a jsp.
public class WebViewActivity extends Activity {
private String url = "website";
private ValueCallback<Uri> mUploadMessage;
private final static int FILECHOOSER_RESULTCODE=1;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if(requestCode==FILECHOOSER_RESULTCODE) {
if (null == mUploadMessage) return;
Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
WebView webView = (WebView) findViewById(R.id.webview1);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
webView.setWebChromeClient(
new WebChromeClient() {
#SuppressWarnings("unused")
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
mUploadMessage = uploadMsg;
//Log.d ("myfirstapp_tag", "1) MainActivity.java loaded openFileChooser" );
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
//Log.d ("myfirstapp_tag", "2) MainActivity.java loaded openFileChooser" );
i.addCategory(Intent.CATEGORY_OPENABLE);
//Log.d ("myfirstapp_tag", "3) MainActivity.java loaded openFileChooser" );
i.setType("image/*");
//Log.d ("myfirstapp_tag", "4) MainActivity.java loaded openFileChooser" );
WebViewActivity.this.startActivityForResult(Intent.createChooser(i,"File Chooser"), FILECHOOSER_RESULTCODE);
//Log.d ("myfirstapp_tag", "5) MainActivity.java loaded openFileChooser" );
}
}
);
webView.loadUrl(url);
setContentView(webView);
//android.util.Log.d ("myfirstapp_tag", "MainActivity.java loaded URL and set Content View." );
}
}
try this ... may this can help you
taken from http://androidexample.com/
import java.io.File;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.webkit.ConsoleMessage;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings.PluginState;
import android.widget.Toast;
public class ShowWebView extends Activity {
//private Button button;
private WebView webView;
final Activity activity = this;
public Uri imageUri;
private static final int FILECHOOSER_RESULTCODE = 2888;
private ValueCallback<Uri> mUploadMessage;
private Uri mCapturedImageURI = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_web_view);
//Get webview
webView = (WebView) findViewById(R.id.webView1);
// Define url that will open in webview
String webViewUrl = "Your Url Here";
// Javascript inabled on webview
webView.getSettings().setJavaScriptEnabled(true);
// Other webview options
webView.getSettings().setLoadWithOverviewMode(true);
//webView.getSettings().setUseWideViewPort(true);
//Other webview settings
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(false);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setPluginState(PluginState.ON);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setSupportZoom(true);
//Load url in webview
webView.loadUrl(webViewUrl);
// Define Webview manage classes
startWebView();
}
private void startWebView() {
// Create new webview Client to show progress dialog
// Called When opening a url or click on link
// You can create external class extends with WebViewClient
// Taking WebViewClient as inner class
webView.setWebViewClient(new WebViewClient() {
ProgressDialog progressDialog;
//If you will not use this method url links are open in new brower not in webview
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// Check if Url contains ExternalLinks string in url
// then open url in new browser
// else all webview links will open in webview browser
// Stay within this webview and load url
view.loadUrl(url);
return true;
}
//Show loader on url load
public void onLoadResource (WebView view, String url) {
// if url contains string androidexample
// Then show progress Dialog
if (progressDialog == null && url.contains("any Text If you want")
) {
// in standard case YourActivity.this
progressDialog = new ProgressDialog(ShowWebView.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
}
// Called when all page resources loaded
public void onPageFinished(WebView view, String url) {
try{
// Close progressDialog
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
}catch(Exception exception){
exception.printStackTrace();
}
}
});
// You can create external class extends with WebChromeClient
// Taking WebViewClient as inner class
// we will define openFileChooser for select file from camera or sdcard
webView.setWebChromeClient(new WebChromeClient() {
// openFileChooser for Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType){
// Update message
mUploadMessage = uploadMsg;
try{
// Create AndroidExampleFolder at sdcard
File imageStorageDir = new File(
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES)
, "AndroidExampleFolder");
if (!imageStorageDir.exists()) {
// Create AndroidExampleFolder at sdcard
imageStorageDir.mkdirs();
}
// Create camera captured image file path and name
File file = new File(
imageStorageDir + File.separator + "IMG_"
+ String.valueOf(System.currentTimeMillis())
+ ".jpg");
mCapturedImageURI = Uri.fromFile(file);
// Camera capture image intent
final Intent captureIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
// Create file chooser intent
Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
// Set camera intent to file chooser
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS
, new Parcelable[] { captureIntent });
// On select image call onActivityResult method of activity
startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
}
catch(Exception e){
Toast.makeText(getBaseContext(), "Exception:"+e,
Toast.LENGTH_LONG).show();
}
}
// openFileChooser for Android < 3.0
public void openFileChooser(ValueCallback<Uri> uploadMsg){
openFileChooser(uploadMsg, "");
}
//openFileChooser for other Android versions
public void openFileChooser(ValueCallback<Uri> uploadMsg,
String acceptType,
String capture) {
openFileChooser(uploadMsg, acceptType);
}
// The webPage has 2 filechoosers and will send a
// console message informing what action to perform,
// taking a photo or updating the file
public boolean onConsoleMessage(ConsoleMessage cm) {
onConsoleMessage(cm.message(), cm.lineNumber(), cm.sourceId());
return true;
}
public void onConsoleMessage(String message, int lineNumber, String sourceID) {
//Log.d("androidruntime", "Show console messages, Used for debugging: " + message);
}
}); // End setWebChromeClient
}
// Return here when file selected from camera or from SDcard
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if(requestCode==FILECHOOSER_RESULTCODE)
{
if (null == this.mUploadMessage) {
return;
}
Uri result=null;
try{
if (resultCode != RESULT_OK) {
result = null;
} else {
// retrieve from the private variable if the intent is null
result = intent == null ? mCapturedImageURI : intent.getData();
}
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), "activity :"+e,
Toast.LENGTH_LONG).show();
}
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
// Open previous opened link from history on webview when back button pressed
#Override
// Detect when the back button is pressed
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
} else {
// Let the system handle the back button
super.onBackPressed();
}
}
}

Enable attachment in WebView android

I have been trying to make my app let the user upload pictures from locel drive inside the webview from inside my app.
I used this code to do the pop up webview:
package com.webview.test;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
public class WebViewDialogActivity extends Activity
{
//Create a dialog object, that will contain the WebView
private Dialog webViewDialog;
//a WebView object to display a web page
private WebView webView;
//The button to launch the WebView dialog
private Button btLaunchWVD;
//The button that closes the dialog
private Button btClose;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.sliding_menu_categories);
//Inflate the btLaunchWVD button from the 'main.xml' layout file
btLaunchWVD = (Button) findViewById(R.id.bt_launchwvd);
//Set the 35. OnClickListener for the launch button
btLaunchWVD.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
//Display the WebView dialog
webViewDialog.show();
}
});
//Create a new dialog
webViewDialog = new Dialog(this);
//Remove the dialog's title
webViewDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
//Inflate the contents of this dialog with the Views defined at 'webviewdialog.xml'
webViewDialog.setContentView(R.layout.webviewdialog);
//With this line, the dialog can be dismissed by pressing the back key
webViewDialog.setCancelable(true);
//Initialize the Button object with the data from the 'webviewdialog.xml' file
btClose = (Button) webViewDialog.findViewById(R.id.bt_close);
//Define what should happen when the close button is pressed.
btClose.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
//Dismiss the dialog
webViewDialog.dismiss();
}
});
//Initialize the WebView object with data from the 'webviewdialog.xml' file
webView = (WebView) webViewDialog.findViewById(R.id.wb_webview);
//Scroll bars should not be hidden
webView.setScrollbarFadingEnabled(false);
//Disable the horizontal scroll bar
webView.setHorizontalScrollBarEnabled(false);
//Enable JavaScript
webView.getSettings().setJavaScriptEnabled(true);
//Set the user agent
webView.getSettings().setUserAgentString("Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.4) Gecko/20100101 Firefox/4.0");
//Clear the cache
webView.clearCache(true);
//Make the webview load the specified URL
String url = "http://phppot.com/demo/jquery-contact-form-with-attachment-using-php/";
webView.loadUrl(url);
}
}
Please let me know what fixes do I need to apply to the code.
Try to implement WebChromeClient to select image from local :
private Uri mCapturedImageURI;
private int FILECHOOSER_RESULTCODE=11;
private ValueCallback<Uri> mUploadMessage;
webView.setWebChromeClient(new WebChromeClient() {
// openFileChooser for Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType){
try{
mUploadMessage = uploadMsg;
// Create AndroidExampleFolder at sdcard
File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), getString(R.string.app_name));
if (!imageStorageDir.exists()) {
// Create AndroidExampleFolder at sdcard
imageStorageDir.mkdirs();
}
// Create camera captured image file path and name
File file = new File(imageStorageDir + File.separator + "IMG_" + String.valueOf(System.currentTimeMillis())+ ".jpg");
mCapturedImageURI = Uri.fromFile(file);
// Camera capture image intent
final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
// Create file chooser intent
Intent chooserIntent = Intent.createChooser(i,"Image Chooser");
// Set camera intent to file chooser
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[] { captureIntent });
// On select image call onActivityResult method of activity
startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
}
catch(Exception e){
e.printStackTrace();
}
}
// openFileChooser for Android < 3.0
public void openFileChooser(ValueCallback<Uri> uploadMsg){
openFileChooser(uploadMsg, "");
}
//openFileChooser for other Android versions
public void openFileChooser(ValueCallback<Uri> uploadMsg,String acceptType,String capture) {
openFileChooser(uploadMsg, acceptType);
}
// The webPage has 2 filechoosers and will send a
// console message informing what action to perform,
// taking a photo or updating the file
public boolean onConsoleMessage(ConsoleMessage cm) {
onConsoleMessage(cm.message(), cm.lineNumber(), cm.sourceId());
return true;
}
public void onConsoleMessage(String message, int lineNumber, String sourceID) {
//Log.d("androidruntime", "Show console messages, Used for debugging: " + message);
}
});
Upload selected image onActivityResult :
#Override
protected void onActivityResult(int requestCode, int resultCode,Intent intent) {
if(requestCode==FILECHOOSER_RESULTCODE){
if (null == this.mUploadMessage) {
return;
}
Uri result=null;
try{
if (resultCode != RESULT_OK) {
result = null;
} else {
// retrieve from the private variable if the intent is null
result = intent == null ? mCapturedImageURI : intent.getData();
}
}
catch(Exception e)
{
e.printStackTrace();
}
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
Here is the edited working code:
package com.example.anandsingh.webproject;
import com.example.testweb.R;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class TestWeb extends Activity {
/** Called when the activity is first created. */
WebView web;
ProgressBar progressBar;
private ValueCallback<Uri> mUploadMessage;
private final static int FILECHOOSER_RESULTCODE = 1;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == mUploadMessage)
return;
Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
web = (WebView) findViewById(R.id.webView1);
web = new WebView(this);
web.getSettings().setJavaScriptEnabled(true);
web.setScrollbarFadingEnabled(false);
// Disable the horizontal scroll bar
web.setHorizontalScrollBarEnabled(false);
// Enable JavaScript
web.getSettings().setJavaScriptEnabled(true);
// Set the user agent
web.getSettings().setUserAgentString("Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.4) Gecko/20100101 Firefox/4.0");
// Clear the cache
web.clearCache(true);
// Make the webview load the specified URL
String url = "http://phppot.com/demo/jquery-contact-form-with-attachment-using-php/";
web.loadUrl(url);
web.setWebViewClient(new myWebClient());
web.setWebChromeClient(new WebChromeClient() {
// The undocumented magic method override
// Eclipse will swear at you if you try to put #Override here
// For Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
}
// For Android 3.0+
public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE);
}
// For Android 4.1
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
}
});
setContentView(web);
}
public class myWebClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
}
}
// flipscreen not loading again
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
}

Categories

Resources