0

Im new to android development.....Since two days i struck with a problem in twitter integration.....According to my knowledge the way i implemented is right.....But I missed something thats the reason Im not getting the out put...At first I will explain the problem....

1.According to my requirement I need to do twitter integration in my application.
2.So whenever i click on tweet button....At first it has to check whether the user is in login state or not.
3.If the user is in login state he has to post the comment. 4.Otherwise it has to show a login page and then it should post the comment. 5.Below the versions of 4 it was working fine but above the version it was not working and showing "NETWORK MAIN THREAD EXCEPTION".
6.for this reason i implemented asynchronous task in code.
7.From there the problem was raised. 8.It was unable to login into twitter I google a lot and didnt found where the error....Im posting my code here can you guys please help me from this....

public class sharetw extends Activity {
// Shared Preferences
private static SharedPreferences mSharedPreferences;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
       setContentView(R.layout.sharetw);
            tweetbtn = (Button) findViewById(R.id.tweet);
    // Shared Preferences
mSharedPreferences = getApplicationContext().getSharedPreferences(
            "MyPref", 0);
tweetbtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            status = twtreview.getText().toString();

            // Check for blank text
            if (isTwitterLoggedInAlready() && status.trim().length() > 0) {
                new updateTwitterStatus().execute(status);
            } else if (status.equals("")) {
                // EditText is empty
                Toast.makeText(getApplicationContext(),
                        "Please enter status message", Toast.LENGTH_SHORT)
                        .show();
            } else {

                new loginToTwitter().execute(); 
        }
    });
/**
     * This if conditions is tested once is redirected from twitter page.
     * Parse the uri to get oAuth Verifier
     * */
    if (!isTwitterLoggedInAlready()) {
        Uri uri = getIntent().getData();
        if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {   // oAuth verifier
            String verifier = uri
                    .getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
try {       
// Get the access token
requestToken = twitter
                        .getOAuthRequestToken(TWITTER_CALLBACK_URL);
accessToken = twitter.getOAuthAccessToken(requestToken,
                        verifier);
// Shared Preferences
Editor e = mSharedPreferences.edit();

                // After getting access token, access token secret
                // store them in application preferences
                e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
                e.putString(PREF_KEY_OAUTH_SECRET,
                        accessToken.getTokenSecret());
                // Store login status - true
                e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
                e.commit(); // save changes
Log.e("Twitter OAuth Token", "> " + accessToken.getToken());
// Getting user details from twitter
                // For now i am getting his name only
                long userID = accessToken.getUserId();
                User user = twitter.showUser(userID);
                username = user.getName();
e.putString("namew", "" + username);
                e.commit();
                // Displaying in xml ui
                twtconect.setText("Twitter" + "(" + username + ")" + "a");} catch (Exception e) {
                // Check log for login errors
                Toast.makeText(getApplicationContext(),
                        "Sorry!login again", Toast.LENGTH_LONG).show();
            }
        }
    }
    if (isTwitterLoggedInAlready()) {
                     new updateTwitterStatus().execute(status);

        Log.v("logged", "in");

    }

}

/**
 * Function to login twitter
 * */
class loginToTwitter extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(sharetw.this);
        pDialog.setMessage("Login to twitter...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting Places JSON
     * */
    protected String doInBackground(String... args) {

        if (!isTwitterLoggedInAlready()) {
            Log.v("login method","df");
            ConfigurationBuilder builder = new ConfigurationBuilder();
            builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
            builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
            twitter4j.conf.Configuration configuration = builder.build();

            TwitterFactory factory = new TwitterFactory(configuration);
            twitter = factory.getInstance();

            try {

                requestToken = twitter
                        .getOAuthRequestToken(TWITTER_CALLBACK_URL);


            } catch (TwitterException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog and show
     * the data in UI Always use runOnUiThread(new Runnable()) to update UI
     * from background thread, otherwise you will get error
     * **/
    protected void onPostExecute(String file_url) {

        pDialog.dismiss();
        Intent i2 = new Intent(Intent.ACTION_VIEW,
                Uri.parse(requestToken.getAuthenticationURL()));

        i2.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        i2.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
        i2.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        startActivity(i2);
        i2.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);



    }
}

/**
 * Function to update status
 * */
class updateTwitterStatus extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(sharetw.this);
        pDialog.setMessage("Updating to twitter...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting Places JSON
     * */
    protected String doInBackground(String... args) {
        Log.d("Tweet Text", "> " + args[0]);
        String status = args[0];


        try {
            ConfigurationBuilder builder = new ConfigurationBuilder();
            builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
            builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);

            // Access Token
            String access_token = mSharedPreferences.getString(
                    PREF_KEY_OAUTH_TOKEN, "");
            // Access Token Secret
            String access_token_secret = mSharedPreferences.getString(
                    PREF_KEY_OAUTH_SECRET, "");

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

            // Update status

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

            Log.d("Status", "> " + response.getText());
        } catch (TwitterException e) {
            // Error in updating status
            Log.d("Twitter Update Error", e.getMessage());
        }
        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog and show
     * the data in UI Always use runOnUiThread(new Runnable()) to update UI
     * from background thread, otherwise you will get error
     * **/
    protected void onPostExecute(String file_url) {

        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(),
                        "Status tweeted successfully", Toast.LENGTH_SHORT)
                        .show();
                // Clearing EditText field
                twtreview.setText("");
            }
        });
    }
}

/**
 * Function to logout from twitter It will just clear the application shared
 * preferences
 * */
public void logoutFromTwitter() {
    AlertDialog.Builder alert = new AlertDialog.Builder(sharetw.this);
    alert.setTitle("Are u sure want to logout?");
    alert.setPositiveButton("YES", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            Editor e = mSharedPreferences.edit();
            e.remove(PREF_KEY_OAUTH_TOKEN);
            e.remove(PREF_KEY_OAUTH_SECRET);
            e.remove(PREF_KEY_TWITTER_LOGIN);
            e.remove(TWITTER_CALLBACK_URL);
            e.remove(TWITTER_CONSUMER_SECRET);
            e.remove(URL_TWITTER_AUTH);
            e.remove(URL_TWITTER_OAUTH_VERIFIER);
            e.remove(username);
            e.remove(TWITTER_CONSUMER_KEY);
            e.remove(URL_TWITTER_OAUTH_TOKEN);
            e.clear();
            e.commit();
            layoutnotconect.setVisibility(View.VISIBLE);
            layoutconect.setVisibility(View.INVISIBLE);
            twtconect.setText("");
            twtconect.setVisibility(View.GONE);
            btnLoginTwitter.setVisibility(View.VISIBLE);
        }
    });

}

/**
 * Check user already logged in your application using twitter Login flag is
 * fetched from Shared Preferences
 * */
private boolean isTwitterLoggedInAlready() {
    // return twitter login status from Shared Preferences
    return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}






}


}
Ramz
  • 658
  • 1
  • 7
  • 19

1 Answers1

0

I integrated socialauth-android sdk to integrate twitter in my application after reading this post Android Twitter Connectivity?

I was also facing the same problem. I found some examples in this sdk which helped to handle tasks asynchronously.

Community
  • 1
  • 1
user1722283
  • 234
  • 3
  • 7