Skip to content
Advertisement

How to save last visited url in android webview? [closed]

So im writing a very simple web-view app that shows certain types of users a web-page that I get from Firebase Realtime Database. Everything works just fine but upon closing an app, user gets sent back to the original “starting point” page. I heard you have to use SharedPreferences to solve a problem but how can I tie it up with firebase so everything would work fine? Attaching the code

public class TargetActivty extends AppCompatActivity {
private WebView webView;
private TextView msgURL;
private FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
private DatabaseReference reference = firebaseDatabase.getReference();
private DatabaseReference childReference = reference.child("url");
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_target);
    webView = findViewById(R.id.webView);
    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webView.setWebViewClient(new WebViewClient());
}
@Override
public void onBackPressed() {
    if (webView.canGoBack()) {
        webView.goBack();
    } else {
        super.onBackPressed();
    }
}
@Override
protected void onStart() {
    super.onStart();
    childReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            String message = dataSnapshot.getValue(String.class);
            webView.loadUrl(message);


        }
        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
        }
    });
}}

Advertisement

Answer

Use this code :

webView.setWebViewClient(new MyWebViewClient());

class MyWebViewClient extends WebViewClient {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {

        view.loadUrl(url);
        return true;

    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);

        //Save the last visited URL to shared preference
        saveUrl(url);
    }


}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement