简体   繁体   中英

Flag from AsyncTask class doesn't work properly in main class

I've created some lines of code which are supposed to switch to the next activity if connection is set without any exceptions. But if there are some exceptions, it should make "Error." toast and not go to the next activity: Boolean flag in Connection class works well, if the server is off, app will say "Error,". if on, it won't. But same flag in main class ( con.flag ) doesn't work properly, it looks like it is always false . App always switches to the next activity, with making toast or without, depending on server status. What's wrong in my code? I suppose that there's something I don't know about AsyncTask classes' fields initialization. So, here is my code:

public class Connection extends AsyncTask<Void, Void, String> {
    Context mContext;
    public Connection(Context context){
        this.mContext = context;
    }
    static String value;
    boolean flag = false;

    @Override
    protected String doInBackground(Void... arg0) {

        try {
            Jedis jedis = new Jedis("192.168.0.120", 6381);
            String name = jedis.ping();
            value = name;
        } catch (Exception e){
            flag = true;
        }
        return null;
    }
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        if (flag) {
            Toast toast = Toast.makeText(mContext,
                    "Error!", Toast.LENGTH_LONG);
            toast.show();
        }
    }

}
public class MainActivity extends AppCompatActivity {
    Button click;
    Context maincontext = this;
    public void goTo2ndActivity(){
        Intent intent = new Intent(this, Main2Activity.class);
        startActivity(intent);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        click = (Button)findViewById(R.id.button);
        click.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    final Connection con = new Connection(maincontext);
                    con.execute();
                    if (!con.flag){
                        goTo2ndActivity();
                    }
            }
        });
    }
}

Your problem seems to be a race condition between main thread and the asynctask, the problem is in the onClick listener:

    click.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {


                final Connection con = new Connection(maincontext);
                con.execute();
                if (!con.flag){
                    goTo2ndActivity();
                }
        }
    });

so this part

                if (!con.flag){
                    goTo2ndActivity();
                }

must be called from on post execute of your async task, for that pass the activity to the constructor of the async task like this:

update constructor of async task:

public class Connection extends AsyncTask<Void, Void, String> {
    Context mContext;
    MainActivity activity;
    public Connection(Context context,MainActivity activity){
        this.mContext = context;
        this.activity= activity
    }

..........
..........

and on post execute:

protected void onPostExecute(String result) {
    super.onPostExecute(result);
    if (flag) {
        Toast toast = Toast.makeText(mContext,
                "Error!", Toast.LENGTH_LONG);
        toast.show();
    }else{
     //go to next activity
     activity.goTo2ndActivity();
     }
}

now your button click becomes:

    click.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

                //just execute
                final Connection con = new Connection(maincontext,this);
                con.execute();

        }
    });

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