14

How can I share a string message on twitter? I would like to let the user choose between multiple string messages and click on one to share it via Twitter.

TN888
  • 7,659
  • 9
  • 48
  • 84
Ahmad Ayyad
  • 141
  • 1
  • 1
  • 3

5 Answers5

20

There are a number of ways to implement this.One may be simply open up http://twitter.com and share tweets in a single intent such as..

Intent tweet = new Intent(Intent.ACTION_VIEW);
tweet.setData(Uri.parse("http://twitter.com/?status=" + Uri.encode(message)));//where message is your string message
startActivity(tweet);

Or,

Intent tweet = new Intent(Intent.ACTION_SEND);
tweet.putExtra(Intent.EXTRA_TEXT, "Sample test for Twitter.");
startActivity(Intent.createChooser(share, "Share this via"));

Or,

String tweetUrl = "https://twitter.com/intent/tweet?text=WRITE YOUR MESSAGE HERE &url="
                    + "https://www.google.com";
Uri uri = Uri.parse(tweetUrl);
startActivity(new Intent(Intent.ACTION_VIEW, uri));
ridoy
  • 6,274
  • 2
  • 29
  • 60
6

To share via twitter I use my own custom static function in a Util class like so:

public class Util
{
    public static Intent getTwitterIntent(Context ctx, String shareText)
    {
        Intent shareIntent;

        if(doesPackageExist(ctx, "com.twitter.android"))
        {           
            shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.setClassName("com.twitter.android",
                "com.twitter.android.PostActivity"); 
            shareIntent.setType("text/*");
            shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareText); 
            return shareIntent;
       }
       else
       {
           String tweetUrl = "https://twitter.com/intent/tweet?text=" + shareText;
           Uri uri = Uri.parse(tweetUrl);
           shareIntent = new Intent(Intent.ACTION_VIEW, uri);
           return shareIntent;
       }
   }
}

The advantage of this function is that if the twitter app is installed it uses that, otherwise, it uses the web based twitter page. The text that will be tweeted is passed into the function.

In your scenario, when the user has selected from a choice of messages, pass the selected message into the function. It will then give you back an Intent which you can plug into startActivity() function like so:

startActivity(Util.getTwitterIntent(context, "Text that will be tweeted"));
Richard Lewin
  • 1,870
  • 1
  • 19
  • 26
1

You can use library Twitter4J. Download it and add to java bulid path. Code samples :

  • adding new tweet :

    Twitter twitter = TwitterFactory.getSingleton();

    Status status = twitter.updateStatus(latestStatus);

  • log in using OAuth (code for Java, edit it):

    Twitter twitter = TwitterFactory.getSingleton();
    twitter.setOAuthConsumer("[consumer key]", "[consumer secret]");
    RequestToken requestToken = twitter.getOAuthRequestToken();
    AccessToken accessToken = null;
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    while (null == accessToken) {
      System.out.println("Open the following URL and grant access to your account:");
      System.out.println(requestToken.getAuthorizationURL());
      System.out.print("Enter the PIN(if aviailable) or just hit enter.[PIN]:");
      String pin = br.readLine();
      try{
         if(pin.length() > 0){
           accessToken = twitter.getOAuthAccessToken(requestToken, pin);
         }else{
           accessToken = twitter.getOAuthAccessToken();
         }
      } catch (TwitterException te) {
        if(401 == te.getStatusCode()){
          System.out.println("Unable to get the access token.");
        }else{
          te.printStackTrace();
        }
      }
    }
    //persist to the accessToken for future reference.
    storeAccessToken(twitter.verifyCredentials().getId() , accessToken);
    Status status = twitter.updateStatus(args[0]);
    System.out.println("Successfully updated the status to [" + status.getText() + "].");
    System.exit(0);
    

    }

    private static void storeAccessToken(int useId, AccessToken accessToken){ //store accessToken.getToken() //store accessToken.getTokenSecret() }

    • getting tweets :

      Twitter twitter = TwitterFactory.getSingleton();
      Query query = new Query("source:twitter4j yusukey");
      QueryResult result = twitter.search(query);
      for (Status status : result.getStatuses()) {
          System.out.println("@" + status.getUser().getScreenName() + ":" + status.getText());
      }
      
  • getting timeline :

       Twitter twitter = TwitterFactory.getSingleton();
       List<Status> statuses = twitter.getHomeTimeline();
      System.out.println("Showing home timeline.");
       for (Status status : statuses) {
          System.out.println(status.getUser().getName() + ":" +
                           status.getText());
    }
    

I hope that I helped

TN888
  • 7,659
  • 9
  • 48
  • 84
1

If u need a success response and tweet id u can use twitter SDK Status Services in order to post tweet over Twitter. u can post text using this.

   StatusesService statusesService = TwitterCore.getInstance().getApiClient().getStatusesService();
    Call<Tweet> tweetCall = statusesService.update(text, null, false, null, null, null, false, false, null);
    tweetCall.enqueue(new Callback<Tweet>() {
        @Override
        public void success(Result<Tweet> result) {
            Log.d("result", result.data.idStr);
        }



        @Override
        public void failure(TwitterException exception) {
            hideProgressDialogResult();
            exception.printStackTrace();

        }
    });

u can also upload image with description but before that u have to create media id of image using twitter media service and pass this media id to status service.

ashish
  • 159
  • 9
0
try {
    Intent tweetIntent = new Intent(Intent.ACTION_SEND);
    tweetIntent.setPackage("com.twitter.android");
    tweetIntent.setType("text/plain");
    tweetIntent.putExtra(Intent.EXTRA_TEXT, "your message");
    startActivity(tweetIntent);
  } catch (ActivityNotFoundException e) {
    Intent tweetIntent = new Intent(Intent.ACTION_VIEW);
    tweetIntent.setData(Uri.parse("https://twitter.com/intent/tweet?text=" + "your message"));
    startActivity(tweetIntent);
  }
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 13 '23 at 14:47