0

I am A Beginner in android development, actually I have a fragment with webview. My issue is when I am in fragment and click back button it is not going back to previous web page instead it is going back to previous fragment. so please help me in fixing this.

Here is my Main Activity Code :

public class MainActivity extends AbsRuntimePermission implements NavigationView.OnNavigationItemSelectedListener {
    //, GoogleApiClient.OnConnectionFailedListener {

    private static final int REQUEST_PERMISSION = 10;
    private Toolbar toolBar;
    private NavigationView navDrawer;
    private DrawerLayout drawerLayout;
    private ActionBarDrawerToggle drawerToggle;
    private FirebaseAuth.AuthStateListener authListener;
    private FirebaseAuth auth;
    private View btnLogOut;
    private int selectedItem;
    private FirebaseDatabase mFirebaseDatabase;
    private DatabaseReference myRef;
    //  private GoogleApiClient googleApiClient;
    private FloatingActionButton fab;
    private CoordinatorLayout coordinatorLayout;
    private HomeFragment homeFragment=new HomeFragment();

    final String TAG = this.getClass().getName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
        auth = FirebaseAuth.getInstance();
        final FirebaseUser user = auth.getCurrentUser();
        String userID = user.getUid();
        // Check if no view has focus:
        View view = this.getCurrentFocus();
        if (view != null) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
        fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, Contact_FAB.class);
                startActivity(intent);
            }
        });
        FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
        tx.replace(R.id.main_content, homeFragment);
        tx.commit();
        final WebView webView = (WebView) findViewById(R.id.WV);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient() {
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
            }

            public void onPageFinished(WebView view, String url) {
                // do your stuff here}
                @Override
                public void onReceivedError (WebView view,int errorCode, String description, String
                failingUrl){
                    super.onReceivedError(view, errorCode, description, failingUrl);
                }
            });

    webView.loadUrl("https://google.co.in");

            requestAppPermissions(new String[] {
                Manifest.permission.READ_CONTACTS,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
            },
            R.string.msg,REQUEST_PERMISSION);

            toolBar =(Toolbar)

            findViewById(R.id.app_bar);

            setSupportActionBar(toolBar);

            // If a notification message is tapped, any data accompanying the notification
            // message is available in the intent extras. In this project the launcher
            // intent is fired when the notification is tapped, so any accompanying data would
            // be handled here. If you want a different intent fired, set the click_action
            // field of the notification message to the desired intent. The launcher intent
            // is used when no click_action is specified.
            //
            // Handle possible data accompanying notification message.
    if(

            getIntent().

            getExtras() !=null)

            {
                for (String key : getIntent().getExtras().keySet()) {
                    String value = getIntent().getExtras().getString(key);
                    if (key.equals("AnotherActivity") && value.equals("True")) {
                        Intent intent = new Intent(this, AnotherActivity.class);
                        intent.putExtra("value", value);
                        startActivity(intent);
                        finish();
                    }

                }
            }

            // subscribeToPushService();

            drawerLayout =(DrawerLayout)

            findViewById(R.id.drawer_layout);

            navDrawer =(NavigationView)

            findViewById(R.id.menu_drawer);
    navDrawer.setNavigationItemSelectedListener(this);
            drawerToggle =new

            ActionBarDrawerToggle(this,drawerLayout, toolBar, R.string.drawer_open, R.string.drawer_close);
    drawerLayout.setDrawerListener(drawerToggle);
    drawerToggle.syncState();
            selectedItem =savedInstanceState ==null?R.id.nav_item_1 :savedInstanceState.getInt("selectedItem");

        }


        @Override
        public boolean onNavigationItemSelected (MenuItem menuItem){
            menuItem.setChecked(true);
            selectedItem = menuItem.getItemId();
            Fragment fragment = null;
            switch (selectedItem) {
                case R.id.nav_item_1:
                    fragment = new HomeFragment();
                    break;
                case R.id.nav_item_2:
                    fragment = new MicrosoftDskFragment();
                    break;
                case R.id.nav_item_3:
                    fragment = new GoogleDskFragment();
                    break;
                case R.id.nav_item_4:
                    fragment = new AppleDskFragment();
                    break;
                case R.id.nav_item_5:
                    fragment = new OthersDskFragment();
                    break;
                case R.id.nav_item_6:
                    fragment = new MobiSpecsFragment();
                    break;
                case R.id.nav_item_8:
                    Intent intent = new Intent(MainActivity.this, About.class);
                    startActivity(intent);
                    break;
                default:
                    break;
            }

            if (!DetectConnection.checkInternetConnection(MainActivity.this)) {
                Toast.makeText(MainActivity.this, "Plz check your network connectivity", Toast.LENGTH_SHORT).show();
            } else {

                if (fragment != null) {

                    FragmentManager fragmentManager = getSupportFragmentManager();
                    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                    fragmentTransaction.replace(R.id.main_content, fragment);
                    fragmentTransaction.addToBackStack(null);
                    fragmentTransaction.commit();
                }
            }

            drawerLayout.closeDrawer(GravityCompat.START);
            return true;
        }

        boolean twice = false;

        @Override
        public void onBackPressed () {
            DrawerLayout layout = (DrawerLayout) findViewById(R.id.drawer_layout);

            if (layout.isDrawerOpen(GravityCompat.START)) {
                layout.closeDrawer(GravityCompat.START);
            } else {
                if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
                    getSupportFragmentManager().popBackStack();
                } else {
                    Log.d(TAG, "click");

                    if (twice == true) {
                        Intent intent = new Intent(Intent.ACTION_MAIN);
                        intent.addCategory(Intent.CATEGORY_HOME);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                        finish();
                        System.exit(0);
                    }
                    twice = true;
                    Log.d(TAG, "twice: " + twice);

                    //super.onBackPressed();
                    Toast.makeText(MainActivity.this, "Please Press Again To Exit", Toast.LENGTH_SHORT).show();

                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            twice = false;
                            Log.d(TAG, "twice: " + twice);
                        }
                    }, 3000);

                }
            }
        }

        @Override
        public boolean onKeyDown ( int keyCode, KeyEvent event){
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                switch (keyCode) {
                    case KeyEvent.KEYCODE_BACK:
                        homeFragment.OnKeyDown(keyCode);
                        return true;
                }
            }
            return super.onKeyDown(keyCode, event);
        }


        @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 super.onCreateOptionsMenu(menu);
        }

        @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.profile) {
                Intent intent = new Intent(MainActivity.this, Profile.class);
                startActivity(intent);
                return true;
            }


            return super.onOptionsItemSelected(item);
        }


        @Override
        public void onSaveInstanceState (Bundle outState, PersistableBundle outPersistentState){
            super.onSaveInstanceState(outState, outPersistentState);

            outState.putInt("selectedItem", selectedItem);
        }

        @Override
        public void onPermissionsGranted ( int requestCode){
            //Do anything when permisson granted
            //   Toast.makeText(getApplicationContext(), "Permission granted", Toast.LENGTH_LONG).show();
        }


/*    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

*/

    }
}

And Here Is My Home Fragment Code :

@SuppressWarnings("ALL")

public class HomeFragment extends Fragment {

WebView webView;
SwipeRefreshLayout swipeView;

public HomeFragment() {
    // Required empty public constructor
}

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

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_home, container, false);
    swipeView = (SwipeRefreshLayout) rootView.findViewById(R.id.container);
    webView = (WebView) rootView.findViewById(R.id.webView);


    webView.getSettings().setJavaScriptEnabled(true);
    // Inflate the layout for this fragment
    webView.loadUrl("https://google.co.in");

    webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            webView.stopLoading();
            webView.clearView();
            Intent intent = new Intent(getActivity(), ErrorActivity.class);
            startActivity(intent);
            swipeView.setEnabled(false);
            super.onReceivedError(view, errorCode, description, failingUrl);

        }

        public void onPageFinished(WebView view, String url) {
            // do your stuff here
            swipeView.setRefreshing(false);

        }

    });


    swipeView.setColorScheme(android.R.color.holo_blue_dark, android.R.color.holo_blue_light);
    swipeView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

        @Override
        public void onRefresh() {
            swipeView.setRefreshing(true);

            (new Handler()).postDelayed(new Runnable() {
                @Override
                public void run() {
                    webView.loadUrl("javascript:window.location.reload( true )");

                }
            }, 2000);
        }
    });
    return rootView;
}
    @Override
    public void onAttach (Activity activity){
        super.onAttach(activity);
    }

    @Override
    public void onDetach () {
        super.onDetach();
    }

  public void OnKeyDown(int keyCode) {
    if (webView != null) {
        if (webView.canGoBack()) {
            webView.goBack();

        } else {
            getActivity().onBackPressed();
        }
    }
}
}
Sharath kumar
  • 4,064
  • 1
  • 14
  • 20
  • Try to add something like webView.canGoBack() in onBackPressed() Ref : https://stackoverflow.com/questions/42749269/back-button-in-android-webview-within-a-fragment – VVB Oct 13 '17 at 10:10

2 Answers2

0

In your onNavigationItemSelected when the FragmentManager replaces the Fragment, don't add it to the backstack:

FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                    fragmentTransaction.replace(R.id.main_content, fragment);
                    fragmentTransaction.commit();

If you add it to the backstack, that means you add that Fragment to the history stack of the Activity, action which is reverted when you press the back button. So every time you add a new Fragment, the stack will be like this: [fragment1][fragment2][fragment3], and if you press the back button, it will remove the last added action, so removing the [fragment3] will show you the [fragment2].

Hope this helps.

camilocons
  • 31
  • 2
0

Create a method in your fragment like to perform action when keys are pressed

public void OnKeyDown(int keyCode){
   if (mWebView.canGoBack()) {
       mWebView.goBack();
   } else {
       getActivity().onBackPressed();
   }
}

And in your corresponding activity override keyDown method and handle the key press

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (event.getAction() == KeyEvent.ACTION_DOWN) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                yourFagmentObject.OnKeyDown(keyCode);
                return true;
        }
    }
    return super.onKeyDown(keyCode, event);
}

Remove the webView.setOnKeyListener(new View.OnKeyListener() from the webViewFragment.

Sharath kumar
  • 4,064
  • 1
  • 14
  • 20