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
babakar
Posts: 742
Registered: ‎05-29-2012
My Device: see later

facebook/twiter in your app

how can I from my application do posts to facebook twitter etc.

 

 

thanky ou

Please use plain text.
Developer
babakar
Posts: 742
Registered: ‎05-29-2012
My Device: see later

Re: facebook/twiter in your app

package mypackage;
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());
		}
	}
}

 

package mypackage;

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;
	}

}

 

package mypackage;

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;  
    }  
}

 

package mypackage;

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



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

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

 

package mypackage;

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();
		}
	}
}
}

 

package mypackage;

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


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 mypackage;

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;
	} 
	
}

 

 

package mypackage;

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;

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 );				
			}
		});
	}
   
}

 

 

USED THIS CODE, I GET

 

 

I enter application, i get this  http://postimage.org/image/72n0rx577/

 

I click tweet i get this http://postimage.org/image/41t7xnyl9/

 

The while processing i get this http://postimage.org/image/rhb530icd/

 

 

Please use plain text.
Developer
babakar
Posts: 742
Registered: ‎05-29-2012
My Device: see later

Re: facebook/twiter in your app

I want on click of twitter, to enter twitter login form... if user logged in before ( save in mysqllite database) i dont log him...just let him tweet message he wants to a friend ... working on tweet, then will see facebook as well
Please use plain text.
Developer
babakar
Posts: 742
Registered: ‎05-29-2012
My Device: see later

Re: facebook/twiter in your app

here is my requirement, he clicks on tweet... i tweet or post on facebook walll automatic message

Twitter Message:
[TwitterUserName] is listening to [TrackName] on http:djjf.fm #np


Facebook Message:
[FacebookUserName] is listening to [TrackName] on http://ssa.fm
Note:
You should also send cover photo of the album being played (Check this with the Facebook and Twitter SDK for Blackberry).
The SDK may require you to supply a URL for the photo, use the following function to get cover URL: GetUrlImage (AlbumId).
Please use plain text.