Twitter tutorial covering hashtags, reply & favorite/un-favorite using twitter4j

This article is in continuation to our previous article which demonstrated user how to authenticate on twitter and post tweet with/without image using twitter4j. This article will help you understand on how to fetch tweets using hashtags and other twitter actions like tweet, re-tweet etc . So lets begin tweeting…I mean the tutorial 🙂 #letsBegin In social media everyone is aware of #hashtags, here we will explain how to fetch tweets for a particular hash tags. we are using “Query” class to fetch tweets.


Query query = new Query(“#android”);

Here, above code snippet is to fetch tweets containing “#android” hashtag. Multiple hashtags You can also fetch tweets for more than one hashtags, say you want to fetch tweets containing hashtag #code or #android,  you need to include both tags with keyword “OR”. for eg:  “#code OR #android” ,  “#code AND #android” Now lets see the above code in action.


Query query = new Query(hashtag);

query.count(10); //  Query will return only 10 tweets per request.

QueryResult queryResultObject = twitter.search(query);

List<twitter4j.Status> qrTweets = queryResultObject.getTweets();

queryResultObject.getTweets()  will return list of twitter4j.Status, which contains tweet data  like retweet count as well as tweet’s owner info. for eg: user screen name, profile image etc Here is code snippet to fetch tweet related data from status model.


status.getUser().getName(); // to get user name

status.getId();// to get tweet id

status.getUser().getScreenName(); // to get user screen name/ user handler

status.getText();// tweet

status.getFavoriteCount(); // favorite count

status.getRetweetCount();// retweet count

PAGINATION setMaxId(int) is useful to fetch next set of tweets . this method will  return tweets with status ids less than the given id.


query.setMaxId(lastSeenId);

TWITTER ACTIONS To perform actions like reply retweet you need to authenticate user on twitter. You can find a tutorial on how to authenticate user on twitter using twitter4j here 1] Favorite To perform fav action on any tweet  you  can use createFavorite() method with tweet id.


twitterInstance.createFavorite(mTweetId)

2] Re-tweet To re-tweet tweet  use  retweetStatus() method with tweet id.


twitterInstance.retweetStatus(mTweetId)

3] Reply To reply on a tweet use updateStatus() method with tweet id.


Twitter twitter = TwitterHelper.getTwitterInstance(mContext);

StatusUpdate statusUpdate = new StatusUpdate(mReplyText);

statusUpdate.inReplyToStatusId(mTweetId);

twitter.updateStatus(statusUpdate);

4] Un-favorite To un-favorite  any tweet  you  can use destroyFavorite() method with tweet id


twitterInstance.destroyFavorite(mTweetId)

Just follow the sample, and you’re ready to tweet. Any issues feel free to contact us. You can download working project from github. Happy Coding Happy Learning 🙂

Advertisements

Listview getViewType() and getViewTypeCount() in Action

This  is an article on listview with different view’s.

We all know that listview is the most used and conventional way of displaying list  of data in android. Many-a-times we do encounter a scenario where we want to display list item depending on a specific condition for example have a look at the images below.

The common way of displaying such a data is to inflate one row and depending on the condition you may hide or make a view visible.

Toggling a view between VIEW.GONE and VIEW.VISIBLE can be a very expensive task inside the getview(..) which will sure affect the list scroll. This can be easily managed and tackled with listview’s pre-defined methods getViewTypeCount() and getItemViewType(..).

So to begin with you need to create separate layouts for each type of view that will be displayed. This way it will be more efficient and less clustered to manage the data.

To put all this into action i have created a demo project which can be downloaded here.

In this project i ‘ m showing 3 different types of row in a listview:

1. A simple text

2. Text with image view

3. Poll with three option

so first create 3 different xmls for different row type.

  • view_row_type_one.xml (for text layout)
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/textview"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:layout_gravity="center"
 android:background="@android:color/darker_gray"
 android:textColor="@android:color/black"
 android:textSize="20sp"
 android:padding="10dp"/>

  • view_row_type_two.xml (layout with text and image )
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:background="@android:color/darker_gray"
 android:padding="10dp" >

<ImageView
 android:id="@+id/imageView"
 android:layout_width="100dp"
 android:layout_height="100dp"
 android:layout_centerInParent="true"
 android:layout_marginBottom="10dp"
 android:contentDescription="@null" />

<TextView
 android:id="@+id/labelTextView"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_alignEnd="@id/imageView"
 android:layout_below="@id/imageView"
 android:layout_marginTop="15dp"
 android:textColor="@android:color/black"
 android:textSize="20sp" />

</RelativeLayout>

* view_row_type_three.xml (layout with radio buttons)

<?xml version="1.0" encoding="utf-8"?>
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:background="@android:color/darker_gray"
 android:padding="10dp" >

<TextView
 android:id="@+id/questionTextView"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_marginLeft="5dp"
 android:textColor="@android:color/black"
 android:textSize="20sp" />

<RadioButton
 android:id="@+id/radioButtonOne"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="@string/yes"
 android:textColor="@android:color/black"
 android:textSize="20sp" />

<RadioButton
 android:id="@+id/radioButtonTwo"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="@string/no"
 android:textColor="@android:color/black"
 android:textSize="20sp" />

<RadioButton
 android:id="@+id/radioButtonThree"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="@string/cant_say"
 android:textColor="@android:color/black"
 android:textSize="20sp" />

</RadioGroup>

What does getViewTypeCount() and getItemViewType(…) do ?

These methods are called before getView(…).

1] getViewTypeCount()

Returns the count of different type of views. Here we are having three different type of views so this method will return count as 3.

2] getItemViewType(…) 

Here we will write the logic to determine the type of view.

@Override

public int getItemViewType(int position) {

if(mList.get(position) instanceof DataModel){

return VIEW_TYPE_TEXT;

}else if(mList.get(position) instanceof ImageModel){

return VIEW_TYPE_IMAGE;

}else{

return VIEW_TYPE_QUESTION;
}

Inside getView(…) method first we determine the type of view by calling getItemViewType(..) method, this will return the type to be inflated as shown below.

@Override

public View getView(int position, View convertView, ViewGroup parent) {

ViewHolder.DataViewHolder dataViewHolder = null;

ViewHolder.ImageViewHolder imageViewHolder = null;

ViewHolder.QuestionViewHolder questionViewHolder = null;

int type = getItemViewType(position); // to determine type of view.

if(type == VIEW_TYPE_TEXT){

if(convertView == null){

convertView = mInflater.inflate(R.layout.view_row_type_one, parent, false);

convertView.setTag(dataViewHolder);

.................

}else{

dataViewHolder = (DataViewHolder)convertView.getTag();

........

}

}else if(type == VIEW_TYPE_IMAGE){

if(convertView == null){

convertView = mInflater.inflate(R.layout.view_row_type_two, parent, false);

convertView.setTag(imageViewHolder);

..........

}else{

imageViewHolder = (ImageViewHolder)convertView.getTag();

...............

}

}else{

if(convertView == null){

convertView = mInflater.inflate(R.layout.view_row_type_three, parent, false);

convertView.setTag(questionViewHolder);

.................

}else{

questionViewHolder = (ViewHolder.QuestionViewHolder)convertView.getTag();

.......

}

}

return convertView;

}

This is all it. You can follow this mechanism of displaying data and you will notice significant improvements in the list scroll and the number of objects created. Hope this is useful to someone.

Download sample project from here.

Happy coding, happy learning. 🙂

How to use tabwidget with fragments

This is a simple tutorial on how to use tabs with fragment in android application.

Final output

final output

In this application we are using fragment from android-support-v4.jar,  you are required to add android-support-v4.jar into your app.

1] Create a class lets say “BaseActivity” as we are using fragments to show tabs. BaseActivity class will extends “android.support.v4.app.FragmentActivity” class.

Here is xml file for BaseActivity class

<android.support.v4.app.FragmentTabHost
 android:id="@android:id/tabhost"
 android:layout_width="match_parent"
 android:layout_height="match_parent" >

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TabWidget
android:id="@android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" />

<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>

</android.support.v4.app.FragmentTabHost>

2] BaseActivity class

In onCreate() method first setup tabhost instance and then add tabs.

mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);

mTabHost.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);

mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator(getResources().getString(R.string.tab_one)), TabOneFrgment.class, null);

mTabHost.addTab(mTabHost.newTabSpec("tab2").setIndicator(getResources().getString(R.string.tab_two)), TabTwoFrgment.class, null);

Here we are adding tabs in tabhost using addTab method

addTab method takes 3 parameter:

a] TabSpec instance :  you can define tab indicator, can assign a tag for this tab etc.

b] activity which you want to show when user clicks on this tab.

c] bundle instance

  • setIndicator(): here you can set text and or icon which will displayed on tab.

  • You can also add icon with tabs

 Ex : mTabHost.addTab(mTabHost.newTabSpec("tab2").setIndicator(getResources().getString(R.string.tab_two),

                getResources().getDrawable(R.drawable.ic_launcher)),TabTwoFrgment.class, null);

Tag a tab

By default tabs are shown in the same order as they were added in tabhost.

You can set a tab as current tab  by using setCurrentTabByTag method.

Ex : mTabHost.setCurrentTabByTag("tag2");

You can also show a tab by using tags :

Ex : TabOneFrgment tabOneFrgment = (TabOneFrgment) fragmentManager.findFragmentByTag("tab1");

fragmentTransaction.show(tabOneFrgment);

fragmentTransaction.commit();

How to navigate tabs???

Tab navigation has 2 aspects:

a] create a new fragment (add a fragment)

b] show already added fragment.

It is easy to create a new fragment on tab click but the trickiest part is to retain fragment state while changing tabs.

So in the sample app we are retaining fragment state whenever user changes a tab.

For this you need to add setOnTabChangedListener to the tab host.

Ex : mTabHost.setOnTabChangedListener(new OnTabChangeListener() {.....});

Inside setOnTabChangedListener we need check whether the intended fragment is already created (please refer fragment life cycle).

If fragment is already created  we just need to show that fragment else we will have to create a new fragment and hide current fragment.

 mTabHost.setOnTabChangedListener(new OnTabChangeListener() {

@Override
 public void onTabChanged(String tabId) {

android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();

TabOneFrgment tabOneFrgment = (TabOneFrgment) fragmentManager.findFragmentByTag("tab1");

TabTwoFrgment tabTwoFrgment = (TabTwoFrgment) fragmentManager.findFragmentByTag("tab2");

android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if(tabId.equalsIgnoreCase("tab1")){

if(tabOneFrgment != null){

if(tabTwoFrgment != null){

fragmentTransaction.hide(tabTwoFrgment);

}

fragmentTransaction.show(tabOneFrgment);

}

}else{

if(tabTwoFrgment != null){

if(tabOneFrgment != null){

fragmentTransaction.hide(tabOneFrgment);

}

fragmentTransaction.show(tabTwoFrgment);

}

}

fragmentTransaction.commit();

}

});

Download sample project from here.
Happy Coding Happy Learning :)

Tutorial on uploading image on twitter using twitter4j

This tutorial walks you through the steps to post a tweet or a tweet with a image on twitter.

First and foremost you should have a valid twitter app configured correctly to post on twitter.

In case you don’t have an app on twitter, follow the steps below to create a simple twitter app and how to configure it correctly.

Step 1.  Goto https://dev.twitter.com/apps Click on create new application button.

Then you will be presented the following page :

1_twit_create_app

Step 1

Fill in the details of your app.

Make sure you don’t leave the CallBack URL blank. A callback url is the one where your app will be redirected to from twitter; this is a test app so for time being you can specify something like eg: http://www.google.com . If you leave this field blank then your app wont be authorized.

Step 2. Now its time to configure your app. Click on the settings tab. Scroll down to the

Application type section and change access to read and write.

2_twit_settings_app

Step 2

Click on the update settings button at the bottom to reflect the changes. Ideally it takes 10 – 15 seconds for the settings to get updated so be patient.

Step 3. Download twitter4J library from the following url http://twitter4j.org/en/index.html and add it to your libs folder.

Note: The zip contains other additional jars. From these we need only twitter4j-core and

twitter4j-media support jars.

3_twit_libs_eclipse

Step 3

Step 4. Now lets get back to some coding. First you need to add the twitter consumer key and secret key to the Strings xml:

<string name = "twitter_consumer_key">YOUR_CONSUMER_KEY</string>
<string name= "twitter_consumer_secret">YOUR_CONSUMER_SECRET</string>
Step 4

Step 4

In our activity we have two buttons:

  • To post a tweet.

  • To post a tweet with image.

On button click we will check whether the app is already authorized if not we will authorize the app using a custom web view.

We will be using the custom webview to authorize the app so that once the app is authorized, you can finish the webview else you will be stuck with a common issue where the view remains opened even after the app is authorized.

Step 5

Step 5

 

The authorization logic is written in LoginActivity class.

Step 5. How to post a tweet/image on twitter ? Is this that tricky ? Lets have a look at it.

a. Post:

 ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();

 configurationBuilder.setOAuthConsumerKey(context.getResources().getString(R.string.twitter_consumer_key));

 configurationBuilder.setOAuthConsumerSecret(context.getResources().getString(R.string.twitter_consumer_secret));

 configurationBuilder.setOAuthAccessToken(LoginActivity.getAccessToken((context)));

 configurationBuilder.setOAuthAccessTokenSecret(LoginActivity.getAccessTokenSecret(context));

 Configuration configuration = configurationBuilder.build();

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

 twitter.updateStatus(message);

b. Post with image:

ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();

configurationBuilder.setOAuthConsumerKey(context.getResources().getString(R.string.twitter_consumer_key));

configurationBuilder.setOAuthConsumerSecret(context.getResources().getString(R.string.twitter_consumer_secret));

configurationBuilder.setOAuthAccessToken(LoginActivity.getAccessToken((context)));

configurationBuilder.setOAuthAccessTokenSecret(LoginActivity.getAccessTokenSecret(context));

Configuration configuration = configurationBuilder.build();

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

StatusUpdate status = new StatusUpdate(message);

status.setMedia(file); // set the image to be uploaded here.

twitter.updateStatus(status);

As you can see posting is as simple as it can be. Further you can download live and functioning app.

Happy Coding Happy Learning 🙂