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
Contributor
KamalSalem
Posts: 28
Registered: ‎06-21-2011
My Device: Torch 9800

twitter integration with my app

Hi Guys,

 

I'm trying to write code to use in my app to post tweets from users' phones to twitter

 

I have two code blocks, both of which seem to need the username/password combo of the user. I have two questions

 

1. Is there a way to retrieve the user/pass combo without needing the user to write them in my app? if so, how?

 

2. which of the following code samples will actually post my tweets, I'm inclinded towards the second one because it's a Geo-Based tweet.

 

String consumerKey = "xxx";
String consumerSecret = "xxx";
HttpRequest req = new HttpRequest("https://api.twitter.com/oauth/access_token");
req.setMethod(HttpConnection.POST);
XAuthSigner signer = new XAuthSigner(consumerKey, consumerSecret);
signer.signForAccessToken(req, "", "");//HERE I'M SUPPOSED TO PUT A USER/PASS COMBO
try {
HttpResponse resp = req.send();
if (resp.getCode() == HttpConnection.HTTP_OK) {
Token accessToken = Token.parse(resp.getBodyContent());

req.close();

req = new HttpRequest("http://api.twitter.com/1/statuses/update.xml");
				          req.setMethod(HttpConnection.POST);
				          req.setBodyParameter("status", "Just used my BB ");          req.setSigner(signer, accessToken);
resp = req.send();
   }
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
req.close();
} catch (IOException e) {}
}

 second code follows:

Credential c = new Credential("xxx", "xxx", "xxx", "xxx");//username,password,key,secret
UserAccountManager m = UserAccountManager.getInstance(c);
if (m.verifyCredential()) {
GeoLocation loc = new GeoLocation(String.valueOf(myX), String.valueOf(myY));
Tweet t = new Tweet("Cool! Geo-located tweet via Twitter API ME", loc);
TweetER ter = TweetER.getInstance(m);
t = ter.post(t);

 

Contributor
praveennagsethiya
Posts: 20
Registered: ‎05-21-2012
My Device: NA

Re: twitter integration with my app -

 login is success but do not post on my wall. Exception show 104:runtime Exception after login.please solve this.

 

my code here:-

 

import net.rim.device.api.ui.UiApplication;


public class Home extends UiApplication
{
    public static void main(String[] args)
    {
        Home app = new Home();
        app.enterEventDispatcher();
    }

    public Home()
    {
        pushScreen(new TwitterAPIMERIMOauthSample());
    }

}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

import impl.rim.com.twitterapime.xauth.ui.BrowserContentManagerOAuthDialogWrapper;

import java.io.IOException;

import com.twitterapime.rest.Credential;
import com.twitterapime.rest.GeoLocation;
import com.twitterapime.rest.TweetER;
import com.twitterapime.rest.UserAccountManager;
import com.twitterapime.search.LimitExceededException;
import com.twitterapime.search.Tweet;
import com.twitterapime.xauth.Token;
import com.twitterapime.xauth.ui.OAuthDialogListener;
import com.twitterapime.xauth.ui.OAuthDialogWrapper;
import net.rim.device.api.browser.field.BrowserContentManager;
import net.rim.device.api.browser.field.RenderingOptions;
import net.rim.device.api.browser.field2.BrowserField;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.container.MainScreen;

 

public    class TwitterAPIMERIMOauthSample extends MainScreen implements OAuthDialogListener {
    
     String CONSUMER_KEY = "PP0dvMT5HUni3MZeimX4OQ";
     String CONSUMER_SECRET = "hqZiN5zADjTWl1f9qSCAsVmWgagg26VcN3qdDpRMFU";
     String CALLBACK_URL = "http://www.rechargestudio.com";
    
                public TwitterAPIMERIMOauthSample() {
                super(VERTICAL_SCROLL);
                setTitle("Twitter API ME - OAuth");
                BrowserField browserField = new BrowserField();
                //BrowserContentManager browserMngr = new BrowserContentManager(0);
                //RenderingOptions rendOptions = browserMngr.getRenderingSession().getRenderingOptions();
                //rendOptions.setProperty(RenderingOptions.CORE_OPTIONS_GUID,RenderingOptions.SHOW_IMAGES_IN_HTML,false);
                add(browserField);
                
                OAuthDialogWrapper pageWrapper = new BrowserFieldOAuthDialogWrapper(browserField);
                
                pageWrapper.setConsumerKey(CONSUMER_KEY);
                pageWrapper.setConsumerSecret(CONSUMER_SECRET);
                pageWrapper.setCallbackUrl(CALLBACK_URL);
                pageWrapper.setOAuthListener(this);
                pageWrapper.login();
            
            }
            
    public void onAccessDenied(String arg0) {
        
            }
            
    public void onAuthorize(Token token) {
        
        Credential c = new Credential(CONSUMER_KEY,    CONSUMER_SECRET, token);
        UserAccountManager m = UserAccountManager.getInstance(c);
        String twitter_username = token.getUsername();
        Dialog.alert(twitter_username);
        try {
            if (m.verifyCredential()) {
                //String twitter_username = token.getUsername();
                //Dialog.alert(twitter_username);
                Tweet t = new Tweet("Hi!!! This is my first tweet via Twitter API ME. ");
                TweetER ter = TweetER.getInstance(m);
                t = ter.post(t);    
                Dialog.alert("Posted");
            }
            else
            Dialog.alert("User name and/or password are invalid!");
            }
        
        catch (IOException e) {
            
            e.printStackTrace();
        } catch (LimitExceededException e) {
            
            e.printStackTrace();
        }
        
        }
    public void onFail(String arg0, String arg1) {
        
        
    }}
    
    
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////

import java.io.IOException;
import org.w3c.dom.Document;
import net.rim.device.api.browser.field2.BrowserField;
import net.rim.device.api.browser.field2.BrowserFieldListener;
import net.rim.device.api.ui.UiApplication;
import com.twitterapime.rest.Credential;
import com.twitterapime.rest.GeoLocation;
import com.twitterapime.rest.TweetER;
import com.twitterapime.rest.UserAccountManager;
import com.twitterapime.search.LimitExceededException;
import com.twitterapime.search.Tweet;
import com.twitterapime.xauth.Token;
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());
                                
            }}
                
        


    }


please solve my problem as soon as possible

 

 

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

Re: twitter integration with my app -

Contributor
praveennagsethiya
Posts: 20
Registered: ‎05-21-2012
My Device: NA

Re: twitter integration with my app -

dear sir above link is very useful. I am trying this code but in this code, i click on button then direct login and post on my wall.no login page appears.please cleare this things

 

thanking you

 

regards

 

praveen nagsethiya      

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

Re: twitter integration with my app -

Hi Praveen

 

On that link:

 

On First time click: 

 

When you click over the button, you will get login page after entering username and password it will do authentic and after that you will post the tweet.

Next time :

 

you will not have to face the login page again. you can directly post your tweet.

Thanks

Pawan 

Contributor
praveennagsethiya
Posts: 20
Registered: ‎05-21-2012
My Device: NA

Re: twitter integration with my app -

thanking you for reply.........

 

but i want login page again and again then what i do changes in your code.

 

sir please reply. its very urgent

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

Re: twitter integration with my app -

HI Praveen

 

If you want login page again and again. Then don't store the token value.

 

If you don't store the token, then you will get login page again and again

 

 

Pawan

Thanks

Contributor
praveennagsethiya
Posts: 20
Registered: ‎05-21-2012
My Device: NA

Re: twitter integration with my app -

thanking you for reply.

 

sir if i dont save tokan value then run time exception shown.sir please make changes in your code .sir i am a new blackberry developer.so please reply with code.

 

 

thanking you sir 

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

Re: twitter integration with my app -

[ Edited ]

Hi Praveen

package app.screen;

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.EditField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.MainScreen;

import com.twitterapime.rest.Credential;
import com.twitterapime.rest.TweetER;
import com.twitterapime.rest.UserAccountManager;
import com.twitterapime.search.Tweet;
import com.twitterapime.xauth.ui.OAuthDialogListener;
import com.twitterapime.xauth.ui.OAuthDialogWrapper;

public class TwitterScreen extends MainScreen  {

	private final String CONSUMER_KEY =" ";
	private final String CONSUMER_SECRET =  ";
	private final String CALLBACK_URL =" ";
	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) {

				 	showAuthBrowserScreen.doAuth( null );
					UiApplication.getUiApplication().pushScreen(showAuthBrowserScreen);
			 
				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;
	 
			UiApplication.getUiApplication().invokeLater( new Runnable() {

				public void run() {
					deleteAll();
					doTweet("This days is lucky for me.", token);
					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 );				
			}
		});
	}

	public void doTweet( String message, Token token )
	{
		Credential c = new Credential(CONSUMER_KEY,	CONSUMER_SECRET, token);
		UserAccountManager uam = UserAccountManager.getInstance(c);

		try 
		{
			if (uam.verifyCredential()) 
			{
				TweetER.getInstance(uam).post(new Tweet( message ));
				updateScreenLog("Tweet posted!");
			}
		}
		catch (Exception e) 
		{
			Dialog.alert("Error by posting tweet."+e.getMessage());
			updateScreenLog("Error by posting tweet.");
		}
	}
}

 

Thanks 

Contributor
praveennagsethiya
Posts: 20
Registered: ‎05-21-2012
My Device: NA

Re: twitter integration with my app -

sir I am very very thankful to you..........

 

but sir that code run on device after click button login page open.after login goes to callback url.first time post on wall.but second time show on error:- by posting tweet.unterminated entity ref(position:TEXT??vk0?8..........@1.45 in java.io.inputstream Reader @27c60cb5).

 

sir please help me

 

thanking you