I have a WebView that is supposed to load the mobile version of a website, but when I try to load it inside the WebView it only appears as a white screen. I have tried loading the same URL in my android browser, and on my desktop with a User-Agent Switcher. I know the page is done loading also, because I have a method onPageFinished() that displays a toast when the page is displayed. Every time I load the application I am greeted with a white screen and then a few seconds later, the Toast message.
EDIT: I have tried different mobile web sites, and they all work in the WebView, the only one that is giving me trouble is this one: https://zangleweb01.clovisusd.k12.ca.us/StudentConnect/Home/Login
MainActivity.java
package com.student.connect;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.net.Uri;
import android.os.Bundle;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ArrayAdapter;
import android.widget.Toast;
public class MainActivity extends FragmentActivity implements
ActionBar.OnNavigationListener {
/**
* The serialization (saved instance state) Bundle key representing the
* current dropdown position.
*/
private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";
#SuppressWarnings("unused")
private WebView student_zangle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar to show a dropdown list.
final ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
// Set up the dropdown list navigation in the action bar.
actionBar.setListNavigationCallbacks(
// Specify a SpinnerAdapter to populate the dropdown list.
new ArrayAdapter<String>(getActionBarThemedContextCompat(),
android.R.layout.simple_list_item_1,
android.R.id.text1, new String[] {
getString(R.string.title_section1),
getString(R.string.title_section2),
getString(R.string.title_section3), }), this);
}
/**
* Backward-compatible version of {#link ActionBar#getThemedContext()} that
* simply returns the {#link android.app.Activity} if
* <code>getThemedContext</code> is unavailable.
*/
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private Context getActionBarThemedContextCompat() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
return getActionBar().getThemedContext();
} else {
return this;
}
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Restore the previously serialized current dropdown position.
if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
getActionBar().setSelectedNavigationItem(
savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
// Serialize the current dropdown position.
outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActionBar()
.getSelectedNavigationIndex());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#SuppressLint("NewApi")
#Override
public boolean onNavigationItemSelected(int position, long id)
{
WebView student_zangle = (WebView) findViewById(R.id.student_zangle);
student_zangle.setWebViewClient( new YourWebClient());
student_zangle.loadUrl("https://zangleweb01.clovisusd.k12.ca.us/StudentConnect/Home/Login");
student_zangle.setDrawingCacheEnabled(false);
WebSettings settings = student_zangle.getSettings();
student_zangle.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setAllowUniversalAccessFromFileURLs(true);
settings.setAllowContentAccess(true);
student_zangle.setDownloadListener(new DownloadListener()
{
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype, long contentLength)
{
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setType("application/x-rar-compressed");
intent.setData(Uri.parse(url));
startActivity(intent);
}
});
return true;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
}
return super.onKeyDown(keyCode, event);
}
private class YourWebClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains("mailto"))
{
String mail = url.replaceFirst("mailto:", "");
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_EMAIL, mail );
startActivity(intent);
return true;
}
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url)
{
Toast.makeText(getApplicationContext(), "done",
Toast.LENGTH_LONG).show();
}
}
}
Try buildDrawingCache with following changes:
student_zangle.setDrawingCacheEnabled(true);
student_zangle.buildDrawingCache();
Note : You should avoid calling this method when hardware acceleration is enabled
Related
The features are enabled once the onCreate() methood is executed for the first time, but after i do a screen rotation none of the features get saved, even though I've overridden the onSaveInstanceState() method and I've also tried using the onRestoreInstanceState() method.
Kindly help me out.
I'll attach the code below.
Activity file
import android.app.LoaderManager;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.Loader;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class Main3Activity extends AppCompatActivity implements LoaderManager.LoaderCallbacks{
Toolbar toolbar;
WebView webView;
ProgressDialog progressDialog;
final String urld="https://www.google.co.in/";
final int LOADER_ID=1;
Bundle bundle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
webView = (WebView)findViewById(R.id.wb1);
progressDialog = new ProgressDialog(Main3Activity.this);
progressDialog.setTitle("Loading");
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Please Wait...");
progressDialog.setCancelable(true);
if(savedInstanceState!=null)
{
webView.restoreState(savedInstanceState);
webView.getSettings().setJavaScriptEnabled(true);
}
else {
webView.getSettings().setJavaScriptEnabled(true);
webView.setFocusable(true);
webView.setFocusableInTouchMode(true);
//webView.getSettings().setSupportZoom(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(true);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
//webView.setInitialScale(1);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.setBackgroundColor(Color.WHITE);
//webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
webView.getSettings().setDomStorageEnabled(true);
//webView.getSettings().setDatabaseEnabled(true);
webView.getSettings().setAppCacheEnabled(true);
//webView.setWebChromeClient(new WebChromeClient());
if (Build.VERSION.SDK_INT >= 19) {
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else {
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
/*if( URLUtil.isNetworkUrl(url) ) {
return false;
}
if (appInstalledOrNot(url)) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity( intent );
} else {
// do something if app is not installed
}
return true;*/
if (Uri.parse(url).getHost().endsWith("google.co.in")) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
CookieManager.getInstance().setAcceptCookie(true);
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
progressDialog.show();
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
progressDialog.dismiss();
super.onPageFinished(view, url);
}
});
}
bundle = savedInstanceState;
LoaderManager loaderManager = getLoaderManager();
// Initialize the loader. Pass in the int ID constant defined above and pass in null for
// the bundle. Pass in this activity for the LoaderCallbacks parameter (which is valid
// because this activity implements the LoaderCallbacks interface).
loaderManager.initLoader(LOADER_ID, null, this);
}
/*private boolean appInstalledOrNot(String uri) {
PackageManager pm = getPackageManager();
try {
pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
return true;
} catch (PackageManager.NameNotFoundException e) {
}
return false;
}*/
#Override
public void onBackPressed() {
if(webView.canGoBack())
{
webView.goBack();
}
else {
super.onBackPressed();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle arrow click here
if (item.getItemId() == android.R.id.home) {
finish(); // close this activity and return to preview activity (if there is any)
}
return super.onOptionsItemSelected(item);
}
#Override
public Loader onCreateLoader(int i, Bundle bundle) {
return new LoadingPageInBackground(this,urld,bundle,webView,progressDialog);
}
#Override
public void onLoadFinished(Loader loader, Object o) {
}
#Override
public void onLoaderReset(Loader loader) {
//webView.setVisibility(WebView.GONE);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
webView.saveState(outState);
Toast.makeText(Main3Activity.this,"Saved",Toast.LENGTH_SHORT).show();
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle state) {
webView.restoreState(state);
Toast.makeText(Main3Activity.this,"Restored",Toast.LENGTH_SHORT).show();
super.onRestoreInstanceState(state);
}
}
restoreState is not reliable, based on the documentation for restoreState :
If it is called after this WebView has had a chance to build state
(load pages, create a back/forward list, etc.) there may be
undesirable side-effects. Please note that this method no longer
restores the display data for this WebView.
Based on the documentation for saveState:
Please note that this method no longer stores the display data for
this WebView
You have to reload your WebView in onCreate(). You can store the URL in SharedPreference and load it in onCreate().
Another alternative is to handle the Orientation by your self and keep WebView unchanged. You can handle the orientation change by adding android:configChanges="orientation" in your manifest and Overriding onConfigurationChanged().
If the user were to select an item from the drop down navigation menu, it appears as selected only until the application closes. Then, on reopening the app, it displays the first item as selected. How can I keep an item permanently selected until the user changes it even after the activity closes? FYI There is only one activity in my application.
MainActivity.java
package com.student.connect;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.net.Uri;
import android.os.Bundle;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ArrayAdapter;
import android.widget.Toast;
public class MainActivity extends FragmentActivity implements
ActionBar.OnNavigationListener {
/**
* The serialization (saved instance state) Bundle key representing the
* current dropdown position.
*/
private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";
#SuppressWarnings("unused")
private WebView student_zangle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar to show a dropdown list.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
actionBar.setTitle(" ");
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setLogo(R.drawable.logo);
actionBar.setDisplayUseLogoEnabled(true);
// Set up the dropdown list navigation in the action bar.
actionBar.setListNavigationCallbacks(
// Specify a SpinnerAdapter to populate the dropdown list.
new ArrayAdapter<String>(getActionBarThemedContextCompat(),
android.R.layout.simple_list_item_1,
android.R.id.text1, new String[] {
"Select a District",
"Clovis Unified",
"Claremont Unified",
"San Diego Unified",
"Pleasanton Unified",
"San Juan Unified", }), this);
}
/**
* Backward-compatible version of {#link ActionBar#getThemedContext()} that
* simply returns the {#link android.app.Activity} if
* <code>getThemedContext</code> is unavailable.
*/
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private Context getActionBarThemedContextCompat() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
return getActionBar().getThemedContext();
} else {
return this;
}
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Restore the previously serialized current dropdown position.
if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
getActionBar().setSelectedNavigationItem(
savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
// Serialize the current dropdown position.
outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActionBar()
.getSelectedNavigationIndex());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#SuppressLint("NewApi")
#Override
public boolean onNavigationItemSelected(int position, long id)
{
WebView student_zangle = (WebView) findViewById(R.id.student_zangle);
student_zangle.setWebViewClient( new YourWebClient());
WebSettings settings = student_zangle.getSettings();
settings.setLoadWithOverviewMode(true);
settings.setUseWideViewPort(true);
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setAllowUniversalAccessFromFileURLs(true);
settings.setAllowContentAccess(true);
settings.setBuiltInZoomControls(true);
settings.setDisplayZoomControls(false);
if ( position == 0 )
{
Toast.makeText(getApplicationContext(), "Select a District from the Menu Above", Toast.LENGTH_LONG).show();
}
else if ( position == 1 )
{
student_zangle.loadUrl("https://zangleweb01.clovisusd.k12.ca.us/studentconnect/");
student_zangle.zoomOut();
student_zangle.zoomOut();
student_zangle.zoomOut();
}
else if ( position == 2 )
{
student_zangle.loadUrl("http://studentconnect.cusd.claremont.edu/");
}
else if ( position == 3 )
{
student_zangle.loadUrl("https://zangle.sandi.net/studentconnect/");
}
else if ( position == 4 )
{
student_zangle.loadUrl("https://sis.pleasanton.k12.ca.us/StudentPortal/");
}
else if ( position == 5 )
{
student_zangle.loadUrl("https://sis.sanjuan.edu/studentportal");
}
student_zangle.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
settings.setUserAgentString("Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.4) Gecko/20100101 Firefox/4.0");
student_zangle.setDownloadListener(new DownloadListener()
{
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype, long contentLength)
{
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setType("application/x-rar-compressed");
intent.setData(Uri.parse(url));
startActivity(intent);
}
});
return true;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
}
return super.onKeyDown(keyCode, event);
}
private class YourWebClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains("mailto"))
{
String mail = url.replaceFirst("mailto:", "");
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_EMAIL, mail );
startActivity(intent);
return true;
}
view.loadUrl(url);
return true;
}
}
}
Use SharedPreferences for this case.
//write your selected position in preferences when the user clicks the DropDown menu
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
preferences.edit().putInt("selectedPosition", selectedItemIndex).commit();
When the user returns to the Activity (launching the app again), you have to read the value from Preferences, like this:
int position = PreferenceManager.getDefaultSharedPreferences(this).getInt("selectedPosition",0);
Then just select your dropdown menu item programatically.
The SharedPreferences data is kept even when the app closes. So you can trust it because it's persistent data and does not depend on your App state.
Note that your Preferences will be empty if the user unninstalls the app or clears the app data.
I am developing an android app. which is using webview to render a html page but it stays blank while the page loads. I want to add a loading spinner in the action bar so the user knows that something is loading and it not blank.
Please can anyone guide me how to do that.
My existing code -
package com.pranavsethi.dpsrkp;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.DownloadListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class Achievements extends Activity{
private WebView mWebView;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webvew_client_layout);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
//For web view
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true); //enable javascript
mWebView.getSettings().setBuiltInZoomControls(true); //enable zoom
mWebView.getSettings().setDisplayZoomControls(false);
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setUseWideViewPort(true);
mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
mWebView.setScrollbarFadingEnabled(true);
mWebView.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
// handle download, here we use brower to download, also you can try other approach.
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
mWebView.loadUrl("http://pranavsethi.tk"); // name of website to load
mWebView.setWebViewClient(new HelloWebViewClient()); //removing loading progressbar
}
private class HelloWebViewClient extends WebViewClient{ //our web client
#Override
public void onReceivedError(WebView view, int errorCode, //Code for checking the internet connection and return the error if fails
String description, String failingUrl) {
Intent intent = new Intent(Achievements.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return;
}
#Override
public boolean shouldOverrideUrlLoading(WebView webview, String url)
{
webview.loadUrl(url);
return true;
}
}
#Override
public boolean onKeyDown(int KeyCode, KeyEvent event)
{
if ((KeyCode)== KeyEvent.KEYCODE_BACK && mWebView.canGoBack())
{
mWebView.goBack();
return true;
}
return super.onKeyDown(KeyCode, event);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.home:
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
overridePendingTransition (R.anim.right_slide_in, R.anim.fade_out);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
#Override
public void onBackPressed()
{
this.finish();
overridePendingTransition (0, R.anim.right_slide_out);
return;
}
}
SOLUTION
Add the following -
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setProgressBarIndeterminateVisibility(true);
After -
super.onCreate(savedInstanceState);
And this in your WebViewClient
private class HelloWebViewClient extends WebViewClient{
#Override
public boolean shouldOverrideUrlLoading(WebView webview, String url){
webview.loadUrl(url);
setProgressBarIndeterminateVisibility(true);
return true;
}
#Override
public void onPageFinished(WebView webview, String url){
super.onPageFinished(webview, url);
setProgressBarIndeterminateVisibility(false);
}
}
I've pretty much followed all the necessary steps for adding a ProgressBar to my WebView using ActionBarSherlock, but I don't get any results on pre-Android 4.0. Can anyone help? I've imported Window from ABS, added requestWindowFeature(Window.FEATURE_PROGRESS); before setting content, i just don't know what to do. Please don't tell me to follow the samples, since I've tried that and I've gotten no results. Thank you.
Here is the code for MainActivity.class
package com.twk95.webviewtest;
import android.content.Intent;
import android.os.Bundle;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.Window;
public class MainActivity extends SherlockActivity {
public static WebView webView;
final SherlockActivity MyActivity = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.WebView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView webview, String url) {
webview.loadUrl(url);
return true;
}
});
webView.loadUrl("http://www.google.com");
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
MyActivity.setTitle("Loading...");
MyActivity.setProgress(progress * 100);
setSupportProgressBarVisibility(true);
if (progress == 100) {
MyActivity.setTitle(R.string.app_name);
setSupportProgressBarVisibility(false);
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.webview_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.webReload:
webView.reload();
break;
case android.R.id.home:
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
}
return false;
}
}
Make sure that the requestWindowFeature method is using com.actionbarsherlock.app.SherlockActivity.requestWindowFeature(long featureId) then use setSupportProgress(int progress) to update it rather than using MyActivity.setProgress()
Here's one of the tabs I have that loads a page.
package realstrat.cfostudio.magazineapp;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import realstrat.cfostudio.magazineapp.R;
public class TabActivity3 extends Activity {
WebView mWebView;
private ProgressDialog progressBar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.web);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setPluginsEnabled(true);
mWebView.loadUrl("--company URL--");
mWebView.setWebViewClient(new FirstTabWebViewClient());
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putBoolean("OverviewMode", mWebView.getSettings().getLoadWithOverviewMode());
mWebView.saveState(savedInstanceState);
super.onSaveInstanceState(savedInstanceState);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
((WebView)findViewById(R.id.webview1)).restoreState(savedInstanceState);
if (savedInstanceState.getBoolean("OverviewMode") == false) {
((WebView)findViewById(R.id.webpageview)).getSettings().setLoadWithOverviewMode(false);
((WebView)findViewById(R.id.webpageview)).getSettings().setUseWideViewPort(false);
}
else {
((WebView)findViewById(R.id.webpageview)).getSettings().setLoadWithOverviewMode(true);
((WebView)findViewById(R.id.webpageview)).getSettings().setUseWideViewPort(true);
}
return;
}
private class FirstTabWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// YouTube video link
if (url.startsWith("vnd.youtube"))
{
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return (true);
}
if (url.endsWith("-m.html")){
mWebView.getSettings().setLoadWithOverviewMode(false);
mWebView.getSettings().setUseWideViewPort(false);
}
else {
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setUseWideViewPort(true);
}
view.loadUrl(url);
return true;
}
public void onPageStarted(WebView view, String url, Bitmap favicon){
progressBar = ProgressDialog.show(TabActivity3.this, "", "Loading...", true);
}
public void onPageFinished(WebView view, String url) {
progressBar.hide();
if (url.endsWith("-m.html")){
mWebView.getSettings().setLoadWithOverviewMode(false);
mWebView.getSettings().setUseWideViewPort(false);
}
else {
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setUseWideViewPort(true);
}
return;
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Context context = getApplicationContext();
CharSequence text = "Desc: " + description;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
return;
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Once in a while it will crash with a nullPointerException on the line progressBar.hide() under onPageFinished(). That doesn't make any sense since onPageStarted() starts the progressBar, and onPageStarted always comes before onPageFinished(). Why is this?
This only happens like, once in 10 times or something, which is really confusing to me.
It usually happens (always?) when the activity is being started for the first time.
try this
if(progressBar!=null)
progressBar.hide();
Maybe the Activity has been restarted in between the two callbacks? Try rotating the phone while the progressBar is shown to see what the results are.
Try to load progress bar as singleton object. If you create anther progress bar object before hide first one then second progress bar will crash in hide().
if(_progressBar == null)
_progressBar = new ProgressDialog(this);