Question

Exception using trying to tweet after authentication , Twitter Login Error

if (!isTwitterLoggedInAlready()) { Uri uri = getIntent().getData();

        if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
            // oAuth verifier
            Log.d("Inside","inside");
            String verifier = uri
                    .getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);

            try {
                // Get the access token
                AccessToken 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());

                // For now i am getting his name only
                long userID = accessToken.getUserId();
                User user = twitter.showUser(userID);
                String username = user.getName();
                Log.d("usrnm",username);
                // Displaying in xml ui

            } catch (Exception e) {
                // Check log for login errors
                Log.e("Twitter Login Error", "> " + e.getMessage());
            }
        }




private void loginToTwitter() {
        Log.d("user",""+isTwitterLoggedInAlready());
        // Check if already logged in
        if (!isTwitterLoggedInAlready()) {
            ConfigurationBuilder builder = new ConfigurationBuilder();
            builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
            builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
            Configuration configuration = builder.build();

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

            try {
                requestToken = twitter
                        .getOAuthRequestToken(TWITTER_CALLBACK_URL);
                this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
                        .parse(requestToken.getAuthenticationURL())));
            } catch (TwitterException e) {
                e.printStackTrace();
            } 
        } else {
            // user already logged into twitter    
            new updateTwitterStatus().execute("Hello");

        }
    }

stack trace

04-12 11:21:52.479: E/Twitter Login Error(1065): > null
Was it helpful?

Solution

This solution is for uploading an image to Twitter via the TwitPic API. You will need to register your account in their Developer Section

The solution I employ can be thought of to be a two step solution.

First, when the user clicks the post button, I first grab the Image and upload to TwitPic. From there, I grab the URL that is returned by TwitPic (String url = upload.upload(finalFile);).

In step two of this code, in a String instance (String finalStatusWithURL), I grab the content of an EditText and then append the URL from step 1 to it. With this done, the post is finally posted to Twitter.

Configuration conf = new ConfigurationBuilder()
.setOAuthConsumerKey(TWITTER_CONSUMER_KEY)
.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET)
.setOAuthAccessToken(twit_access_token)
.setOAuthAccessTokenSecret(twit_access_token_secret)
.setMediaProviderAPIKey(TWIT_PIC_API)
.build();

// SET THE FILE PATH (THIS IS UPDATED! NOTICE THE CHANGES MADE!!)
Uri tempUri = getImageUri(getApplicationContext(), bmpFinal);
File finalFile = new File(getRealPathFromURI(tempUri));

// THIS IS IMPORTANT. TWITPIC NEEDS THE ACTUAL / ABSOLUTE PATH OF THE IMAGE. JUST THE URI DOES NOT WORK!!!!

ImageUpload upload = new ImageUploadFactory(conf).getInstance(MediaProvider.TWITPIC);

String url = upload.upload(finalFile);
Log.e("TWITTER URL RESPONSE", url);

// END OF FIRST STEP:

// SECOND STEP IS TO UPLOAD TO TWITTER

ConfigurationBuilder builder = new ConfigurationBuilder();

builder.setOAuthConsumerKey(YOUR_TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(YOUR_TWITTER_CONSUMER_SECRET);

AccessToken accessToken = new AccessToken(your_twit_access_token, your_twit_access_token_secret);
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);

String finalStatusWithURL = null;

if (finalStatusMessage.trim().length() > 0) {

    finalStatusMessage = editStatusUpdate.getText().toString();
    finalStatusWithURL = finalStatusMessage + ":\n " + url;

} else {
    finalStatusWithURL = url;
}

twitter4j.Status response = twitter.updateStatus(finalStatusWithURL);
Log.e("TWITTER RESPONSE", response.getText());

This is a method to get the real path of the image you want to upload:

// HELPER METHOD TO GET REAL PATH FOR THE SELECTED IMAGE
public String getRealPathFromURI(Uri uri) {
    Cursor cursor = getContentResolver().query(uri, null, null, null, null); 
    cursor.moveToFirst(); 
    int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); 
    return cursor.getString(idx); 
}

public Uri getImageUri(Context inContext, Bitmap inImage) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
    return Uri.parse(path);
}

UPDATE:

Do this before you attempt to upload:

Bitmap bmpFinal = getBitmapFromURL("http://www.cosmopolitanclublahore.com/wp-content/uploads/2011/06/mexicanfoodrestaurant.jpg");

And the method that return a Bitmap:

// THE METHOD TO DOWNLOAD THE IMAGE INTO A BITMAP
public Bitmap getBitmapFromURL(String strURL) {
    try {
        URL url = new URL(strURL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

You may need to adapt a few things. My code uses images selected by the user from the Gallery or an image he captured with the Camera. You need to upload an image taken off the Internet. The mileage may vary and the code may need to be tweaked.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top