I am creating an Android project in which I have created a Webview. When the page loads, the progress bar runs. When the page is 100% loaded then the progress bar becomes hidden
But i don't know how to hide it
ProgressBar Code:
#Override
public void onProgressChanged(WebView view,int newProgress)
{
super.onProgressChanged(view, newProgress);
superProgressBar.setProgress(newProgress);
}
All Code:
package com.djaman.musicwala;
import android.app.*;
import android.os.*;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings;
import android.widget.ProgressBar;
import android.widget.ImageView;
import android.webkit.WebChromeClient;
import android.graphics.Bitmap;
import android.support.v7.app.ActionBar;
public class MainActivity extends Activity
{
ProgressBar superProgressBar;
ImageView superImageView;
WebView superWebView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
superWebView = (WebView) findViewById(R.id.webview);
superProgressBar = (ProgressBar) findViewById(R.id.myProcessBar);
superImageView = (ImageView) findViewById(R.id.myImageView);
superProgressBar.setMax(100);
superWebView.loadUrl("http://musicwala.cf");
superWebView.getSettings().setJavaScriptEnabled(true);
superWebView.setWebViewClient(new WebViewClient());
superWebView.setWebChromeClient(new WebChromeClient(){
#Override
public void onProgressChanged(WebView view,int newProgress)
{
super.onProgressChanged(view, newProgress);
superProgressBar.setProgress(newProgress);
}
#Override
public void onReceivedTitle(WebView view,String title)
{
super.onReceivedTitle(view, title);
}
#Override
public void onReceivedIcon(WebView view,Bitmap icon)
{
super.onReceivedIcon(view, icon);
superImageView.setImageBitmap(icon);
}
});
}
private WebView findViewById()
{
// TODO: Implement this method
return null;
}
#Override
public void onBackPressed()
{
// TODO: Implement this method
if(superWebView.canGoBack())
{
superWebView.goBack();
}else{
super.onBackPressed();
}
}
}
you can try this in your "onProgressChanged()".
if (newProgress == 100) {
superProgressBar.setVisibility(View.GONE);
} else {
superProgressBar.setVisibility(View.VISIBLE);
superProgressBar.setProgress(newProgress);
}
Related
I just make a web browser and uploaded on play store but This is not working on my some of friends device (redmi note 8),(redmi 9). when he click on link a blank page will come same as when divice is not connected to internet. my app link - https://play.google.com/store/apps/details?id=com.zimax.forxbrowser .
my java code of first page-
package com.zimax.forxbrowser;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
public class BrowserView extends AppCompatActivity {
private String url;
private ProgressBar progressBar;
SwipeRefreshLayout mySwipeRefreshLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_browser_view2);
final WebView webview = findViewById(R.id.webView);
final EditText urlET = findViewById(R.id.urlET);
final ImageView homeBtn = findViewById(R.id.homeIcon);
url = getIntent().getStringExtra("url");
final String urlData = url.substring(0, 4);
if(!urlData.contains("www")){
url = "www.google.com/search?q="+url;
}
urlET.setText(url);
webview.setWebViewClient(new WebViewClient(){
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
urlET.setText(url);
}
});
//Progress Bar
progressBar = (ProgressBar) findViewById(R.id.progressBar);
webview.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int progress) {
progressBar.setProgress(progress);
if(progress<100 && progressBar.getVisibility() == progressBar.GONE){
progressBar.setVisibility(ProgressBar.VISIBLE);
}
if(progress == 100){
progressBar.setVisibility(ProgressBar.GONE);
}
}
});
//BackButton
webview.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
WebView webView = (WebView) v;
switch(keyCode) {
case KeyEvent.KEYCODE_BACK:
if (webView.canGoBack()) {
webView.goBack();
return true;
}
break;
}
}
return false;
}
});
urlET.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if(actionId == EditorInfo.IME_ACTION_SEARCH){
final String urlTxt = urlET.getText().toString();
if(!urlTxt.isEmpty()){
final String urlData = urlTxt.substring(0, 4);
if(!urlData.contains("www")){
url = "www.google.com/search?q="+url;
}
else {
url = urlTxt;
}
}
}
return false;
}
});
//download any thing
webview.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl(url);
homeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
}
I am expecting to work on all android similar to working on my device.
This is the MainActivity.java code in my web app that give a blank Wordpress page when I open the app.
It happens only for Wordpress.
Other websites work just fine.
They open as they should.
Thank you for your help.
The code is below:
package com.sdvjuridic.sdv;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
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://www.sdvjuridic.wordpress.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){
view.loadUrl(url);
return true;
}
}
#Override
public void onBackPressed(){
if(mywebView.canGoBack()) {
mywebView.goBack();
}
else{
super.onBackPressed();
}
}
}
This code is the fix:
package com.sdvjuridic.sdv;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Bundle;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
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 SSLTolerentWebViewClient());
mywebView.loadUrl("https://www.sdvjuridic.wordpress.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){
view.loadUrl(url);
return true;
}
#Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
handler.proceed(); // Ignore SSL certificate errors
}
}
#Override
public void onBackPressed(){
if(mywebView.canGoBack()) {
mywebView.goBack();
}
else{
super.onBackPressed();
}
}
// SSL Error Tolerant Web View Client
private class SSLTolerentWebViewClient extends WebViewClient {
#Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
handler.proceed(); // Ignore SSL certificate errors
}
}
}
Hey i want to implement google billing into my app but everytime i open the activty where the button is to call my purchase the Console prints
"E/RecyclerView: No adapter attached; skipping layout"
I have a ProductAdapterclass my Information Activity where the button is located.
package com.test.smartbuyapp.Adapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.BillingFlowParams;
import com.android.billingclient.api.SkuDetails;
import com.test.smartbuyapp.InformationActivity;
import com.test.smartbuyapp.Interface.IProductClickListener;
import com.test.smartbuyapp.R;
import java.util.List;
public class MyProductAdapter extends RecyclerView.Adapter<MyProductAdapter.MyViewHolder> {
InformationActivity informationActivity;
List<SkuDetails> skuDetailsList;
BillingClient billingClient;
public MyProductAdapter(InformationActivity informationActivity, List<SkuDetails> skuDetailsList, BillingClient billingClient) {
this.informationActivity = informationActivity;
this.skuDetailsList = skuDetailsList;
this.billingClient = billingClient;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
View itemView = LayoutInflater.from(informationActivity.getBaseContext())
.inflate(R.layout.layout_product_item,viewGroup,false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.txt_product.setText(skuDetailsList.get(position).getTitle());
//Product click
holder.setiProductClickListener(new IProductClickListener() {
#Override
public void onProductClickListerner(View view, int position) {
//Launch Billing flow
BillingFlowParams billingFlowParams = BillingFlowParams.newBuilder()
.setSkuDetails(skuDetailsList.get(position))
.build();
billingClient.launchBillingFlow(informationActivity,billingFlowParams);
}
});
}
#Override
public int getItemCount() {
return skuDetailsList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView txt_product;
IProductClickListener iProductClickListener;
public void setiProductClickListener(IProductClickListener iProductClickListener) {
this.iProductClickListener = iProductClickListener;
}
public MyViewHolder(#NonNull View itemView) {
super(itemView);
txt_product = (TextView) itemView.findViewById(R.id.txt_product_name);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
iProductClickListener.onProductClickListerner(v, getAdapterPosition());
}
}
}
And My Informationactivity
package com.test.smartbuyapp;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.BillingClientStateListener;
import com.android.billingclient.api.BillingResult;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.PurchasesUpdatedListener;
import com.android.billingclient.api.SkuDetails;
import com.android.billingclient.api.SkuDetailsParams;
import com.android.billingclient.api.SkuDetailsResponseListener;
import com.test.smartbuyapp.Adapter.MyProductAdapter;
import java.util.Arrays;
import java.util.List;
public class InformationActivity extends AppCompatActivity implements PurchasesUpdatedListener {
BillingClient billingClient;
Button loadProduct;
RecyclerView recyclerProduct;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_information);
setupBillingClient();
//View
loadProduct = (Button) findViewById(R.id.btn_load_product);
recyclerProduct = (RecyclerView)findViewById(R.id.recycler_product);
recyclerProduct.setLayoutManager(new LinearLayoutManager(this));
recyclerProduct.setHasFixedSize(true);
//Event
loadProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(billingClient.isReady()) {
SkuDetailsParams params = SkuDetailsParams.newBuilder()
.setSkusList(Arrays.asList("adfree"))
.setType(BillingClient.SkuType.INAPP)
.build();
billingClient.querySkuDetailsAsync(params, new SkuDetailsResponseListener() {
#Override
public void onSkuDetailsResponse(BillingResult billingResult, List<SkuDetails> list) {
if(billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK){
loadProductToRecyclerView(list);
}else{
Toast.makeText(InformationActivity.this,"Cannot query product",Toast.LENGTH_SHORT);
}
}
});
}else {
Toast.makeText(InformationActivity.this,"Billing client not Ready",Toast.LENGTH_SHORT);
}
}
});
//////////// Toolbar //////////////////////////////////////////////////////////////
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("Information");
}
private void loadProductToRecyclerView(List<SkuDetails> list) {
MyProductAdapter adapter= new MyProductAdapter(this,list,billingClient);
recyclerProduct.setAdapter(adapter);
}
private void setupBillingClient() {
billingClient = BillingClient.newBuilder(this).setListener(this).enablePendingPurchases().build();
billingClient.startConnection(new BillingClientStateListener() {
#Override
public void onBillingSetupFinished(BillingResult billingResult) {
if(billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK){
Toast.makeText(InformationActivity.this,"Sucessfully Billing Connect",Toast.LENGTH_SHORT);
}else {
Toast.makeText(InformationActivity.this,"Failed to Billing Connect"+billingResult.getResponseCode(),Toast.LENGTH_SHORT);
}
}
#Override
public void onBillingServiceDisconnected() {
Toast.makeText(InformationActivity.this,"You are disconnected from billing",Toast.LENGTH_SHORT);
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
startActivity(new Intent(com.test.smartbuyapp.InformationActivity.this, ListMainActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
return true;
}
return false;
}
public void PrivacyPerform(View view) {
TextView agb = (TextView) findViewById(R.id.AGB);
agb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://sites.google.com/view/smartbuyapp/"));
startActivity(intent);
}
});
}
#Override
public void onPurchasesUpdated(BillingResult billingResult, #Nullable List<Purchase> list) {
//Here if user clicks Buy, we will receive data
Toast.makeText(InformationActivity.this,"Purchase item",Toast.LENGTH_SHORT);
}
}
Im trying to implement a webview inside one of my pages but I am using an "else if" for the fragment. Im getting and error on the line "changeFragment(new CalendarFragment());", saying that it cannot be applied to my Calender Fragment file. Any help solving this would be greatly appreciated.
MainActivity.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.WebViewClient;
import android.widget.Toast;
import com.special.ResideMenu.ResideMenu;
import com.special.ResideMenu.ResideMenuItem;
import com.parse.Parse;
import com.parse.ParseAnalytics;
import com.parse.ParseInstallation;
import com.parse.PushService;
public class MenuActivity extends FragmentActivity implements View.OnClickListener{
private ResideMenu resideMenu;
private MenuActivity mContext;
private ResideMenuItem itemHome;
private ResideMenuItem itemProfile;
private ResideMenuItem itemCalendar;
private ResideMenuItem itemSettings;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mContext = this;
setUpMenu();
changeFragment(new HomeFragment());
Parse.initialize(this, "123", "IHecHh");
PushService.setDefaultPushCallback(this, MenuActivity.class);
}
private void setUpMenu() {
// attach to current activity;
resideMenu = new ResideMenu(this);
resideMenu.setBackground(R.drawable.menu_background);
resideMenu.attachToActivity(this);
resideMenu.setMenuListener(menuListener);
//valid scale factor is between 0.0f and 1.0f. leftmenu'width is 150dip.
resideMenu.setScaleValue(0.6f);
// create menu items;
itemHome = new ResideMenuItem(this, R.drawable.icon_home, "Home");
itemProfile = new ResideMenuItem(this, R.drawable.icon_profile, "Profile");
itemCalendar = new ResideMenuItem(this, R.drawable.icon_calendar, "Calendar");
itemSettings = new ResideMenuItem(this, R.drawable.icon_settings, "Settings");
itemHome.setOnClickListener(this);
itemProfile.setOnClickListener(this);
itemCalendar.setOnClickListener(this);
itemSettings.setOnClickListener(this);
resideMenu.addMenuItem(itemHome, ResideMenu.DIRECTION_LEFT);
resideMenu.addMenuItem(itemProfile, ResideMenu.DIRECTION_LEFT);
resideMenu.addMenuItem(itemCalendar, ResideMenu.DIRECTION_RIGHT);
resideMenu.addMenuItem(itemSettings, ResideMenu.DIRECTION_RIGHT);
// You can disable a direction by setting ->
// resideMenu.setSwipeDirectionDisable(ResideMenu.DIRECTION_RIGHT);
findViewById(R.id.title_bar_left_menu).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
resideMenu.openMenu(ResideMenu.DIRECTION_LEFT);
}
});
findViewById(R.id.title_bar_right_menu).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
resideMenu.openMenu(ResideMenu.DIRECTION_RIGHT);
}
});
}
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
return resideMenu.dispatchTouchEvent(ev);
}
#Override
public void onClick(View view) {
if (view == itemHome){
changeFragment(new HomeFragment());
}else if (view == itemProfile){
changeFragment(new ProfileFragment());
}else if (view == itemCalendar){
changeFragment(new CalendarFragment());
}else if (view == itemSettings){
changeFragment(new SettingsFragment());
}
resideMenu.closeMenu();
}
private ResideMenu.OnMenuListener menuListener = new ResideMenu.OnMenuListener() {
#Override
public void openMenu() {
Toast.makeText(mContext, "Menu is opened!", Toast.LENGTH_SHORT).show();
}
#Override
public void closeMenu() {
Toast.makeText(mContext, "Menu is closed!", Toast.LENGTH_SHORT).show();
}
};
private void changeFragment(Fragment targetFragment){
resideMenu.clearIgnoredViewList();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.main_fragment, targetFragment, "fragment")
.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.commit();
}
// What good method is to access resideMenu?
public ResideMenu getResideMenu(){
return resideMenu;
}
}
CalendarFragment.java
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class CalendarFragment extends Activity implements OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calendar);
WebView wv = (WebView) findViewById(R.id.webView1);
wv.getSettings().setJavaScriptEnabled(true);
wv.loadUrl("http://www.xxxx.com");
wv.setWebViewClient(new WebViewClient());
}
#Override
public void onClick(View v) {
}
private class Callback extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return (true);
}
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
super.onResume();
}
}
your CalendarFragment is not actually a Fragment but an Activity since you extended Activity
public class CalendarFragment extends Activity
but the changeFragment method takes a parameter a Fragment, causing a compile time error,
I'm using the following code to display a webview in my Android app.
package com.company.myapp;
import com.google.android.apps.analytics.GoogleAnalyticsTracker;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class ArticlesActivity extends Activity {
/** Initialize the Google Analytics Tracker */
GoogleAnalyticsTracker tracker;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_PROGRESS);
getWindow().setFeatureInt(Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);
WebView webview = new WebView(this);
setContentView(webview);
setProgressBarVisibility(true);
webview.getSettings().setJavaScriptEnabled(true);
webview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
final Activity activity = this;
tracker = GoogleAnalyticsTracker.getInstance();
// Start the tracker, updating google every 20 seconds
tracker.start((String) getText(R.string.analyticsID), 20, this);
webview.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
activity.setProgress(progress * 100 );
}
});
webview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
}
});
webview.loadUrl("http://www.google.com");
}
#Override
public void onResume() {
tracker.trackPageView("ArticlesActivity");
super.onResume();
}
#Override
protected void onDestroy() {
super.onDestroy();
// Stop the tracker when it is no longer needed.
tracker.stop();
}
}
I would need to enable the back button to step back if history exists instead of just exiting the webview.
I've tried many different code examples such as this but can't get any to work. The app just shuts down when the back button is pressed.
Here's my code with the back button code but it just crashes the app when then back button is pressed:
package com.company.myapp;
import com.google.android.apps.analytics.GoogleAnalyticsTracker;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class ArticlesActivity extends Activity {
WebView webview;
/** Initialize the Google Analytics Tracker */
GoogleAnalyticsTracker tracker;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_PROGRESS);
getWindow().setFeatureInt(Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);
WebView webview = new WebView(this);
setContentView(webview);
setProgressBarVisibility(true);
webview.getSettings().setJavaScriptEnabled(true);
webview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
final Activity activity = this;
tracker = GoogleAnalyticsTracker.getInstance();
// Start the tracker, updating google every 20 seconds
tracker.start((String) getText(R.string.analyticsID), 20, this);
webview.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
activity.setProgress(progress * 100 );
}
});
webview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
}
});
webview.loadUrl("http://www.google.com");
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
webview.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public void onResume() {
tracker.trackPageView("ArticlesActivity");
super.onResume();
}
#Override
protected void onDestroy() {
super.onDestroy();
// Stop the tracker when it is no longer needed.
tracker.stop();
}
}
Could someone help me with a solution?
Got it! Your problem in this line
WebView webview = new WebView(this);
Instead of using your member variable you are creating a variable inside function, and hence your member variable is null inside onKeyDown function.
Just replace it with
webview = new WebView(this);