📜 ⬆️ ⬇️

An example of using Fabric (Twitter Kit) in Android Studio



At the end of October last year, the guys from Twitter launched Fabric. Until now, there was no information about Fabric in Russian on the network, so I decided to explain with an example how everything works on the example of authorization, tweet feed, adding a tweet and leaving the account.

First you need to get Fabric yourself. To do this, you need to leave a mail address here . The letter will not be long in coming, I received the platform in two hours. After confirmation, you will get to the page with the installation of the plugin on your IDE.

Choose Android Studio, download the plugin.
')
Installing it is also very simple: Preferences -> Plugins -> Install plugin from disk We install the plugin, restart the IDE and voila, we have a blue platform icon on the toolbar when we click on which the authorization and project selection window appears, but we will create a new one.

1. Authorization

So, create a project. Call the factory window again, select the project for it. Next you will need to install the Twitter Kit (the rest of us are not interested yet). To log in on Twitter, we need to select in the next window the third option with authorizations (Log in with Twitter). Dependencies, meta dates, twitter kei, he pulls himself. In the next windows, he will already ask us to add a few lines of code, well, we can not refuse him?

As a result, our starting xml will only have a login button:
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:id="@+id/layout"> <com.twitter.sdk.android.core.identity.TwitterLoginButton android:id="@+id/twitter_login_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true"/> </LinearLayout> 



In our activity, too, everything is simple:
MainActivity
 public class MainActivity extends ActionBarActivity { private static final String TWITTER_KEY = "YOUR_TWITTER_KEY"; private static final String TWITTER_SECRET = "YOUR_TWITTER_SECRET"; private TwitterLoginButton loginButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET); Fabric.with(this, new Twitter(authConfig)); setContentView(R.layout.activity_main); loginButton = (TwitterLoginButton) findViewById(R.id.twitter_login_button); loginButton.setCallback(new Callback<TwitterSession>() { @Override public void success(Result<TwitterSession> result) { // Do something with result, which provides a TwitterSession for making API calls String name = result.data.getUserName(); Toast.makeText(MainActivity.this, ", " + name,Toast.LENGTH_SHORT).show(); } @Override public void failure(TwitterException exception) { // Do something on failure } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); loginButton.onActivityResult(requestCode, resultCode, data); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override protected void onResume() { super.onResume(); } @Override protected void onDestroy() { super.onDestroy(); } } 



Build, we start, we try to become authorized, everything works. Simply? Yes!

2. Tweets


Let's create a new activity based on the ListActivity and use the adapter already in the toolbox.

TweetsFeedActivity
 public class TweetsActivity extends ListActivity { private TweetViewAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list); adapter = new TweetViewAdapter(this); setListAdapter(adapter); loadTweets(); } public void loadTweets() { final StatusesService service = Twitter.getInstance().getApiClient().getStatusesService(); service.homeTimeline(null, null, null, null, null, null, null, new Callback<List<Tweet>>() { @Override public void success(Result<List<Tweet>> result) { adapter.setTweets(result.data); } @Override public void failure(TwitterException error) { Toast.makeText(TweetsActivity.this, "Failed to retrieve timeline", Toast.LENGTH_SHORT).show(); } } ); } 


What happened.

Great, go ahead.

3. We write your tweet


Go to javadoc for this method and see:
javadoc
  /** * Updates the authenticating user's current status, also known as tweeting. * <p> * For each update attempt, the update text is compared with the authenticating user's recent * tweets. Any attempt that would result in duplication will be blocked, resulting in a 403 * error. Therefore, a user cannot submit the same status twice in a row. * <p> * While not rate limited by the API a user is limited in the number of tweets they can create * at a time. If the number of updates posted by the user reaches the current allowed limit this * method will return an HTTP 403 error. * * @param status (required) The text of your status update, typically up to 140 characters. URL * encode as necessary. [node:840,title="t.co link wrapping"] may effect character * counts. There are some special commands in this field to be aware of. For * instance, preceding a message with "D " or "M " and following it with a screen * name can create a direct message to that user if the relationship allows for * it. * @param inReplyToStatusId (optional) The ID of an existing status that the update is in reply * to. Note:: This parameter will be ignored unless the author of the * tweet this parameter references is mentioned within the status text. * Therefore, you must include @username, where username is the author * of the referenced tweet, within the update. * @param possiblySensitive (optional) If you upload Tweet media that might be considered * sensitive content such as nudity, violence, or medical procedures, * you should set this value to true. See Media setting and best * practices for more context. Defaults to false. * @param latitude (optional) The latitude of the location this tweet refers to. This parameter * will be ignored unless it is inside the range -90.0 to +90.0 (North is * positive) inclusive. It will also be ignored if there isn't a corresponding * long parameter. * @param longitude (optional) The longitude of the location this tweet refers to. The valid * ranges for longitude is -180.0 to +180.0 (East is positive) inclusive. This * parameter will be ignored if outside that range, if it is not a number, if * geo_enabled is disabled, or if there not a corresponding lat parameter. * @param placeId (optional) A place in the world. These IDs can be retrieved from [node:29]. * @param displayCoordinates (optional) Whether or not to put a pin on the exact coordinates a * tweet has been sent from. * @param trimUser (optional) When set to either true, t or 1, each tweet returned in a timeline * will include a user object including only the status authors numerical ID. * Omit this parameter to receive the complete user object. * @param cb The callback to invoke when the request completes. */ @FormUrlEncoded @POST("/1.1/statuses/update.json") void update(@Field("status") String status, @Field("in_reply_to_status_id") Long inReplyToStatusId, @Field("possibly_sensitive") Boolean possiblySensitive, @Field("lat") Double latitude, @Field("long") Double longitude, @Field("place_id") String placeId, @Field("display_cooridnates") Boolean displayCoordinates, @Field("trim_user") Boolean trimUser, Callback<Tweet> cb); 


We see that the only required parameter is status. Okay, we write method:

 private void publishTweet() { final StatusesService statusesService = Twitter.getInstance().getApiClient().getStatusesService(); statusesService.update(" !", null, null, null, null, null, null, null, new Callback<Tweet>() { @Override public void success(Result<Tweet> tweetResult) { Toast.makeText(TweetsActivity.this, "  ", Toast.LENGTH_SHORT).show(); } @Override public void failure(TwitterException e) { Toast.makeText(TweetsActivity.this, "   ", Toast.LENGTH_SHORT).show(); } }); } 

It should be noted that in the current version you cannot add a photo to a tweet. Will have to wait.

4. Logout

Just add
  Twitter.getSessionManager().clearActiveSession(); 


And he will interrupt the current session.

Repository link: github.com/afeozzz/fabric-testApp

If we compare it with what crutches we had to do before, even with these 4 functions, then we can safely conclude that the developers of the Fabric have pretty much simplified the life of the developers.

Source: https://habr.com/ru/post/248667/


All Articles