简体   繁体   中英

Android - Executing Asynctask in Activity

I have my login. The user types his username and password in EditText and press onClick login button.

public void onClick(View v) {

    String username = ((EditText) findViewById(R.id.typeUsername)).getText().toString();
    String password = ((EditText) findViewById(R.id.typePassword)).getText().toString();
    Controller handler = new Controller(getBaseContext());


    if (!username.equals("") || !password.equals("")) {
        //new LoginTask().execute(((EditText)findViewById(R.id.typeUsername)).getText().toString(),
         //       ((EditText)findViewById(R.id.typePassword)).getText().toString());
       LoginTask load = new LoginTask(context);
       load.execute();
    } else {
        Toast.makeText(getApplicationContext(), "Please fill in all fields", Toast.LENGTH_SHORT).show();
        return;
    }
}

Now when the login button is clicked. It executes LoginTask in the same class.

In the LoginTask when the login button is clicked a dialog should show, and in the background the user input is checked with the SQL. executeLog is a method in my DatabaseHelper it is a rawQuery to the SQL checking if username and password matches. saveLogin() is another method in my sharedpref class that saves the username and password in sharedPreference.

My issue is how can I execute? LoginTask properly in the Login class? Do i need to pass anything? What should I use in LoginTask instead of getApplicationContext

The correct way to use a Context reference in your AsyncTask is like this:

private static class ExampleTask extends AsyncTask<Void, Void, String> {

    private final WeakReference<Context> contextReference;

    private ExampleTask(Context context) {
        this.contextReference = new WeakReference<Context>(context);
    }

    @Override
    protected String doInBackground(Void... params) {
        final Context context = this.contextReference.get();
        if(context != null) {
            // Inside this if you can safely use the context variable
        }
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

        final Context context = this.contextReference.get();
        if(context != null) {
            // Inside this if you can safely use the context variable
        }
    }
}

What the WeakReference does is it allows the garbage collector to destroy the Activity or Context even though your AsyncTask still has a reference to it and as such prevents the creation of memory leaks. If you want to use the Context inside your AsyncTask you need to call get() on the WeakReference like in the example above and perform a null check. If the Context you get from get() is not null you can safely use it.

Your LoginTask is declared as static class, so you don't have acces to instance of Login . Althrough you are trying to access Intent log member.

LoginTask is declared static and it has not access to the outer environment. So neither Intent log or getApplicationContext() are visible from your AsyncTask . Also notice that your AsyncTask try to access not-intialized class member. Eg Controller handler; in the AsyncTask's scope, is never intialized. When doInBackground will be executed it will cause a NPE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM