Search code examples
androidandroid-asynctasktwitter4j

How to save a variable in AsyncTask in Android


I am using Twitter 4j to post tweet on single button. If user revoke access of my app then its showing Error in Logcat in do in background i want this error and if this error comes my another hide button of twitter authorize app visible. how do i do that please help. I need that error and if its exists i want to hide show my buttons.

 class updateTwitterStatus extends AsyncTask<String, String, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
    protected Void doInBackground(String... args) {

        String status = args[0];
        try {
            ConfigurationBuilder builder = new ConfigurationBuilder();
            builder.setOAuthConsumerKey(consumerKey);
            builder.setOAuthConsumerSecret(consumerSecret);

            String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");

            String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");


            AccessToken accessToken = new AccessToken(access_token, access_token_secret);
            twitter4j.Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);

            StatusUpdate statusUpdate = new StatusUpdate(status);

            File extStore = Environment.getExternalStoragePublicDirectory("/Twitter/Cache/demo.jpg");
            statusUpdate.setMedia(extStore);

            twitter4j.Status response = twitter.updateStatus(statusUpdate);

        } catch (TwitterException e) {
            Log.d("Failed to post!", e.getMessage());

            error=e; //error is exception
        }
        return null;}

    @Override
    protected void onPostExecute(Void result) {
       pDialog.dismiss();

       Toast.makeText(getContext(), "Posted to Twitter!"+error, Toast.LENGTH_SHORT).show();
    /* i need a variable like int a =10; access it globally, How i do that/*
       } } }

Solution

  • You can save the exception in a variable and check it in onPostExecute() and hide your button ..

        new AsyncTask<Void, Void, Boolean>() {
        Exception error;
    
        @Override
        protected Boolean doInBackground(Void... params) {
            try {
                 // do work
                 return true;
            } catch (Exception e) {
                error = e;
    
                return false;
            } 
        }
    
        @Override
        protected void onPostExecute(Boolean result) {
            if (result) {
                Toast.makeText(ctx, "Success!",
                    Toast.LENGTH_SHORT).show();
             } else {
                if (error != null) {
                    Toast.makeText(getApplicationContext(), error.getMessage(),
                            Toast.LENGTH_SHORT).show();
                    //error occurs hide button here
                }
            }
        }
    }