Trouble with Webview, ProgressBar, and ActionBarSherlock - android

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()

Related

Android onBackPressed issue

I created a basic webview app following instructions from web.
everything works well except the backpress button, when webview connected to server backpress goes to home screen, but when i clicked the home in menu items (search and aboutpage) the app closed.
Here is my code
MainActivity.java
package com.dijitalyayincim.cekmekoy.cekmekoy_web;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
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.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class MainActivity extends AppCompatActivity {
private WebView webView;
private boolean isRedirected;
private ProgressBar progress;
String url = "file:///android_asset/www/index.html";
String url1 ="http://www.cekmekoy.info/index.php?option=com_sppagebuilder&view=page&id=12";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setContentView(R.layout.aa);
webView = (WebView) findViewById(R.id.webView);
startWebView(webView, url);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
case R.id.action_info:
Element adsElement = new Element();
adsElement.setTitle("Advertise with us");
View aboutPage = new AboutPage(this)
.isRTL(false)
.setImage(R.drawable.logo_cekmekoy)
.addItem(new Element().setTitle("Version 1.0"))
.addItem(adsElement)
.addGroup("Bize Ulaşın")
.addEmail("info#cekmekoy.info")
.addWebsite("http://www.cekmekoy.info/")
.addFacebook("cekmekoyinfo")
.addTwitter("cekmekoyinfo")
.addYoutube("UCYt3Z595jctz5oUhg0SMLqQ")
.addInstagram("cekmekoy_info")
.create();
setContentView(aboutPage);
setTitle("Bize Ulaşın");
return true;
case R.id.action_search:
setContentView(R.layout.test);
webView = (WebView) findViewById(R.id.search);
startWebView(webView, url1);
setTitle("Arama");
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
private void startWebView(WebView webView,String url) {
webView.setWebViewClient(new WebViewClient() {
ProgressDialog progressDialog;
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
startActivity(intent);
view.reload();
return true;
}
view.loadUrl(url);
isRedirected = true;
return false;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
isRedirected = false;
}
public void onLoadResource (WebView view, String url) {
if (!isRedirected) {
if (progressDialog == null) {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Yükleniyor...");
progressDialog.show();
}
}
}
public void onPageFinished(WebView view, String url) {
MainActivity.this.setTitle(view.getTitle());
try{
isRedirected=true;
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
}catch(Exception exception){
exception.printStackTrace();
}
}
});
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
}
#Override
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
}
i really appreciate if you can help
thanks...
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (mWebView.canGoBack()) {
mWebView.goBack();
} else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
Use this code. Hope help you.
Comment this finish line.and use your method. webView.goBack();
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// finish();
return true;
}
}

Making a News reading app in Android Studio (WebView). but when ever i click a video in a selected article it does not play

Is their something i'm doing wrong? Do i have to include some lib?
I've tried adding the Youtube Api but that didn't help.
Edit#1: This is the WebView code
On some instance the Audio Playback works but instead of video it's just a rotating circle animation trying to load the video.
package com.PAKGN.Mizzy;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import android.webkit.WebSettings;
private WebView webView1;
private Toolbar toolbar;
private String title;
private String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview);
// this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
WebView myWebView = (WebView) findViewById(R.id.webView1);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
title = getIntent().getExtras().getString("title");
url = getIntent().getExtras().getString("url");
getSupportActionBar().setTitle(title);
if (savedInstanceState != null) {
((WebView) findViewById(R.id.webView1)).restoreState(savedInstanceState);
} else {
webView1 = (WebView) findViewById(R.id.webView1);
webView1.getSettings().setJavaScriptEnabled(true);
webView1.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
final Activity activity = this;
webView1.setWebViewClient(new WebViewClient()
{
#Override
public boolean shouldOverrideUrlLoading(WebView view,
String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
});
webView1.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
// Activities and WebViews measure progress with different scales.
// The progress meter will automatically disappear when we reach 100%
activity.setProgress(progress * 1000);
}
});
webView1.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
}
});
runOnUiThread(new Runnable() {
#Override
public void run() {
// Code for WebView goes here
webView1.loadUrl(url);
}
});
}
}
#Override
protected void onSaveInstanceState(Bundle outState ){
((WebView) findViewById(R.id.webView1)).saveState(outState);
}
#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) && webView1.canGoBack()) {
webView1.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);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
.
You need to enable javaScript.WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
EDIT:
You are setting the WebClient for webview twice.
`webView1.setWebViewClient(new WebViewClient()
{
#Override
public boolean shouldOverrideUrlLoading(WebView view,
String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
});`
You aren't really doing anything here thats different from the original implementation and this code isn't even running because you replace the webview with another webclient so delete this.
` runOnUiThread(new Runnable() {
#Override
public void run() {
// Code for WebView goes here
webView1.loadUrl(url);
}
});
`
Delete this too, just type webview1.loadUrl(url) no need for a runOnUiThread.
` webView1.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
Delete this too, its this line that is causing your issue. `

WebView displaying white screen after page loads

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

Adding loading spinner on Action Bar while the WebView loads?

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);
}
}

Android webview loading dialog

I'm trying to implement a loading dialog in my webview application but whatever I do it just won't work.
What I want is the following, everytime someone clicks a link in the webview the loading dialog has to popup like this:
(source: wordpress.com)
And when the loading is done it has to disappear. Can anyone show me how to do it in my own source? I've tried a lot of things but there's always an issue so I really don't know how to.
This is my WebviewActivity:
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebviewActivity extends MainActivity {
private WebView myWebView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
myWebView = (WebView)findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.setWebViewClient(new WebViewClient());
myWebView.requestFocus(View.FOCUS_DOWN);
myWebView.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_UP:
if (!v.hasFocus()) {
v.requestFocus();
}
break;
}
return false;
}
});
}
#Override
public void onResume() {
super.onResume();
if ( isOnline() == true )
myWebView.loadUrl(webLink);
else if ( isOnline() == false )
showNoConnectionDialog();
}
#Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
}
}
Thank you very much for your help!!
You have to override the WebViewClient like this,
webview.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, final String url) {
progressDialog.cancel();
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
progressDialog.show();
}
});
webview.loadUrl(TwitterUrl);
This is my final solution:
myWebView.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
progressDialog.show();
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, final String url) {
progressDialog.dismiss();
}
});
This can be possible with WebChromeClient. It does worked for me.
Code snippet :
progressDialog.show(); // Add before page load
webView.setWebChromeClient(new HelpWebChromeClient());
private class HelpWebChromeClient extends WebChromeClient {
#Override
public void onProgressChanged(WebView view, int newProgress) {
if(newProgress == 100)
progressDialog.dismiss();
}
}

Categories

Resources