Milos Cuculovic
Milos Cuculovic

Reputation: 20223

AsyncTask is not working properly in android 4.0

I have this async Task on android 2.3.5

    class InternetConnexionErrorAsync extends AsyncTask<String, String, String> 
{
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mdpiImageView.setClickable(false);
        journalsImageView.setClickable(false);
        accountImageView.setClickable(false);
        Toast.makeText(getBaseContext(),errorMessage , Toast.LENGTH_LONG).show();
    }

    @Override
    protected String doInBackground(String... aurl) {   
        try {
            Thread.sleep(3450);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    return null;
    }

    @Override
    protected void onPostExecute(String unused) 
    {
        finish();
    }
}

Everything is working well.

When I try this in Android 4.0, I am newer accessint the onPostExecute.

Could you please help me. No error message, only that the onPostExecute is newer reached.

Upvotes: 1

Views: 1881

Answers (3)

Sara
Sara

Reputation: 1874

I found the solution here

Instead of using :

task.execute();

use :

task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null);

Upvotes: 0

Milos Cuculovic
Milos Cuculovic

Reputation: 20223

The solution I adopted, after the suggestion of @Davek804 is that I replace the AsyncTask with a delayed runable like this:

private Runnable mMyRunnable = new Runnable()
    {
        public void run()
        {
            finish();
        }
     };


Toast.makeText(getBaseContext(),errorMessage , Toast.LENGTH_LONG).show();
            Handler myHandler = new Handler();
            myHandler.postDelayed(mMyRunnable, 3450);

So the effect will be the same.

Upvotes: 1

Davek804
Davek804

Reputation: 2804

Whatever you need to update on the UI you need to do in onPostExecute.

The code below, take a look at onPostExecute - specifically the activity.xx() methods send updates to the main activity that do things on the UI.

For example:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import library.DatabaseHandler;
import library.JSONParser;
import library.UserFunctions;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import com.actionbarsherlock.R;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class LoginTask extends AsyncTask<String, Void, Integer> {

    private ProgressDialog progressDialog;
    private Polling activity;
    private int id = -1;
    private JSONParser jsonParser;
    private static String loginURL = "http://davidjkelley.net/android_api/";
    private static String registerURL = "http://davidjkelley.net/android_api/";
    private static String KEY_SUCCESS = "success";
    private static String KEY_ERROR = "error";
    private static String KEY_ERROR_MSG = "error_msg";
    private static String KEY_UID = "uid";
    private static String KEY_NAME = "name";
    private static String KEY_EMAIL = "email";
    private static String KEY_CREATED_AT = "created_at";
    private int responseCode = 0;

    public LoginTask(Polling activity, ProgressDialog progressDialog)
    {
        this.activity = activity;
        this.progressDialog = progressDialog;
    }

    @Override
    protected void onPreExecute()
    {
        progressDialog.show();
    }

    protected Integer doInBackground(String... arg0) {
        EditText userName = (EditText)activity.findViewById(R.id.emailEditText);
        EditText passwordEdit = (EditText)activity.findViewById(R.id.passEditText);
        String email = userName.getText().toString();
        String password = passwordEdit.getText().toString();
        UserFunctions userFunction = new UserFunctions();
        JSONObject json = userFunction.loginUser(email, password);

        // check for login response
        try {
            if (json.getString(KEY_SUCCESS) != null) {
                String res = json.getString(KEY_SUCCESS);

                if(Integer.parseInt(res) == 1){
                    //user successfully logged in
                    // Store user details in SQLite Database
                    DatabaseHandler db = new DatabaseHandler(activity.getApplicationContext());
                    JSONObject json_user = json.getJSONObject("user");
                    //Log.v("name", json_user.getString(KEY_NAME));
                    // Clear all previous data in database
                    userFunction.logoutUser(activity.getApplicationContext());
                    db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), 
                            json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));                        

                    responseCode = 1;
                    // Close Login Screen
                    //finish();

                }else{
                    responseCode = 0;
                    // Error in login
                }
            }

        } catch (NullPointerException e) {
            e.printStackTrace();

        }
        catch (JSONException e) {
            e.printStackTrace();
        }

        return responseCode;
    }

    @Override
    protected void onPostExecute(Integer responseCode)
    {
        EditText userName = (EditText)activity.findViewById(R.id.emailEditText);
        EditText passwordEdit = (EditText)activity.findViewById(R.id.passEditText);

        if (responseCode == 1) {
            progressDialog.dismiss();
            activity.loginReport(responseCode);
            userName.setText("");
            passwordEdit.setText("");
            //shared prefences, store name

        }
        if (responseCode == 0) {
            progressDialog.dismiss();
            activity.loginReport(responseCode);

        }
        //if(responseCode == 202)
            //activity.login(id);
        //else
            //activity.showLoginError("");

    }
}

Here's the main activity, you can see what loginReport does:

public class Polling extends SherlockFragmentActivity {
    private ViewPager mViewPager;
    private TabsAdapter mTabsAdapter;
    private final static String TAG = "21st Polling:";
    private Button loginButton;
    private Button registerButton;
    private CheckBox remember;
    SharedPreferences sharedPreferences;
    Toast toast;
    ActionBar bar;
    //DatabaseHandler ;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.v(TAG, "onCreate");
        mViewPager = new ViewPager(this);
        mViewPager.setId(R.id.pager);
        setContentView(mViewPager);
        bar = getSupportActionBar();
        bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        bar.setDisplayShowTitleEnabled(false);
        bar.setDisplayShowHomeEnabled(false);
        mTabsAdapter = new TabsAdapter(this, mViewPager);
        mTabsAdapter.addTab(bar.newTab().setText(R.string.login),
                LoginFragment.class, null);
        mTabsAdapter.addTab(bar.newTab().setText(R.string.economics),
                EconFragment.class, null);
        mTabsAdapter.addTab(bar.newTab().setText(R.string.elections),
                ElectionsFragment.class, null);
        mTabsAdapter.addTab(bar.newTab().setText(R.string.politics),
                PoliticsFragment.class, null);
        mTabsAdapter.addTab(bar.newTab().setText(R.string.science),
                ScienceFragment.class, null);
        mTabsAdapter.addTab(bar.newTab().setText(R.string.finance),
                FinanceFragment.class, null);
        mTabsAdapter.addTab(bar.newTab().setText(R.string.religion),
                ReligionFragment.class, null);
        mTabsAdapter.addTab(bar.newTab().setText(R.string.military),
                MilitaryFragment.class, null);
        mTabsAdapter.addTab(bar.newTab().setText(R.string.international),
                InternationalFragment.class, null); 
    }

    public void loginReport(int responseCode) {
        DatabaseHandler db = new DatabaseHandler(getApplicationContext());
        UserFunctions userFunctions = new UserFunctions();
        Context context = getApplicationContext();
        //login succeeded, sent when LoginTask doInBg sends a 1 to onPostExecute
        if (responseCode == 1) {
            loginButton = (Button)findViewById(R.id.loginButton);
            loginButton.setText("Log Out");
            int duration = Toast.LENGTH_LONG;
            Toast toast = Toast.makeText(context, "Logged in.", duration);
            toast.show();
            bar.getTabAt(0).setText(db.getUserDetails().get(db.KEY_EMAIL));
            //Log.v(TAG, db.getUserDetails().toString());
        }
        //login failed, sent when LoginTask doInBg sends a 0 to onPostExecute
        if (responseCode == 0) {
            int duration = Toast.LENGTH_LONG;
            Toast toast = Toast.makeText(context, "Incorrect username/password", duration);
            toast.show();
        }
        if (responseCode == 2) {
            //logout button clicked, listened from within LoginFragment
            //remove user from active sql db here rather than LoginFragment?!
            bar.getTabAt(0).setText(R.string.login);
            int duration = Toast.LENGTH_SHORT;
            Toast toast = Toast.makeText(context, "Logged out", duration);
            toast.show();
            userFunctions.logoutUser(context);
        }
    }

Upvotes: 1

Related Questions