Android App - webview not opening file upload - android

I created an Android app(On Android Studio) that loads/open a website. Everything is OK on the browser but on the app, the image upload is not opening my phone's photos so that I can select the pic to upload - how to solve this??.
package com.example.opex.shoutout;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class MainActivity extends AppCompatActivity {
WebView webView;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new MainActivity.myWebClient());
webView.loadUrl("http://rms.irsglobal.net/mobile/");
webView.setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading(WebView view, String url) {
String url2="http://rms.irsglobal.net/mobile/";
// all links with in ur site will be open inside the webview
//links that start ur domain example(http://www.example.com/)
if (url != null && url.startsWith(url2)){
return false;
}
// all links that points outside the site will be open in a normal android browser
else {
view.getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
}
}
});
}
public class myWebClient extends WebViewClient
{
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
/*#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
return super.shouldOverrideUrlLoading(view, request);
}*/
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()){
webView.goBack();
}
return super.onKeyDown(keyCode, event);
}
}

Full working code :)
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);
}*/
}

Related

In andriod webview whatsapp button is not working

I am trying android webview but whatsapps button give an error when i want to connect whatsapp app in my mobile, the error is like - ERR_UNKNOWN_URI_SCHEME,
below are my code, please help me-
public class MainActivity extends AppCompatActivity {
private WebView mywebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mywebView=(WebView) findViewById(R.id.webview);
mywebView.setWebViewClient(new WebViewClient());
mywebView.loadUrl("https://royalahm.com");
WebSettings webSettings=mywebView.getSettings();
webSettings.setJavaScriptEnabled(true);
}
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){
if(url.startsWith("whatsapp:")) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
return true;
}
return false;
}
}
#Override
public void onBackPressed(){
if(mywebView.canGoBack()) {
mywebView.goBack();
}
else{
super.onBackPressed();
}
}
}
Try This :
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){
if( url.startsWith("http:") || url.startsWith("https:") ) {
return false;
}
try {
// Otherwise allow the OS to handle things like tel, mailto, etc.
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
}catch (Exception e){
Log.i("IvaExc",e.toString());
}
return true;
}
}

How to open .ppt, .pptx, .doc, .xlsx files in a webview from the SD card?

"How to open .ppt, .pptx,.doc, .xlsx files in android webview within app?"
"This is requirement to open any documents which i have download in sd card and open witin android webview. In the past I have tried lot of google suggested answer which they are open file outside the app using intent and MIME Type or open online file like webview.loadUrl("http://docs.google.com/gview?embedded=true&url=http://myurl.com/mySlide.ppt");"
public class WebContentViewActivity extends BaseActivity {
#BindView(R.id.webView)
WebView webView;
private String docUrl="http://docs.google.com/gview?
embedded=true&url=";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.VmPolicy.Builder builder = new
StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
setContentView(R.layout.activity_video_view);
ButterKnife.bind(this);
WebSettings settings = webView.getSettings();
webView.clearCache(true);
webView.clearHistory();
settings.setJavaScriptEnabled(true);
settings.setAllowFileAccessFromFileURLs(true);
settings.setAllowUniversalAccessFromFileURLs(true);
settings.setBuiltInZoomControls(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setUseWideViewPort(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setWebViewClient(new WebViewController(this));
filePath =
"/storage/emulated/0/New_Files/1550130536314somefile.pptx";
fileName = "1550130536314somefile.pptx";
if (!TextUtils.isEmpty(fileName )){
Uri fileUri = Uri.fromFile(fileName );
webView.loadUrl(fileUri.toString());
// webView.loadUrl(docUrl+fileUri);//getting 400.That's an error
on webview
}
/**
* Custom WebView controller class
*/
private class WebViewController extends WebViewClient {
private Context mContext;
//TODO : use this flag while open clicked url in the same WebView
public WebViewController(Context ctx) {
this.mContext = ctx;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
System.out.println("onPageStarted: " + url);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return false;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.v("Webview Error", description);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack())
{
webView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
I want to show any document file witin webview as above in the code.

How to open new screen on webview url click?

In my app i am using webview to display some web data, i want to implement a functionality where if a user clicks on any link a new screen (activity) will open and url's data will be displayed in that activity's webview. i have tried setting a webview client to webview and overriding its onPageStarted,shouldOverrideUrlLoading methods but they all open the url within the same screen.
Here is my code
webview.loadData(html, "text/html; charset=utf-8", "UTF-8");
webview.setWebViewClient(webViewClient);
}
WebViewClient webViewClient = new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
if (url.startsWith("http://")) {
Intent intent = new Intent(FirstActivity.this, WebActivity.class);
intent.putExtra("url", url);
startActivity(intent);
}
}
#Override
public void onPageFinished(WebView view, String url) {
}
#SuppressWarnings("deprecation")
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
#TargetApi(Build.VERSION_CODES.N)
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
return false;
}
#Override
public void onLoadResource(WebView view, String url) {
super.onLoadResource(view, url);
}
};
How this can be implemented? any help will be appreciated
Try this:
#SuppressWarnings("deprecation")
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("http://")) {
Intent intent = new Intent(FirstActivity.this, WebActivity.class);
intent.putExtra("url", url);
startActivity(intent);
return true;
}
return false;
}
#TargetApi(Build.VERSION_CODES.N)
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
String url = request.getUrl().toString();
if (url.startsWith("http://")) {
Intent intent = new Intent(FirstActivity.this, WebActivity.class);
intent.putExtra("url", url);
startActivity(intent);
return true;
}
return false;
}
Try this. But you first need to set a start website like google.com
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends Activity {
private WebView view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view = (WebView) this.findViewById(R.id.webView);
view.getSettings().setJavaScriptEnabled(true);
view.getSettings().setDomStorageEnabled(true);
view.setWebViewClient(new MyBrowser());
view.loadUrl("[YOUR_WEBSITE]"); //try js alert
view.setWebChromeClient(new WebChromeClient()); // adding js alert support
}
private class MyBrowser extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("tel:") || url.startsWith("sms:") || url.startsWith("smsto:") || url.startsWith("mailto:") || url.startsWith("mms:") || url.startsWith("mmsto:") || url.startsWith("market:")) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
else {
view.loadUrl(url);
return true;
}
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && view.canGoBack()) {
view.goBack(); //method goback()
return true;
}
return super.onKeyDown(keyCode, event);
}
}
If links are external to the site, you could do something like this:
webview.setWebViewClient(new LinkExtWebViewClient());
And then:
public class LinkExtWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(Uri.parse(url).getHost().endsWith(" if your site is www.myurl.com, here you have to insert 'myurl.com' ")) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
return true;
}
}
Let me know if it works :)

Webview email link (mailto)

I have a view and view the site has malito code to send email.
When I open the link opens in an error.
I want that when I open the link opens Gmail app or another email application.
Thanks to all helpers.
public class teacher extends Activity implements OnClickListener {
WebView webView;
final Activity activity = this;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.teacher);
webView = (WebView) findViewById(R.id.webView145);
webView.getSettings().setJavaScriptEnabled(true); webView.loadUrl("https://dl.dropboxusercontent.com/u/233211/%D7%A8%D7%A9%D7%99%D7%95%D7%9F/iWebKit%20demo/ther.html");
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
activity.setTitle("Loading...");
activity.setProgress(progress * 100);
if (progress == 100)
activity.setTitle(R.string.app_name);
} });
webView.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
// Handle the error
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true; } });}
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
Intent B = new Intent(this, MainActivity.class);
startActivity(B);
}}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (webView.canGoBack() == true) {
webView.goBack();
} else {
finish();
}return true;} }
return super.onKeyDown(keyCode, event);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}}
You have to create a subclass of WebViewClient and override mailto URL loading. Example:
public class MyWebViewClient extends WebViewClient {
private final WeakReference<Activity> mActivityRef;
public MyWebViewClient(Activity activity) {
mActivityRef = new WeakReference<Activity>(activity);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("mailto:")) {
final Activity activity = mActivityRef.get();
if (activity != null) {
MailTo mt = MailTo.parse(url);
Intent i = newEmailIntent(activity, mt.getTo(), mt.getSubject(), mt.getBody(), mt.getCc());
activity.startActivity(i);
view.reload();
return true;
}
} else {
view.loadUrl(url);
}
return true;
}
private Intent newEmailIntent(Context context, String address, String subject, String body, String cc) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_EMAIL, new String[] { address });
intent.putExtra(Intent.EXTRA_TEXT, body);
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_CC, cc);
intent.setType("message/rfc822");
return intent;
}
}
Then you have to set this custom WebViewClient to your WabView:
webView.setWebViewClient(new MyWebViewClient(activity);
You should update your's WebViewClient with the following:
#SuppressWarnings("deprecation")
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
proceedUrl(view, Uri.parse(url))
return true;
}
#TargetApi(Build.VERSION_CODES.N)
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
proceedUrl(view, request.getUrl());
return true;
}
private void proceedUrl(View view, Uri uri){
if (uri.toString().startsWith("mailto:")) {
startActivity(new Intent(Intent.ACTION_SENDTO, uri));
} else if (uri.toString().startsWith("tel:")) {
startActivity(new Intent(Intent.ACTION_DIAL, uri));
} else {
view.loadUrl(uri.toString());
}
}
Note : - After Android Nougat shouldOverrideUrlLoading is Deprecated
You need to use shouldOverrideUrlLoading along with shouldOverrideUrlLoading for better support.
Also, you might want to check if URL have mailto: or tel:, which are used in HTML5 to trigger mail client and phone dial respectively.
A complete solution will look like this now
#SuppressWarnings("deprecation")
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("mailto:")) {
//Handle mail Urls
startActivity(new Intent(Intent.ACTION_SENDTO, Uri.parse(url)));
} else if (url.startsWith("tel:")) {
//Handle telephony Urls
startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
} else {
view.loadUrl(url);
}
return true;
}
#TargetApi(Build.VERSION_CODES.N)
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
final Uri uri = request.getUrl();
if (uri.toString().startsWith("mailto:")) {
//Handle mail Urls
startActivity(new Intent(Intent.ACTION_SENDTO, uri));
} else if (uri.toString().startsWith("tel:")) {
//Handle telephony Urls
startActivity(new Intent(Intent.ACTION_DIAL, uri));
} else {
//Handle Web Urls
view.loadUrl(uri.toString());
}
return true;
}

Progress bar only work on loading page?

I've in the following code the progressbar working on the first page load. after when I click on other links, the progrss bar is not shown ?
If somebody can tell me how to change this code to have the progress bar working on all loading ?
Thanks,
André.
public class Android_Activity extends Activity {
WebView webview;
#Override
protected void onSaveInstanceState(Bundle outState) {
WebView webview = (WebView) findViewById(R.id.webview);
webview.saveState(outState);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set the main content view
setContentView(R.layout.main);
// check if an instance is stored and so restore it
if (savedInstanceState != null){
((WebView)findViewById(R.id.webview)).restoreState(savedInstanceState);
}
final ProgressDialog progressBar = ProgressDialog.show(this, getString(R.string.progress_title),
getString(R.string.progress_msg));
webview = (WebView)findViewById(R.id.webview);
webview.setHttpAuthUsernamePassword(getString(R.string.kdg_host),
getString(R.string.kdg_realm),
getString(R.string.kdg_user_name),
getString(R.string.kdg_password)
);
//webview.setWebViewClient(new myWebViewClient());
webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webview.getSettings().setRenderPriority(RenderPriority.HIGH);
webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
webview.getSettings().setAllowFileAccess(true);
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebViewClient(new WebViewClient() {
public void onPageStarted(WebView view, String url) {
if (!progressBar.isShowing()) {
progressBar.show();
}
}
public void onPageFinished(WebView view, String url) {
//super.onPageFinished(view, url);
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
});
webview.loadUrl(getString(R.string.base_url));
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
webview.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
private class myWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
boolean error = false;
// check if it's an MAILTO URL
if(url.substring(0, 6).equalsIgnoreCase("mailto")){
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent .setType("plain/text");
emailIntent .putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{url.substring(7)});
startActivity(Intent.createChooser(emailIntent, "Send mail..."));
return true;
}
// check if it's an EXT:// (Call Web Browser)
else if(url.substring(0, 6).equalsIgnoreCase("ext://")){
Uri uriUrl = Uri.parse(url.substring(6));
Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
startActivity(launchBrowser);
return true;
}
// check if it's an RTSP URL
else if(url.substring(0, 4).equalsIgnoreCase("rtsp")){
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
return true;
}
// else if it's an MP4 file link
else if(url.endsWith(".mp4")){
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "video/mp4");
startActivity(intent);
return true;
}
// else if it's a 3GP file link
else if(url.endsWith(".3gp")){
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "video/3gp");
startActivity(intent);
return true;
}
// else if it's a MP3 file link
else if(url.endsWith(".mp3")){
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "audio/mp3");
startActivity(intent);
return true;
}
// else if it's a page URL
else{
URL Url;
try {
Url = new URL(url);
HttpURLConnection httpURLConnection = (HttpURLConnection) Url
.openConnection();
int response = httpURLConnection.getResponseCode();
if ((response >= 200)&&(response < 400))
//view.loadUrl(url);
error = false;
else
error = true;
} catch (Exception e) {
error = true;
}
}
// if an error occurred
if (error) {
showErrorDialog();
}
view.loadUrl(url);
return true;
}
}
#Override
public void onResume() {
super.onResume();
webview.reload();
}
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
showErrorDialog();
}
public void showErrorDialog(){
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle(getString(R.string.error_title));
alertDialog.setMessage(getString(R.string.error_msg));
alertDialog.setButton(getString(R.string.ok_btn),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
});
alertDialog.show();
}
}
Use below working code ::
public class Android_Activity extends Activity {
private Android_Activity _activity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_PROGRESS);
_activity = this;
setContentView(R.layout.main);
mwebview=(WebView)view.findViewById(R.id.webview);
mwebview.getSettings().setJavaScriptEnabled(true);
mwebview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
if(checkInternetConnection(_activity)==true){
if(savedInstanceState==null)
mwebview.loadUrl(URL);
else
mwebview.restoreState(savedInstanceState);
}
else{
AlertDialog.Builder builder = new AlertDialog.Builder(_activity);
builder.setMessage("Please check your network connection.")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
mwebview.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int progress) {
if(mwebview.getVisibility()==View.VISIBLE)
{
_activity.setProgress(progress * 100);
}
}
});
mwebview.setWebViewClient(new HelloWebViewClient());
}
//HelloWebViewClient class for webview
private class HelloWebViewClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
// TODO Auto-generated method stub
super.onReceivedError(view, errorCode, description, failingUrl);
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
view.loadUrl(url);
return true;
}
} //HelloWebViewClient-class
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && mwebview.canGoBack() ){
mwebview.goBack();
return true;
}
// If it wasn't the Back key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
//To check whether network connection is available on device or not
public static boolean checkInternetConnection(Activity _activity) {
ConnectivityManager conMgr = (ConnectivityManager) _activity.getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected())
return true;
else
return false;
}//checkInternetConnection()
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.KDG_EPG_Iphone"
android:versionCode="1"
android:versionName="1.00.00" android:installLocation="auto">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<supports-screens
android:resizeable="false"
android:smallScreens = "false"
android:normalScreens = "true"
android:largeScreens = "false"
android:anyDensity = "true"/>
<uses-sdk android:minSdkVersion="8"/>
<application android:label="#string/app_name" android:icon="#drawable/icon">
<activity android:screenOrientation="portrait"
android:theme="#android:style/Theme.Black.NoTitleBar"
android:configChanges="keyboardHidden|orientation"
android:label="#string/app_label" android:name="com.KDG_EPG_Iphone.KDG_EPG_Iphone_Activity" android:icon="#drawable/icon">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Categories

Resources