Android App: Adding Mailto to Web View for email functionality - android

package com.helloworld;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.view.KeyEvent;
import android.content.Intent;
import android.net.MailTo;
import android.content.Context;
public class HelloWorld extends Activity
{
final Activity activity = this;
WebView webview;
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (webview != null && (keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
webview.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);
webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setBuiltInZoomControls(true);
webview.getSettings().setUseWideViewPort(true);
webview.loadUrl("http://www.blahblah.org");
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)
{
if(url.startsWith("mailto:")){
MailTo mt = MailTo.parse(url);
Intent i = newEmailIntent(activity.this, mt.getTo(), mt.getSubject(), mt.getBody(), mt.getCc());
startActivity(i);
view.reload();
return true;
}
view.loadUrl(url);
return true;
}
});
}
public static 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;
}
}
After help from people and posts on this site I was able to get a functioning web app that works. I just need to get the "mailto" functioning and I'm good. I have tried different code from posts I found. The above code is getting "IntentSupport cannot be resolved" and "MIME Type cannot be resolved" Just started trying to learn this stuff. Any feedback would be great. Thanks!

What is the IntentSupport class? I don't see you importing it any where. I have a feeling like it's some third party library that you don't have installed.

Related

can webview start an activity onReceivedError?

I am trying to start an activity (Errorpage) when webview failed to load content.But there is no error during the build, but the app closes, while inernet is off. It was supposed to launh the Errorpage activity.
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import androidx.appcompat.app.AppCompatActivity;
public class smwebview extends AppCompatActivity {
private WebView webview;
private ProgressBar spinner;
String ShowOrHideWebViewInitialUse = "show";
private WebView mWebView; //added for back buton override
public boolean mShouldPause = false;
String fullurl;
private ProgressBar spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_smwebview);
getIntent();
fullurl= getIntent().getStringExtra("full_url");
webview = (WebView) findViewById(R.id.webView_Latest);
webview.setWebViewClient(new CustomWebViewClient());
spinner = (ProgressBar)findViewById(R.id.progressBar2);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setDomStorageEnabled(true);
webview.getSettings().setAppCacheEnabled(true);
webview.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
webview.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);// keep screen on
webview.loadUrl(fullurl);
private class CustomWebViewClient extends WebViewClient {
#Override
public void onPageStarted(WebView webview, String url, Bitmap favicon) {
if (ShowOrHideWebViewInitialUse.equals("show")) {
webview.setVisibility(webview.INVISIBLE);
}
}
#Override
public void onLoadResource(WebView webview, String url) {
super.onLoadResource(webview, url);
if (url.contains("youtube.com")) mShouldPause = true;
}
public void onReceivedError(WebView webview, int errorCode, String description, String failingUrl) {
Intent intent7 = new Intent(smwebview.this,Errorpage.class);
startActivity(intent7);
}
#Override
public void onPageFinished(WebView view, String url) {
ShowOrHideWebViewInitialUse = "hide";
spinner.setVisibility(View.GONE);
view.setVisibility(webview.VISIBLE);
super.onPageFinished(view, url);
}
}
public class WebViewClient extends android.webkit.WebViewClient {
#Override
public void onPageStarted(WebView webview, String url, Bitmap favicon) {
if (ShowOrHideWebViewInitialUse.equals("show")) {
webview.setVisibility(webview.INVISIBLE);
}
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
ShowOrHideWebViewInitialUse = "hide";
spinner.setVisibility(View.GONE);
view.setVisibility(webview.VISIBLE);
super.onPageFinished(view, url);
}
}
#Override
public void onResume()
{
super.onResume();
webview.onResume();
}
#Override
public void onPause() {
super.onPause();
if(mShouldPause){
webview.onPause();
}
mShouldPause = false;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (webview.canGoBack()) {
webview.goBack();
} else {
super.onBackPressed();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}
If anybody have any idea Please help me. Also please comment your suggestions on the code/logic. (I am very new to android programming)
Internet if off. Its different scenario you must add check internet connection before load.
Or onRwleceiveError is different case. When you load wrong url or utl you entered is not working

Webview - Open links in external browser?

Can anyone help me in opening specific link in External browser or other android app?
For Example if URL matches whatsapp:// then it should open link in WhatsApp app and if WhatsApp is not installed then it should open https://play.google.com/store/apps/details?id=com.whatsapp in android browser.
FYI: I am using https://github.com/SurfEdge/flarum-mobile-android to create Web View App for my Forum website.
My Android code looks like:
package com.example.example;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import im.delight.android.webview.AdvancedWebView;
public class MainActivity extends AppCompatActivity implements AdvancedWebView.Listener{
public AdvancedWebView webView;
private ProgressBar mPbar = null;
private static final String url = "https://example.com/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mPbar = (ProgressBar) findViewById(R.id.loader);
webView = (AdvancedWebView) findViewById(R.id.newWeb);
webView.loadUrl(url);
webView.setListener(this, this);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAppCacheEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
webSettings.setAllowFileAccess(true);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
webView.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
AdvancedWebView newWebView = new AdvancedWebView(MainActivity.this);
WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
transport.setWebView(newWebView);
resultMsg.sendToTarget();
return true;
}
});
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
webSettings.setAllowUniversalAccessFromFileURLs(true);
} else {
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
mPbar.setVisibility(View.VISIBLE);
}
public void onPageFinished(WebView view, String url) {
mPbar.setVisibility(View.GONE);
}
#SuppressWarnings("deprecation")
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("whatsapp://")) {
final Uri uri = Uri.parse("market://details?id=com.whatsapp");
final Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
#SuppressWarnings({"NewApi", "deprecation"})
final int newDocumentFlag = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) ? Intent.FLAG_ACTIVITY_NEW_DOCUMENT : Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET;
goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | newDocumentFlag | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
try {
startActivity(goToMarket);
} catch (ActivityNotFoundException ex) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=com.whatsapp")));
}
return true;
}
return super.shouldOverrideUrlLoading(view, url);
}
});
webView.setOnKeyListener( new View.OnKeyListener() {
#Override
public boolean onKey( View v, int keyCode, KeyEvent event ) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
return false;
}
});
webView.setThirdPartyCookiesEnabled(true);
webView.setCookiesEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
webView.onResume();
}
#Override
protected void onPause() {
webView.onPause();
super.onPause();
}
#Override
protected void onDestroy() {
webView.onDestroy();
super.onDestroy();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
webView.onActivityResult(requestCode, resultCode, intent);
}
#Override
public void onBackPressed() {
if (!webView.onBackPressed()) { return; }
super.onBackPressed();
}
#Override
public void onPageStarted(String url, Bitmap favicon) {
}
#Override
public void onPageFinished(String url) {
}
#Override
public void onPageError(int errorCode, String description, String failingUrl) {
}
#Override
public void onDownloadRequested(String url, String suggestedFilename, String mimeType, long contentLength, String contentDisposition, String userAgent) {
}
#Override
public void onExternalPageRequest(String url) {
}
}
Error:
Error:(86, 11) error: cannot find symbol class Uri
Error:(86, 21) error: cannot find symbol variable Uri
Error:(94, 22) error: cannot find symbol class ActivityNotFoundException
Error:(95, 62) error: cannot find symbol variable Uri
P.S: I am not an Android Developer
You should override shouldOverrideUrlLoading, determine if the url has the specified prefix, and then open the Whatsapp listing on Play Store, or if the Play Store is not installed, open it inside browser :
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
mPbar.setVisibility(View.VISIBLE);
}
public void onPageFinished(WebView view, String url) {
mPbar.setVisibility(View.GONE);
}
#SuppressWarnings("deprecation")
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("whatsapp://")) {
// create an intent for Play Store
final Uri uri = Uri.parse("market://details?id=com.whatsapp");
final Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
#SuppressWarnings({"NewApi", "deprecation"})
final int newDocumentFlag = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) ? Intent.FLAG_ACTIVITY_NEW_DOCUMENT : Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET;
goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | newDocumentFlag | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
try {
// open Whatsapp listing in Play Store app
startActivity(goToMarket);
} catch (ActivityNotFoundException ex) {
// open Whatsapp listing in browser
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=com.whatsapp")));
}
return true;
}
return super.shouldOverrideUrlLoading(view, url);
}
});
EDIT
Add this lines to the top of the file to import the necessary classes :
import android.content.ActivityNotFoundException;
import android.net.Uri;

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

How to implement google analytics sdk android v2

I want to implement google analytics sdk android v2
I had
Update AndroidManifest.xml
Create your analytics.xml file
But i don't know hot to implement EasyTracker methods
https://developers.google.com/analytics/devguides/collection/android/v2/#tracking-methods
I don't know where to put it in my code?
Sorry for my english...
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.MailTo;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class MainActivity extends Activity
{
private static final String MIME_TYPE_EMAIL = null;
final Activity activity = this;
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setPluginsEnabled(true);
webView.setWebChromeClient(new WebChromeClient());
String scandinavianCharacters = null;
webView.loadDataWithBaseURL(null, scandinavianCharacters, "text/html", "UTF-8", null);
webView.getSettings().setUserAgentString("Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)");
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
activity.setTitle("Učitavanje...");
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)
{
try {
webView.stopLoading();
} catch (Exception e) {
}
try {
webView.clearView();
} catch (Exception e) {
}
if (webView.canGoBack()) {
webView.goBack();
}
webView.loadUrl("file:///android_asset/greska/greska.html");
super.onReceivedError(webView, errorCode, description, failingUrl);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
});
webView.loadUrl("http://mobile.mywebsite.com/test/");
}
public boolean shouldOverrideUrlLoading(WebView webview, String url)
{
webview.loadUrl(url);
return true;
}
WebView webView;
#Override
public void onBackPressed (){
if (webView.isFocused() && webView.canGoBack()) {
webView.goBack();
}
else {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Zatvorite aplikaciju?")
.setMessage("Da li ste sigurni da želite da izađete?")
.setPositiveButton("Da", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
System.exit(0);
}
})
.setNegativeButton("Ne", null)
.show();
}
}
public boolean shouldOverrideUrlLoading(webView view, String url) {
if(url.startsWith("mailto:")){
MailTo mt = MailTo.parse(url);
Intent i = IntentSupport.newEmailIntent(MainActivity.this, mt.getTo(), mt.getSubject(), mt.getBody(), mt.getCc());
startActivity(i);
view.reload();
return true;
}
else{
view.loadUrl(url);
}
return true;
}
;
public static 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(MIME_TYPE_EMAIL);
return intent;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the currently selected menu XML resource.
android.view.MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
/** Called when a menu item in the menu is clicked. */
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuabout:
Toast.makeText(this, " " +
" " +
"", Toast.LENGTH_LONG).show();
return true;
// Generic catch all for all the other menu resources
default:
if (!item.hasSubMenu())
return true;
break;
}
return false;
}
}
You need to add two additional functions to your activity. You can add them at the bottom of your class at the very end:
#Override
public void onStart() {
super.onStart();
EasyTracker.getInstance().activityStart(this);
}
#Override
public void onStop() {
super.onStop();
EasyTracker.getInstance().activityStop(this);
}
The onStart() function is called after onCreate() so it will not affect the existing implementation. onStop() is called when the activity is stopped so it will catch things like your onBackPressed() action to stop the activity.
You can then choose to add additional tracking anywhere in your Activity using the send() functions such as the following:
EasyTracker.getTracker().sendEvent("Group", "Name", obj, value);
Unrelated by important - you should not be called System.exit(0) in your onBackPressed() function. If this is the only activity in your application, calling finish() will be enough to exit the application.

Android progressBar random crash with nullPointerException, can't understand why

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

Categories

Resources