EzDevInfo.com

twitter4j

Twitter4J is an open-sourced, mavenized and Google App Engine safe Java library for the Twitter API which is released under the Apache License 2.0. Twitter4J - A Java library for the Twitter API

Retrieve the user profile image from twitter

I am using the Twitter4J API in Java to retrieve the profile image for a Twitter user whose logged in. The command is something like :

twitter.getProfileImage(twitter.getScreenName(), Imagesize);

What is the image size? How can I display the ProfileImage object in a label for example?


Source: (StackOverflow)

twitter application only authentication java android with twitter4j

I'm trying to get a user timeline from twitter with oauth2 (for application-only authentication) but the result is always null. I don't have experience with OAUTH , and I have looked to a couple tutorials and examples, but with no luck so far. I need to retreive a specific users timeline(in this example Twitter) without the user needing to login.

I had an application that used twitter API 1 and I tried to adapt my existing code to the new API 1.1 with oauth2 for application-only auth. So the code should work except it does'nt get anything back from Twitter. If I do get a result back then it should work again.

the connection with Twitter is made in the function twitterconnect underneath the asyncop.

here is my code:

    public class TwitterActivity extends Activity {

private ConfigurationBuilder builder;

// twitter consumer key and secret
static String TWITTER_CONSUMER_KEY = "**************";
static String TWITTER_CONSUMER_SECRET = "*************";

// twitter acces token and accestokensecret
static String TWITTER_ACCES_TOKEN = "************";
static String TWITTER_ACCES_TOKEN_SECRET = "************";

ArrayList<Tweet> tweets = new ArrayList<Tweet>();

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.twitter);

    new AsyncOp().execute("test");

}

 //Async class... 
  public class AsyncOp extends AsyncTask<String, Void,List<twitter4j.Status>> {

  protected List<twitter4j.Status> doInBackground(String... urls) {

  //auth with twitter  
      List<twitter4j.Status> statuses = null;
        try {
            Twitter twitter=twitterConnect();

            statuses = twitter.getUserTimeline("Twitter");

            return statuses;
        } catch (Exception ex) {

            Log.d("Main.displayTimeline", "" + ex.getMessage());
        }
        return statuses;
  }


  protected void onPostExecute(List<twitter4j.Status> statuses) {

  try {

  String TWITTER="EEE MMM dd HH:mm:ss ZZZZZ yyyy"; SimpleDateFormat sf=new
  SimpleDateFormat(TWITTER, Locale.ENGLISH); sf.setLenient(true);

  for(int i=0;i<statuses.size();i++){

  twitter4j.Status stat = statuses.get(i); 
  User user=stat.getUser(); 
  Date datePosted=stat.getCreatedAt();
  String text=stat.getText();
  String name=user.getName();
  String profile_image_url=user.getProfileImageURL();
  Tweet t =new Tweet(datePosted,text,name,profile_image_url,twitterHumanFriendlyDate(datePosted));

  tweets.add(t);
  // logcat info
  Log.i("date",datePosted.toString());
  Log.i("text",text);
  Log.i("user",name);
  Log.i("userprofilepic",profile_image_url); 
  Log.i("timeofpost",twitterHumanFriendlyDate(datePosted));
  } 

  ListView listView = (ListView) findViewById(R.id.ListViewId);
  listView.setAdapter(new UserItemAdapter(TwitterActivity.this,
  R.layout.listitem, tweets)); 
  ProgressBar bar=(ProgressBar) findViewById(R.id.progressBar1); 
  bar.setVisibility(View.GONE); 
  } catch
  (Exception e) { e.printStackTrace(); } }

 }

public class UserItemAdapter extends ArrayAdapter<Tweet> {
    private ArrayList<Tweet> tweets;

    public UserItemAdapter(Context context, int textViewResourceId,
            ArrayList<Tweet> tweets) {
        super(context, textViewResourceId, tweets);
        this.tweets = tweets;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        if (v == null) {
            LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.listitem, null);
        }

        Tweet tweet = tweets.get(position);
        if (tweet != null) {
            TextView username = (TextView) v.findViewById(R.id.username);
            TextView message = (TextView) v.findViewById(R.id.message);
            ImageView image = (ImageView) v.findViewById(R.id.avatar);
            TextView date = (TextView) v.findViewById(R.id.date);
            if (username != null) {
                username.setText(tweet.username);
            }

            if (message != null) {
                message.setText(tweet.message);
            }

            if (image != null) {
                image.setImageBitmap(getBitmap(tweet.image_url));
            }

            if (date != null) {
                date.setText(tweet.hfdate);

            }
        }
        return v;
    }
}

public Bitmap getBitmap(String bitmapUrl) {
    try {
        URL url = new URL(bitmapUrl);
        return BitmapFactory.decodeStream(url.openConnection()
                .getInputStream());
    } catch (Exception ex) {
        return null;
    }
}


// build twitter

public Twitter twitterConnect() throws Exception
{

    // setup
    builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY).setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
    OAuth2Token token = new TwitterFactory(builder.build()).getInstance().getOAuth2Token();


 // exercise & verify
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setUseSSL(true);
    cb.setApplicationOnlyAuthEnabled(true);

    Twitter twitter = new TwitterFactory(cb.build()).getInstance();

    twitter.setOAuthConsumer(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET);
    twitter.setOAuth2Token(token);

    return twitter;
}

public String twitterHumanFriendlyDate(Date dateCreated) {
    // parse Twitter date
    SimpleDateFormat dateFormat = new SimpleDateFormat(
            "EEE MMM dd HH:mm:ss ZZZZZ yyyy", Locale.ENGLISH);
    dateFormat.setLenient(false);
    Date created = dateCreated;

    // today
    Date today = new Date();

    // how much time since (ms)
    Long duration = today.getTime() - created.getTime();

    long second = 1000;
    long minute = second * 60;
    long hour = minute * 60;
    long day = hour * 24;

    if (duration < second * 7) {
        return "right now";
    }

    if (duration < minute) {
        int n = (int) Math.floor(duration / second);
        return n + " seconds ago";
    }

    if (duration < minute * 2) {
        return "about 1 minute ago";
    }

    if (duration < hour) {
        int n = (int) Math.floor(duration / minute);
        return n + " minutes ago";
    }

    if (duration < hour * 2) {
        return "about 1 hour ago";
    }

    if (duration < day) {
        int n = (int) Math.floor(duration / hour);
        return n + " hours ago";
    }
    if (duration > day && duration < day * 2) {
        return "yesterday";
    }

    if (duration < day * 365) {
        int n = (int) Math.floor(duration / day);
        return n + " days ago";
    } else {
        return "over a year ago";
    }
}

}

Is my problem wit the oauth method? or maybe wit the getusertimeline? If anyone has some example code or tutorial for oauth2 with twitter4j , It would be appreciated


Source: (StackOverflow)

Advertisements

twitter not working with twitter4j in android

I am using twitter4j to integrate twitter in android. This is my code to for twitter. I am creating separate class for twitter.

I looked at similar questions to this but nothing works for me. Question and some other questions.

Twitter class

public class OBLTwitter {

private static final String TAG = "OBLTwitter";
private Activity activity;

// Twitter constants
private static final String TWITTER_CONSUMER_KEY = "KEY";
private static final String TWITTER_CONSUMER_SECRET = "SECRET";
public static final String TWITTER_CALLBACK_URL = "app://ridesharebuddy";

// Twitter variables
private static Twitter twitter;
private static RequestToken requestToken;
public static boolean userDeniedToContinue;

    public OBLTwitter(Activity activity) {

        Log.d(TAG, "Parameterized constructor called.");

        this.activity = activity;
        userDeniedToContinue = false;
    }


    // Login to twitter
    public void loginToTwitter() {

        Log.e(TAG, "Logging in to twitter.");

        if(!isNetworkAvailable(this.activity))
        {
            Log.e(TAG, "Interent connection not available");
        }

        // Set up Twitter object
        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();

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {

                    if(twitter == null)
                    {
                        Log.e(TAG, "twitter is null");
                    }
                    Log.e("called", "called run method");
                    // Get RequestToken and call authentication URL to show
                    // twitter page
                    requestToken = twitter
                            .getOAuthRequestToken(TWITTER_CALLBACK_URL);

                    Log.e(TAG, "getting request token");

                    Log.e("oAuth token :", requestToken.getToken());
                    Log.e("oAUth secret:", requestToken.getTokenSecret());
                    Log.e("oAuth URL: ", requestToken.getAuthenticationURL());

                     activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri
                     .parse(requestToken.getAuthenticationURL())));

                } catch (TwitterException te) {

                    Log.e(TAG, "Twitter exception, Login error.");
                    te.printStackTrace();                       

                    Log.e(TAG, "Error code : " + te.getErrorCode());
                    Log.e(TAG, "Error message : " + te.getErrorMessage());
                    Log.e(TAG, "Status code : " + te.getStatusCode());
                    Log.e(TAG, "Access level : " + te.getAccessLevel());

                } catch (Exception e) {

                    e.printStackTrace();
                }
            }
        });

        thread.start();
    }

    public boolean isNetworkAvailable(Context context)
    {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null;
    }

}

This is my activity code from where i am calling loginToTwitter function.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    OBLTwitter twitter = new OBLTwitter(this);
    twitter.loginToTwitter();
}

This is my manifest file, I am adding this because i made some changes suggested by answerers of different questions.

 <uses-sdk
    android:minSdkVersion="14"
    android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />


<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.objectlounge.OBLTwitter.MainActivity"
        android:label="@string/app_name" >
        android:launchMode="singleInstance">


        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data
                android:host="ridesharebuddy"
                android:scheme="app" />
        </intent-filter>
    </activity>
</application>

Error log

enter image description here


Source: (StackOverflow)

"PKIX path building failed" and "unable to find valid certification path to requested target"

I'm trying to get tweets using twitter4j library for my java project. On my first run I got an error about certificate sun.security.validator.ValidatorException and sun.security.provider.certpath.SunCertPathBuilderException. Then I added twitter certificate by:

C:\Program Files\Java\jdk1.7.0_45\jre\lib\security>keytool -importcert -trustcacerts -file PathToCert -alias ca_alias -keystore "C:\Program Files\Java\jdk1.7.0_45\jre\lib\security\cacerts"

But without success. Here is the procedure to get twitters:

public static void main(String[] args) throws TwitterException {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true)
        .setOAuthConsumerKey("myConsumerKey")
        .setOAuthConsumerSecret("myConsumerSecret")
        .setOAuthAccessToken("myAccessToken")
        .setOAuthAccessTokenSecret("myAccessTokenSecret");

    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();

    try {
        Query query = new Query("iphone");
        QueryResult result;
        result = twitter.search(query);
        System.out.println("Total amount of tweets: " + result.getTweets().size());
        List<Status> tweets = result.getTweets();

        for (Status tweet : tweets) {
            System.out.println("@" + tweet.getUser().getScreenName() + " : " + tweet.getText());
        }
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to search tweets: " + te.getMessage());
    }

And here is the error:

sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
Relevant discussions can be found on the Internet at:
    http://www.google.co.jp/search?q=d35baff5 or
    http://www.google.co.jp/search?q=1446302e
TwitterException{exceptionCode=[d35baff5-1446302e 43208640-747fd158 43208640-747fd158 43208640-747fd158], statusCode=-1, message=null, code=-1, retryAfter=-1, rateLimitStatus=null, version=3.0.5}
    at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:177)
    at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:61)
    at twitter4j.internal.http.HttpClientWrapper.get(HttpClientWrapper.java:81)
    at twitter4j.TwitterImpl.get(TwitterImpl.java:1929)
    at twitter4j.TwitterImpl.search(TwitterImpl.java:306)
    at jku.cc.servlets.TweetsAnalyzer.main(TweetsAnalyzer.java:38)
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.ssl.Alerts.getSSLException(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
    at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
    at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
    at sun.security.ssl.ClientHandshaker.serverCertificate(Unknown Source)
    at sun.security.ssl.ClientHandshaker.processMessage(Unknown Source)
    at sun.security.ssl.Handshaker.processLoop(Unknown Source)
    at sun.security.ssl.Handshaker.process_record(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
    at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at java.net.HttpURLConnection.getResponseCode(Unknown Source)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source)
    at twitter4j.internal.http.HttpResponseImpl.<init>(HttpResponseImpl.java:34)
    at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:141)
    ... 5 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.validator.PKIXValidator.doBuild(Unknown Source)
    at sun.security.validator.PKIXValidator.engineValidate(Unknown Source)
    at sun.security.validator.Validator.validate(Unknown Source)
    at sun.security.ssl.X509TrustManagerImpl.validate(Unknown Source)
    at sun.security.ssl.X509TrustManagerImpl.checkTrusted(Unknown Source)
    at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
    ... 20 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(Unknown Source)
    at java.security.cert.CertPathBuilder.build(Unknown Source)
    ... 26 more
Failed to search tweets: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Source: (StackOverflow)

Get tweets of a public twitter profile

I have a list of usernames on Twitter whose profiles are public. I wish to get "all the tweets" they have posted from the day they formed their profile. I checked Twitter4J examples on GitHub.
According to the Twitter API documentation, only the 20 most recent tweets are returned. Is there anyway I could perform my task?


Source: (StackOverflow)

How to retrieve a twitter user's name using Twitter 4j

I'm new to android development (and java in general). I'm building an application that requires a user to signup by logging-in to their twitter account from where their basic information is imported and saved. The information required would be birthday, name (full names), username, location, sex, etc. I'm using twitter4j to accomplish this. I've tried looking at the twitter4j documentation but being an android newbie (and java in general), the documentation is a little bit hard to understand so I seem to be unable to get it to do something other than set a status update.

This is the code in my activity:

package cc.co.localsquare.app;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Toast;
import oauth.signpost.OAuthProvider;
import oauth.signpost.basic.DefaultOAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.exception.OAuthNotAuthorizedException;
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.http.AccessToken;

public class ConnectTwitterActivity extends BaseActivity {

  public final static String CONSUMER_KEY = "valid key";
  public final static String CONSUMER_SECRET = "valid secret";
  public final static String CALLBACK_URL = "localsquare://ConnectTwitterActivity2";

  private CommonsHttpOAuthConsumer commonHttpOAuthConsumer;
  private OAuthProvider authProvider;

  private Twitter twitter;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.connect_twitter);

        commonHttpOAuthConsumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
        authProvider = new DefaultOAuthProvider("http://twitter.com/oauth/request_token",
            "http://twitter.com/oauth/access_token", "http://twitter.com/oauth/authorize");
        try {
      String oAuthURL = authProvider.retrieveRequestToken(commonHttpOAuthConsumer, CALLBACK_URL);
      this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(oAuthURL)));
    } catch (OAuthMessageSignerException e) {
      Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
      e.printStackTrace();
    } catch (OAuthNotAuthorizedException e) {
      Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
      e.printStackTrace();
    } catch (OAuthExpectationFailedException e) {
      Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
      e.printStackTrace();
    } catch (OAuthCommunicationException e) {
      Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
      e.printStackTrace();
    }
    }

    protected void onNewIntent(Intent intent) {
      super.onNewIntent(intent);

      Uri uri = intent.getData();
      if (uri != null && uri.toString().startsWith(CALLBACK_URL)) {
        String verifier = uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);
        try {
          authProvider.retrieveAccessToken(commonHttpOAuthConsumer, verifier);

          AccessToken accessToken = new AccessToken(commonHttpOAuthConsumer.getToken(),
              commonHttpOAuthConsumer.getTokenSecret());

          twitter = new TwitterFactory().getInstance();
          twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);

          twitter.setOAuthAccessToken(accessToken);

          // Alternate way:
          // twitter = new TwitterFactory().getOAuthAuthorizedInstance(CONSUMER_KEY, CONSUMER_SECRET,
          //     new AccessToken(commonHttpOAuthConsumer.getToken(), commonHttpOAuthConsumer.getTokenSecret()));

          // Tweet message to be updated.
          String tweet = "Hi there, This was sent from my application - OAuth, Twitter";
          twitter.updateStatus(tweet);

        }
        catch (Exception e) {
          Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG);
        }
      }
    }

}

How EXACTLY can I solve my problem?


Source: (StackOverflow)

android twitter retrieveRequestToken 401 on request token

I am trying the following sample app for twitter oauth.

http://www.androidsdkforum.com/android-sdk-development/3-oauth-twitter.html

private void askOAuth() {
        try {
            consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
            provider = new DefaultOAuthProvider("http://twitter.com/oauth/request_token",
                                                "http://twitter.com/oauth/access_token",
                                                "http://twitter.com/oauth/authorize");
            String authUrl = provider.retrieveRequestToken(consumer, CALLBACK_URL);
            Toast.makeText(this, "Please authorize this app!", Toast.LENGTH_LONG).show();
            this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
        } catch (Exception e) {
            Log.e(APP, e.getMessage());
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

When i run the following code it gives exception as following

"oauth.signpost.exception.OAuthNotAuthorizedException: Authorization failed (server replied with a 401). This can happen if the consumer key was not correct or the signatures did not match."

on this line String authUrl = provider.retrieveRequestToken(consumer, CALLBACK_URL);

I provided the correct 'key' and 'secret' does twitter giving me wrong key and secret ?


Source: (StackOverflow)

Service provider responded in error: 301 (Moved Permanently) - Twitter API 1.1

I get this error when trying to connect to Twitter? Why?

02-18 16:40:33.270: W/System.err(7167): oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: Service provider responded in error: 301 (Moved Permanently)
02-18 16:40:33.270: W/System.err(7167):     at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:218)
02-18 16:40:33.270: W/System.err(7167):     at oauth.signpost.AbstractOAuthProvider.retrieveRequestToken(AbstractOAuthProvider.java:74)
02-18 16:40:33.270: W/System.err(7167):     at app.jp.cropnet.twitter.TwitterApp$2.run(TwitterApp.java:255)
02-18 16:40:33.270: W/System.err(7167): Caused by: oauth.signpost.exception.OAuthCommunicationException: Service provider responded in error: 301 (Moved Permanently)
02-18 16:40:33.270: W/System.err(7167):     at oauth.signpost.AbstractOAuthProvider.handleUnexpectedResponse(AbstractOAuthProvider.java:245)
02-18 16:40:33.270: W/System.err(7167):     at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:193)
02-18 16:40:33.270: W/System.err(7167):     ... 2 more

Source: (StackOverflow)

Android twitter4j upload image

I have an android app through which I can successfully update the twitter status. I am using it to share links to a webpage which displays an image. I think it will be nice to have a scaled down preview of the image along with the tweet the same way instagram does. How do I upload this image along with my tweet?


Source: (StackOverflow)

Twitter integration:consumer key/secret pair already set

Trying to integrate my webapp with Twitter using twitter4j lib.
I have registered my app on twitter site and got Consumer key and Consumer secret values.
Nothing special,standard OAuth step.

code:

public class TwitterService {
    private final String CONSUMER_KEY = "xxx";
    private final String CONSUMER_SECRET = "yyy";

    public String fav() {
        Twitter twitter = TwitterFactory.getSingleton();
        twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
...

exception:

Caused by: java.lang.IllegalStateException: consumer key/secret pair already set.

I have no more configuration for key and secret,any .properties or other file.

EDIT:

commenting line twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET); causes exception:

java.lang.IllegalStateException: OAuth consumer key/secret combination not supplied

Source: (StackOverflow)

How can I follow a twitter user using Twitter4j framework?

I need my Java Twitter application to be able to follow a user in twitter. When I pass it the user ID as a string, the application follow it automatically. I couldn't find the method that can do that in Twitter4j.


Source: (StackOverflow)

Filter twitter4j stream

I'm trying to filter my twitter4j stream with the following code :

    TwitterStream twitterStream = getTwitterStreamInstance();

    // Listener
    twitterStream.addListener(listener);

    // Filter
    FilterQuery filtre = new FilterQuery();
    String[] keywordsArray = { "iphone", "samsung" };
    filtre.track(keywordsArray);
    twitterStream.filter(filtre);

    // Listening
    twitterStream.sample();

But the result is, for example :

27/59 - "Taking a risk over something only means that you want it more than anything"
28/63 - The more attractive you are, the more awkward I am.
29/64 - the thing about pain is that it demands to be felt

And I don't recover the keywords I want to follow, where is the problem ?


Source: (StackOverflow)

Twitter4j : Search for public tweets

How does one search within public tweets using the Twitter4j library ?

public static void main(String[] args) {
        Twitter twitter = new TwitterFactory().getInstance();
        try {
            Query query = new Query("Cocaine");
            QueryResult result;
            do {
                result = twitter.search(query);
                List<Status> tweets = result.getTweets();
                for (Status tweet : tweets) {
                    System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText());
                }
            } while ((query = result.nextQuery()) != null);
            System.exit(0);
        } catch (TwitterException te) {
            te.printStackTrace();
            System.out.println("Failed to search tweets: " + te.getMessage());
            System.exit(-1);
        }
    }

This gives me a Authentication credentials are missing. error


Source: (StackOverflow)

method retrieveRequestToken raises "Communication with the service provider failed: null"

I am using twitter4j to send tweet from my application. When I invoke the method retrieveRequestToken, I get the error "Communication with the service provider failed: null".

public static void askOAuth(Context context) {
    try {
        // Use Apache HttpClient for HTTP messaging
        consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
        provider = new CommonsHttpOAuthProvider(
                "https://api.twitter.com/oauth/request_token",
                "https://api.twitter.com/oauth/access_token",
                "https://api.twitter.com/oauth/authorize");
        String authUrl = provider.retrieveRequestToken(consumer, CALLBACK_URL);
        Toast.makeText(context, "Authorize this app!", Toast.LENGTH_LONG).show();
        context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
    } catch (Exception e) {
        Log.e(APP, e.getMessage());
        Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show();
    }
}

Thank you.


Source: (StackOverflow)

Rate Limit Exceeded - Custom Twitter app

I am working with a java Twitter app (using Twitter4J api). I have created the app and can view the current users timeline, user's profiles, etc..

However, when using the app it seems to quite quickly exceed the 150 requests an hour rate limit set on Twitter clients (i know developers can increase this to 350 on given accounts, but that would not resolve for other users).

Surely this is not affecting all clients, any ideas as to how to get around this?

Does anyone know what counts as a request? For example, when i view a user's profile, i load the User object (twitter4j) and then get the screenname, username, user description, user status, etc to put into a JSON object - would this be a single call to get the object or would it several to include all the user.get... calls?

Thanks in advance


Source: (StackOverflow)