Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Java Development

Reply
Developer
pankajace12
Posts: 206
Registered: ‎04-30-2011
My Device: BlackBerry Z10

Twitter is Integrated in BlackBerry

[ Edited ]

Hi All,

 

I have read so many forum regarding twitter integration in BlackBerry. Got confusion more with the lots of issue. No where is point is clear about this. But, doing here and there in all support form, finally I did integrate the twitter in BlackBerry.

 

During Twitter Integration, I did help by Ernandes Mourao.& Walter Rodriguez. both guys supported me.

 

So I am posting my entire code experience here, so that other BB developer no need get confusion more.. 

 

In this code. I have added a simple button, and doing click over that your process will continue.

 

According to me, I have created more class to make confusion more.

 

I am using the following java class:

 

1)  TweetToFriend.java, to do tweet, .

2)  FriendshipManagement.java, to do follow & unFollow the friend .

3) StoreToken.java to store the token that we once we login the twitter, I did store token, so, we need not to suffer login more than one time.

 

Hence description has been introduce in the my class.

 

If you find this code is helpful to you. please like it.

 

I am using, twitter_api_me-1.8.jar 

 

Pawan Jha

BlackBerry Developer

 

This is the first class. to call Mainscreen

package app.screen;
/*
 * Name : Pawan kumar jha
 * Email: pankajace12@gmail.com
 * BlackBerry Developer
 */
import net.rim.device.api.ui.UiApplication;
import app.screen.TwitterScreen;


public class StartApp extends UiApplication {
	public StartApp() {
		this.pushScreen(new TwitterScreen());
	}

	public static void main(String[] args) {
		StartApp myApp = new StartApp();
		myApp.enterEventDispatcher();
	}
}

/////////////////////////////////////////////////
This is the class where you will do authorzation of twitter login.

/////////////////////////////////////////////////
package app.screen;
/*
 * Name : Pawan kumar jha
 * Email: pankajace12@gmail.com
 * BlackBerry Developer
 */
import net.rim.device.api.browser.field2.BrowserField;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.MainScreen;

import com.twitterapime.rest.Credential;
import com.twitterapime.xauth.Token;
import com.twitterapime.xauth.ui.OAuthDialogListener;
import com.twitterapime.xauth.ui.OAuthDialogWrapper;
import com.twitterpawan.activity.FriendshipManagement;
import com.twitterpawan.activity.TweetToFriend;
public class TwitterScreen extends MainScreen  {

	private final String CONSUMER_KEY ="<your consume key>";
	private final String CONSUMER_SECRET = "<your consumer secret key>";
	private final String CALLBACK_URL ="any url that you want to call back";
	private LabelField _labelStutus;
	private OAuthDialogWrapper pageWrapper = null;
	public StoreToken _tokenValue;
	ShowAuthBrowser showAuthBrowserScreen;

	public TwitterScreen()
	{
		setTitle("Twitter Integration using OAuth");

		showAuthBrowserScreen = new ShowAuthBrowser();

		add ( new ButtonField("Tweet" ) {
			protected boolean navigationUnclick(int status, int time) {

				_tokenValue = StoreToken.fetch();

				if(_tokenValue.token.equalsIgnoreCase("nothing"))
				{
					showAuthBrowserScreen.doAuth( null );
					UiApplication.getUiApplication().pushScreen(showAuthBrowserScreen);
				}
				else
				{ 
					/************************************************************/
					Token t = new Token(_tokenValue.token, _tokenValue.secret, _tokenValue.userId, _tokenValue.username);
					Credential c = new Credential(CONSUMER_KEY,	CONSUMER_SECRET, t);
					boolean done=false;
					String _friendName = "Pawan Kumar jha";

					try
					{
						FriendshipManagement fm = new FriendshipManagement();
						done=fm.doFollowFriend(c, _friendName);
						if(done == true)
						{
							Dialog.alert("Now you are  Following to " +_friendName);
						}

					}
					catch (Exception e) {
						// TODO: handle exception
						Dialog.alert("Exception" + e.getMessage());
					}
					/************************************************************/
 
				}
				return true;
			}
		});
	}


	class ShowAuthBrowser extends MainScreen implements OAuthDialogListener
	{
		BrowserField b = new BrowserField();

		public ShowAuthBrowser() 
		{	
			_labelStutus = new LabelField("Your app is being authorize." );
			add(_labelStutus );
			add(b);
			pageWrapper = new BrowserFieldOAuthDialogWrapper(b,CONSUMER_KEY,CONSUMER_SECRET,CALLBACK_URL,this);
			pageWrapper.setOAuthListener(this);

		}
		public void doAuth( String pin )
		{
			try
			{
				if ( pin == null )
				{
					pageWrapper.login();
				}
				else
				{
					this.deleteAll();
					add(b);
					pageWrapper.login( pin );
				} 

			}
			catch ( Exception e )
			{
				final String message = "Error loggin Twitter: " + e.getMessage();
				Dialog.alert( message );

			}			
		}


		public void onAccessDenied(String response ) {

			System.out.println("Access denied! -> " + response );
			updateScreenLog( "Acceso denegado! -> " + response );

		}

		public void onAuthorize(final Token token) {

			final Token myToken = token;
			_tokenValue = StoreToken.fetch();
			_tokenValue.token = myToken.getToken();
			_tokenValue.secret = myToken.getSecret();
			_tokenValue.userId = myToken.getUserId();
			_tokenValue.username = myToken.getUsername();
			_tokenValue.save();

			UiApplication.getUiApplication().invokeLater( new Runnable() {

				public void run() {
					deleteAll();
					Credential c = new Credential(CONSUMER_KEY,	CONSUMER_SECRET, myToken);
					TweetToFriend tw = new TweetToFriend();
					String message="";
					boolean done=false;
					done=tw.doTweet(message, c);
					if(done == true)
					{
						Dialog.alert( "Tweet succusfully..." );
						close();	
					}
				}
			});

		}

		public void onFail(String arg0, String arg1) {
			updateScreenLog("Error authenticating user! -> " + arg0 + ", " + arg1);
		}
	}


	private void updateScreenLog( final String message )
	{
		UiApplication.getUiApplication().invokeLater( new Runnable() {

			public void run() {
				_labelStutus.setText( message );				
			}
		});
	}
   
}


//////////////////////////////////////////////////////////////////////
This class support do support valid character from the invalid character that we get in login page of twitter.

package app.screen;
/*
 * BrowserFieldOAuthDialogWrapper.java
 * Me got this class by Ernandes Mourao.
 * Thanks to Ernandes.. 
 * Copyright(c) Ernandes Mourao Junior (ernandes@gmail.com)
 * All rights reserved
 */
 

import net.rim.device.api.browser.field2.BrowserField;
import net.rim.device.api.browser.field2.BrowserFieldListener;

import org.w3c.dom.Document;

import com.twitterapime.xauth.ui.OAuthDialogListener;
import com.twitterapime.xauth.ui.OAuthDialogWrapper;
 
public final class BrowserFieldOAuthDialogWrapper extends OAuthDialogWrapper {
 
	private BrowserField browserField;
	
	 
	public BrowserFieldOAuthDialogWrapper(BrowserField browserField, 
		String consumerKey, String consumerSecret, String callbackUrl, 
		OAuthDialogListener oauthListener) {
		super(consumerKey, consumerSecret, callbackUrl, oauthListener);
		//
		if (browserField == null) {
			throw new IllegalArgumentException(
				"BrowserField must not be null.");
		}
		//
		this.browserField = browserField;
		this.browserField.addListener(new BrowserFieldListenerOAuth());
	}
	
	 
	public BrowserFieldOAuthDialogWrapper(BrowserField browserField) {
		this(browserField, null, null, null, null);
	}
 
	protected void loadUrl(String url) {
		browserField.requestContent(url);
	}
 
	protected void loadHTML(String htmlContent) {
		browserField.displayContent(htmlContent, callbackUrl);
	}
 
	private class BrowserFieldListenerOAuth extends BrowserFieldListener {
	 
		public void documentLoaded(BrowserField browserField, Document document)
			throws Exception {
			trackUrl(browserField.getDocumentUrl());
		}
	}
}


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
I am using this class to store the token value.

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

package app.screen;
/*
 * Name : Pawan kumar jha
 * Email: pankajace12@gmail.com
 * BlackBerry Developer
 */
import net.rim.device.api.system.PersistentObject;
import net.rim.device.api.system.PersistentStore;
import net.rim.device.api.util.Persistable;

public class StoreToken implements Persistable{
private static PersistentObject storage;
private static final long PERSISTENCE_UNIQE_ID= 0x3a08eee2a23dbfccL;
 
 public String token, secret, userId, username;
protected  StoreToken() 
{
	token = "nothing";
	secret = "nothing";
	userId = "nothing";
	username = "nothing";
}

public static StoreToken fetch()
{
	Object ob = storage.getContents();
	StoreToken saved_data = (StoreToken)ob;
	return saved_data;
}

public void save()
{
storage.setContents(this);
storage.commit();
}
static {
	storage = PersistentStore.getPersistentObject(PERSISTENCE_UNIQE_ID);
	synchronized (storage) {
		if(storage.getContents()==null)
		{
			storage.setContents(new StoreToken());
			storage.commit();
		}
	}
}
}


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
This is used to do tweet.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////



package com.twitterpawan.activity;
/*
 * Name : Pawan kumar jha
 * Email: pankajace12@gmail.com
 * BlackBerry Developer
 */
import net.rim.device.api.ui.component.Dialog;

import com.twitterapime.rest.Credential;
import com.twitterapime.rest.TweetER;
import com.twitterapime.rest.UserAccountManager;
import com.twitterapime.search.Tweet;
import com.twitterapime.xauth.Token;

public class TweetToFriend {

	public TweetToFriend() {
		// TODO Auto-generated constructor stub
	}
	
/*	*//************************************************************//*
	Token t = new Token(_tokenValue.token, _tokenValue.secret, 
			_tokenValue.userId, _tokenValue.username);
	Credential c = new Credential(CONSUMER_KEY,	CONSUMER_SECRET, t);
	TweetToFriend tw = new TweetToFriend();
	String message="Hey, I did implment follow & unfollow concept too.... hurrahhhhhhhh";
	boolean done=false;
	done=tw.doTweet(message, c);
	if(done == true)
	{
		Dialog.alert("Tweet send successfully");
	}

	*//************************************************************/
	public boolean doTweet( String message, Credential c )
	{
		boolean done=false;
		UserAccountManager uam = UserAccountManager.getInstance(c);
		try 
		{
			if (uam.verifyCredential()) 
			{
				TweetER.getInstance(uam).post(new Tweet( message ));
				done = true;
			}
		}
		catch (Exception e) 
		{
			System.out.println("Error by posting tweet."+e.getMessage());
		}
		return done;
	} 
	
}


//////////////////////////////////////////////////////////////////////////////////////
This is useful, when you want to follow and unfollow the friend.
//////////////////////////////////////////////////////////////////////////////////////


package com.twitterpawan.activity;
/*
 * Name : Pawan kumar jha
 * Email: pankajace12@gmail.com
 * BlackBerry Developer
 */
import java.io.IOException;

import com.twitterapime.rest.Credential;
import com.twitterapime.rest.UserAccount;
import com.twitterapime.rest.UserAccountManager;
import com.twitterapime.search.LimitExceededException;

public class FriendshipManagement {

	public FriendshipManagement() {
		// TODO Auto-generated constructor stub
	}
	/************************************************************/
	/*
	 * Follow the friend.
	Token t = new Token(_tokenValue.token, _tokenValue.secret, _tokenValue.userId, _tokenValue.username);
	Credential c = new Credential(CONSUMER_KEY,	CONSUMER_SECRET, t);
	boolean done=false;
	String _friendName = "<your friend name>";

	try
	{
		FriendshipManagement fm = new FriendshipManagement();
		done=fm.doFollowFriend(c, _friendName);
		if(done == true)
		{
			Dialog.alert("Now you are Following to " +_friendName);
		}

	}
	catch (Exception e) {
		// TODO: handle exception
		Dialog.alert("Exception" + e.getMessage());
	}*/

	/************************************************************/

	public boolean doFollowFriend(Credential c, String friendName)
	{
		boolean done=false;
		UserAccountManager uam = UserAccountManager.getInstance(c);
		try {
			if (uam.verifyCredential()) 
			{
				UserAccount ua = new UserAccount(friendName);
				ua = uam.follow(ua);
				done = true;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println("IOException: "+e.getMessage());
		} catch (LimitExceededException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("LimitExceededException: "+e.getMessage());
		}
		return done;
	}

	/************************************************************/
/*
	Token t = new Token(_tokenValue.token, _tokenValue.secret, _tokenValue.userId, _tokenValue.username);
	Credential c = new Credential(CONSUMER_KEY,	CONSUMER_SECRET, t);
	boolean done=false;
	String _friendName = "<your friend name>";

	try
	{
		FriendshipManagement fm = new FriendshipManagement();
		done=fm.doUnFollowFriend(c, _friendName);
		if(done == true)
		{
			Dialog.alert("Now you are not Following to " +_friendName);
		}

	}
	catch (Exception e) {
		// TODO: handle exception
		Dialog.alert("Exception" + e.getMessage());
	}*/


	/************************************************************/
	
	public boolean doUnFollowFriend(Credential c, String friendName)
	{
		boolean done=false;

		UserAccountManager uam = UserAccountManager.getInstance(c);
		try {
			if (uam.verifyCredential()) {
				UserAccount ua = new UserAccount(friendName);
				ua = uam.unfollow(ua);
				done = true;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("IOException: "+e.getMessage());
		} catch (LimitExceededException e) {
			// TODO Auto-generated catch block
			System.out.println("LimitExceededException: "+e.getMessage());
		}
		return done;
	}

}


//////////////////////////////////////////////////////////////////////////////////////////
To share the geolocation(Current location).
//////////////////////////////////////////////////////////////////////////////////////////

package com.twitterpawan.activity;
/*
 * Name : Pawan kumar jha
 * Email: pankajace12@gmail.com
 * BlackBerry Developer
 */
import com.twitterapime.rest.Credential;
import com.twitterapime.rest.TweetER;
import com.twitterapime.rest.UserAccountManager;
import com.twitterapime.search.Tweet;
import com.twitterpawan.gps.GPS;

public class TweetGeoLocation {
	public TweetGeoLocation() {
		// TODO Auto-generated constructor stub
	}
	
/*	*//************************************************************//*
	Token t = new Token(_tokenValue.token, _tokenValue.secret, 
			_tokenValue.userId, _tokenValue.username);
	Credential c = new Credential(CONSUMER_KEY,	CONSUMER_SECRET, t);
	
	TweetGeoLocation tgl = new TweetGeoLocation();
	String message="Geo Location.....";
	boolean done=false;
	done=tgl.doShareLocation(message, c);
	if(done == true)
	{
		Dialog.alert("Location Tweet successfully");
	}
	else
	{
		Dialog.alert( "your location is not tweet." );	
	}
	*//************************************************************/
	
	public boolean doShareLocation( String message, Credential c )
	{
		UserAccountManager uam = UserAccountManager.getInstance(c);
		boolean check=false;
		try 
		{
			if (uam.verifyCredential()) 
			{
				GPS geo = new GPS();
				
				 double longi = geo.getLongitude();
				 double latt = geo.getLatitude(); 
		 
				if(!String.valueOf(longi).equalsIgnoreCase("0.0"))
				{
					Tweet post = TweetER.getInstance(uam).post(new Tweet( message 
							+ "Longitutde : " + geo.getLongitude() 
							+ "Latitude : " + geo.getLatitude()));
					check = true;
				}
			}
		}
		catch (Exception e) 
		{
			System.out.println("Error by posting tweet."+e.getMessage());
		}
		return check;
	}
}

////////////////////////////////////////////////////////////////////////////////////////////

package com.twitterpawan.gps;
 
import javax.microedition.location.Location;
import javax.microedition.location.LocationException;
import javax.microedition.location.LocationListener;
import javax.microedition.location.LocationProvider;
import javax.microedition.location.QualifiedCoordinates;

import net.rim.device.api.ui.component.Dialog;

public class GPS extends Thread {  
	  
    private double latitude;  
    private double longitude;  
    private String satCountStr;  
    private float accuracy;  
    private double heading;  
    private double altitude;  
    private double speed;  
  
    private int interval = 1; // time in seconds to get new gps data  
  
    /** 
     * This will start the GPS 
     */  
    public GPS() {  
        // Start getting GPS data  
        if (currentLocation()) {  
            // This is going to start to try and get me some data!  
        }  
    }  
  
    private boolean currentLocation() {  
        boolean retval = true;  
        try {  
            LocationProvider lp = LocationProvider.getInstance(null);  
            if (lp != null) {  
                lp.setLocationListener(new LocationListenerImpl(), interval, 1, 1);  
            } else { 
            	Dialog.inform("Does not Support GPS");
                 retval = false;  
            }  
        } catch (LocationException e) {  
            System.out.println("Error: " + e.toString());  
        }  
  
        return retval;  
    }  
  
    private class LocationListenerImpl implements LocationListener {  
        public void locationUpdated(LocationProvider provider, Location location) {  
            if (location.isValid()) {  
                heading = location.getCourse();  
                longitude = location.getQualifiedCoordinates().getLongitude();  
                latitude = location.getQualifiedCoordinates().getLatitude();  
                altitude = location.getQualifiedCoordinates().getAltitude();  
                speed = location.getSpeed();  
  
           
                String NMEA_MIME = "application/X-jsr179-location-nmea";  
                satCountStr = location.getExtraInfo("satellites");  
                if (satCountStr == null) {  
                    satCountStr = location.getExtraInfo(NMEA_MIME);  
                }  
   
                QualifiedCoordinates qc = location.getQualifiedCoordinates();  
                accuracy = qc.getHorizontalAccuracy();  
            }  
        }  
  
        public void providerStateChanged(LocationProvider provider, int newState) {  
 
        }  
    }  
 
    public double getHeading() {  
        return heading;  
    }  
 
    public double getAltitude() {  
        return altitude;  
    }  
  
  
    public String getSatCount() {  
        return satCountStr;  
    }  
  
  
    public float getAccuracy() {  
        return accuracy;  
    }  
  
  
    public double getLatitude() {  
        return latitude;  
    }  
  
    
    public double getLongitude() {  
        return longitude;  
    }  
   
    public double getSpeed() {  
        return speed;  
    }  
}

 

 

New Developer
Aniruddha
Posts: 60
Registered: ‎09-23-2011
My Device: Blackberry

Re: Twitter is Integrated in BlackBerry

Hello,

 

You are right only check which version you are using for Facebook integrating .

 

The above API support from above version of Blackberry JRE 5.0

 

 

Regards,

Aniruddha

 

Please post message it work or not.

Developer
pankajace12
Posts: 206
Registered: ‎04-30-2011
My Device: BlackBerry Z10

Re: Twitter is Integrated in BlackBerry

[ Edited ]

I have done this twitter not  Facebook integrating as you are saying...

 

This is working fine for OS 6.0 also, I have test it already

 

Pawan

New Developer
Aniruddha
Posts: 60
Registered: ‎09-23-2011
My Device: Blackberry

Re: Twitter is Integrated in BlackBerry

Verry Sorry Its my bad....

Developer
MohammedAziz
Posts: 139
Registered: ‎02-23-2012
My Device: Blackberry bold

Re: Twitter is Integrated in BlackBerry

Can you please attach your running code as a zip file with the jar file you mentioned. That will be a great help for the programmers to integrate then.

Thank you
warm regards
Mohammed Aziz
Developer
pankajace12
Posts: 206
Registered: ‎04-30-2011
My Device: BlackBerry Z10

Re: Twitter is Integrated in BlackBerry

[ Edited ]

HI Mohammed Aziz,

 

Actually, I don't know how to attach the zip file here. Can u please help me for this.

 

Then  I would attach my entire code + jar file as it as. 

 

Thanks

Pawan

Developer
MohammedAziz
Posts: 139
Registered: ‎02-23-2012
My Device: Blackberry bold

Re: Twitter is Integrated in BlackBerry

Yes, you can attach the file when you are replying to this thread or creating a new message.

You can see a attach file option on right hand side with a browse option click on that and browse to the file you want to attach. its very simple isn't?
warm regards
Mohammed Aziz
Developer
pankajace12
Posts: 206
Registered: ‎04-30-2011
My Device: BlackBerry Z10

Re: Twitter is Integrated in BlackBerry

[ Edited ]

Hi Mohammed Aziz,

 

Sorry, I am not able to see the attach option. I mean browse option.

 

Can u give a screen shot for this. indicating to the browse option.

 

Thanks

Developer
MohammedAziz
Posts: 139
Registered: ‎02-23-2012
My Device: Blackberry bold

Re: Twitter is Integrated in BlackBerry

@pankaj

 

Please find the attached file.

 

Thank you

warm regards
Mohammed Aziz
Developer
pankajace12
Posts: 206
Registered: ‎04-30-2011
My Device: BlackBerry Z10

Re: Twitter is Integrated in BlackBerry

[ Edited ]

Hi Mohammed Aziz,

i have already gone through this images. But in my account. there is not any option for attachment.

attachment.png