Ad

How To Call Two Functions In A Button Click In Android?

- 1 answer

I created a button and two function/method in my activity, one method to force quit the application and another to delete the cache directory.

Now, I want to call both the methods when I click on a button, I have canceled exit but I don't know what to do next.

My activity code:

package com.beta.accs;

import android.app.Activity;
import android.content.ComponentName;
import android.os.Bundle;
import android.os.Process;
import android.view.View;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import java.io.File;
import android.content.Context;
import android.widget.Button;

public class MainActivity extends Activity {

    public WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);

        webView = (WebView) findViewById(R.id.WebViewSNCF);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webView.loadUrl("https://www.oui.sncf/services/acces-plus"); //Ton url de page Principal;
        webView.setWebViewClient(new WebViewClient()); //pour rester dans l'aplication meme en cliquant partout a l'ecran.
        webView.getSettings().setBuiltInZoomControls(true);
    }

    public void clickExit(View view) {
        moveTaskToBack(true);

        Process.killProcess(R.id.WebViewSNCF);
        System.exit(1);
    }

    public void clicReturn(View view) {
        if (webView.canGoBack()) {
            webView.goBack();
        }
    }

    public static void deleteCache(Context context) {
        try {
            File dir = context.getCacheDir();
            deleteDir(dir);
        } catch (Exception e) {}
    }

    public static boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
            return dir.delete();
        } else if(dir!= null && dir.isFile()) {
            return dir.delete();
        } else {
            return false;
        }
    }
}

Please show me the way how can I call those both methods from a single button click.

Ad

Answer

Something like this:

Button your_btn = findViewById(R.id.button); // reference to your button ID in your layout xml file
your_btn.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View view) {
         deleteCache(); // delete cache
         clickExit(); // exit
     }
});
Ad
source: stackoverflow.com
Ad