user2763406
user2763406

Reputation: 11

Back button force closing app

I am creating an tabbed app using webview on all tabs. Each tab goes to a different url where the user can then click on links and it'll show them the link in the app. However, I am having trouble implementing the back button so the user can go back to the previous page. Here is my MainActivity.java:

package com.theprospectordaily;

import java.util.Locale;

import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.view.KeyEvent;
import android.content.Intent;


public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {


    WebView myWebView;
    @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) && myWebView.canGoBack()) {
            myWebView.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);
    }

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the three primary sections of the app. We use a
 * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
 * will keep every loaded fragment in memory. If this becomes too memory
 * intensive, it may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
CollectionPagerAdapter mCollectionPagerAdapter;

/**
 * The {@link android.support.v4.view.ViewPager} that will display the
 * object collection.
 */
ViewPager mViewPager;

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);




// Create an adapter that when requested, will return a fragment
// representing an object in
// the collection.
//
// ViewPager and its adapters use support library fragments, so we must
// use
// getSupportFragmentManager.
mCollectionPagerAdapter = new CollectionPagerAdapter(
    getSupportFragmentManager());

// Set up action bar.
final ActionBar actionBar = getActionBar();


// Specify that we will be displaying tabs in the action bar.
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

// Set up the ViewPager, attaching the adapter and setting up a listener
// for when the
// user swipes between sections.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mCollectionPagerAdapter);
mViewPager
    .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
        // When swiping between different app sections, select
        // the corresponding tab.
        // We can also use ActionBar.Tab#select() to do this if
        // we have a reference to the
        // Tab.
        actionBar.setSelectedNavigationItem(position);
        }
    });

// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mCollectionPagerAdapter.getCount(); i++) {
    // Create a tab with text corresponding to the page title defined by
    // the adapter.
    // Also specify this Activity object, which implements the
    // TabListener interface, as the
    // listener for when this tab is selected.
    actionBar.addTab(actionBar.newTab()
        .setText(mCollectionPagerAdapter.getPageTitle(i))
        .setTabListener(this));
}
}

public void onTabUnselected(ActionBar.Tab tab,
    FragmentTransaction fragmentTransaction) {
}

public void onTabSelected(ActionBar.Tab tab,
    FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}

public void onTabReselected(ActionBar.Tab tab,
    FragmentTransaction fragmentTransaction) {
}


/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the primary sections of the app.
 */
public class CollectionPagerAdapter extends FragmentPagerAdapter {

final int NUM_ITEMS = 5; // number of tabs

public CollectionPagerAdapter(FragmentManager fm) {
    super(fm);
}

@Override
public Fragment getItem(int i) {
    Fragment fragment = new TabFragment();
    Bundle args = new Bundle();
    args.putInt(TabFragment.ARG_OBJECT, i);
    fragment.setArguments(args);
    return fragment;
}

@Override
public int getCount() {
    return NUM_ITEMS;
}

@Override
public CharSequence getPageTitle(int position) {
    String tabLabel = null;
    switch (position) {
    case 0:
    tabLabel = getString(R.string.label1);
    break;
    case 1:
    tabLabel = getString(R.string.label2);
    break;
    case 2:
    tabLabel = getString(R.string.label3);
    break;
    case 3:
    tabLabel = getString(R.string.label4);
    break;
    case 4:
    tabLabel = getString(R.string.label5);
    }

    return tabLabel;
}
}

/**
 * A fragment that launches other parts of the demo application.
 */
public static class TabFragment extends Fragment {

public static final String ARG_OBJECT = "object";

private WebView webView;
private Bundle webViewBundle;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    webViewBundle = new Bundle();
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {

    Bundle args = getArguments();
    int position = args.getInt(ARG_OBJECT);

    int tabLayout = 0;
    switch (position) {
    case 0:
    tabLayout = R.layout.tab1;
    break;
    case 1:
    tabLayout = R.layout.tab2;
    break;
    case 2:
    tabLayout = R.layout.tab3;
    break;
    case 3:
    tabLayout = R.layout.tab4;
    break;
    case 4:
        tabLayout = R.layout.tab5;
    break;
    }

    View rootView = inflater.inflate(tabLayout, container, false);

    webView = (WebView) rootView.findViewById(R.id.webView1);
    if (webView != null) {
    webView.setWebViewClient(new WebViewClient());

    if (webViewBundle == null || webViewBundle.isEmpty()) {
        webView.loadUrl("http://www.theprospectordaily.com/category/news/");
    } else {
        webView.restoreState(webViewBundle);
        webViewBundle.clear();

    }
    }

    webView = (WebView) rootView.findViewById(R.id.webView2);
    if (webView != null) {
    webView.setWebViewClient(new WebViewClient());


    if (webViewBundle == null || webViewBundle.isEmpty()) {
        webView.loadUrl("http://www.theprospectordaily.com/category/entertainment/");
    } else {
        webView.restoreState(webViewBundle);
        webViewBundle.clear();
    }
    }

    webView = (WebView) rootView.findViewById(R.id.webView3);
    if (webView != null) {
    webView.setWebViewClient(new WebViewClient());

    if (webViewBundle == null || webViewBundle.isEmpty()) {
        webView.loadUrl("http://www.theprospectordaily.com/category/sports/");
    } else {
        webView.restoreState(webViewBundle);
        webViewBundle.clear();
    }
    }

    webView = (WebView) rootView.findViewById(R.id.webView4);
    if (webView != null) {
    webView.setWebViewClient(new WebViewClient());

    if (webViewBundle == null || webViewBundle.isEmpty()) {
        webView.loadUrl("http://www.theprospectordaily.com/category/multimedia/");
    } else {
        webView.restoreState(webViewBundle);
        webViewBundle.clear();
    }
    }

    webView = (WebView) rootView.findViewById(R.id.webView5);
    if (webView != null) {
    webView.setWebViewClient(new WebViewClient());

    if (webViewBundle == null || webViewBundle.isEmpty()) {
        webView.loadUrl("http://www.theprospectordaily.com/category/perspectives/");
    } else {
        webView.restoreState(webViewBundle);
        webViewBundle.clear();
    }
    }



    return rootView;
}
}

}

It is my first time learning how to code so I understand it is all over the place and it probably has many errors. I apologize in advance for this!

Upvotes: 0

Views: 1112

Answers (4)

Mohit
Mohit

Reputation: 11314

Why you overriding onKeyDown

@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) && myWebView.canGoBack()) {
            myWebView.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);
    }

You can do this it have it's specific method

@Override
public void onBackPressed()
{       
        if (myWebView.canGoBack()) {
            myWebView.goBack();
            return true;
        }
    super.onBackPressed();      

}

Note: But i will suggest to implement your own back button for webview so that user can use back button for existing from activity

Upvotes: 0

Randy
Randy

Reputation: 4381

What you need to do is override the onBackPressed function of the activity. This will allow you to do whatever you need when the back button is pressed.

@Override
public void onBackPressed() {
    wv.goBack();

    //uncomment this if you want the back button to behave as normal
    //super.onBackPressed();
}

Upvotes: 0

Yuichi Araki
Yuichi Araki

Reputation: 3458

Try overriding onBackPressed in your activity.

@Override
public void onBackPressed() {
  if (mWebView.canGoBack()) {
    mWebView.goBack();
  } else {
    super.onBackPressed();
  }
}

Upvotes: 0

nedaRM
nedaRM

Reputation: 1827

Where are you initializing myWebView? I'm not sure what you're trying to do but from your code I am certain myWebView is null when you call myWebView.canGoBack() it will throw a NullPointerException.

Upvotes: 1

Related Questions