How to start another apps when click a button? - blackberry

I want to start another apps when I click this button.
sharebtn = new Custom_ButtonField(share, shareactive, shareactive) {
protected boolean navigationClick(int status, int time) {
//I want to start another apps (Strawberry)
return true;
}
};
add(sharebtn);
Here is the Strawberry Apps
public class StrawBerry extends UiApplication implements ActionListener {
public static void main(String url) {
new StrawBerry(url).enterEventDispatcher();
}
}
I want to pass String url to Strawberry apps. How can I achieve this?

First your main method won't be never called by system. The right signature:
public static void main(String[] arguments){}
Take a look on this article to launch another app with parameters : How To - Launch a third-party application from another third-party application
To post on FB page. You need something like:
private final String NEXT_URL = "http://www.facebook.com/connect/login_success.html";
private final String APPLICATION_ID = "your id";
private final String APPLICATION_SECRET = "your secret";
private Facebook fb;
private User user;
...
fb = Facebook.getInstance(new ApplicationSettings(NEXT_URL, APPLICATION_ID, APPLICATION_SECRET, Facebook.Permissions.PUBLISH_STREAM));
user = fb.getUser(pUserId);
user.publishPost(messageEditField.getText(), linkEditField.getText(), pictureEditField.getText(), nameEditField.getText(), captionEditField.getText(), descriptionEditField.getText(), sourceEditField.getText());

Related

How to get Shared preferences in doInBackground method of AsyncTask

I am building a data transfer app using direct Wifi. I am getting the string value of extension from Uri in the onActivityResult method and storing it in Shared preferences.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
String extension;
Uri uri = data.getData();
Context context = getActivity().getApplicationContext();
extension = "."+getMimeType(context, uri);
SharedPreferences sharedPreferences = myContext.getSharedPreferences(myName, MODE_PRIVATE);
SharedPreferences.Editor myEdit = sharedPreferences.edit();
myEdit.putString("hello", extension);
myEdit.apply();
}
It is working fine till now as the value of extension is storing in shared preferences successfully. Now, in the onConnectionInfoAvailable method (related to the broadcast receiver), I am calling an AsyncTask.
#Override
public void onConnectionInfoAvailable(final WifiP2pInfo info) {
new FileServerAsyncTask().execute();
}
Now, I want to get the shared preference value in doInBackground method of AsyncTask. But I am not getting the value of extension from shared preferences, although my code is working fine. Please help.
public static class FileServerAsyncTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
try {
SharedPreferences sh = myContext.getSharedPreferences(myName, MODE_PRIVATE);
String extension = sh.getString("hello", "no");
}....
Note: myContext and myName are defined as public static variables.

Where do I specify the user I want to follow in twitter hbc

Hey I would like to have the latest tweets from certain users that I will follow to be displayed on a page of my web app. So I followed the tutorial on the git of horsebird client but I don't know where I have to specify the users I want the messages from.
public class TwitterLatestTweets implements Runnable {
private final static String BUNDLE_BASENAME = "configuration.twitter";
private final static String CONSUMER_KEY = ResourceBundle.getBundle(
BUNDLE_BASENAME).getString("consumerKey");
private final static String CONSUMER_SECRET = ResourceBundle.getBundle(
BUNDLE_BASENAME).getString("consumerSecret");
private final static String TOKEN = ResourceBundle.getBundle(
BUNDLE_BASENAME).getString("token");
private final static String SECRET = ResourceBundle.getBundle(
BUNDLE_BASENAME).getString("secret");
private List<String> msgList = new ArrayList<String>();
#Override
public void run() {
/**
* Set up your blocking queues: Be sure to size these properly based on
* expected TPS of your stream
*/
BlockingQueue<String> msgQueue = new LinkedBlockingQueue<String>(100000);
BlockingQueue<Event> eventQueue = new LinkedBlockingQueue<Event>(1000);
/**
* Declare the host you want to connect to, the endpoint, and
* authentication (basic auth or oauth)
*/
Hosts hosebirdHosts = new HttpHosts(Constants.STREAM_HOST);
StatusesFilterEndpoint hosebirdEndpoint = new StatusesFilterEndpoint();
Authentication hosebirdAuth = new OAuth1(CONSUMER_KEY, CONSUMER_SECRET,
TOKEN, SECRET);
ClientBuilder builder = new ClientBuilder().hosts(hosebirdHosts)
.authentication(hosebirdAuth).endpoint(hosebirdEndpoint)
.processor(new StringDelimitedProcessor(msgQueue))
.eventMessageQueue(eventQueue);
Client hosebirdClient = builder.build();
hosebirdClient.connect();
while (!hosebirdClient.isDone()) {
try {
String msg = msgQueue.take();
msgList.add(msg);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
hosebirdClient.stop();
for (String s : msgList) {
System.out.println(s);
}
}
}
}
Is it Constants.STREAM_HOST ? Could you give me an example with the white house twitter (https://twitter.com/whitehouse) ?
You need to add a list of userIds to your endpoint, like this:
hosebirdEndpoint.followings(userIds);
You've got several examples here, in the same github project you've provided in your question. This one uses the same endpoint as in your post.
In here you can find Twitter's documentation on the endpoint, and the full list of the parameters you can use.

how to pause and resume a download in javafx

I am building a download manager in javafx
I have added function to download button which initialises new task.More than one download is also being executed properly.
But I need to add pause and resume function. Please tell how to implement it using executor. Through execute function of Executors, task is being started but how do i pause & then resume it??
Below I am showing relevant portions of my code. Please tell if you need more details. thanks.
Main class
public class Controller implements Initializable {
public Button addDownloadButton;
public Button pauseResumeButton;
public TextField urlTextBox;
public TableView<DownloadEntry> downloadsTable;
ExecutorService executor;
#Override
public void initialize(URL location, ResourceBundle resources) {
// here tableview and table columns are initialised and cellValueFactory is set
executor = Executors.newFixedThreadPool(4);
}
public void addDownloadButtonClicked() {
DownloadEntry task = new DownloadEntry(new URL(urlTextBox.getText()));
downloadsTable.getItems().add(task);
executor.execute(task);
}
public void pauseResumeButtonClicked() {
//CODE FOR PAUSE AND RESUME
}
}
DownloadEntry.java
public class DownloadEntry extends Task<Void> {
public URL url;
public int downloaded;
final int MAX_BUFFER_SIZE=50*1024;
private String status;
//Constructor
public DownloadEntry(URL ur) throws Exception{
url = ur;
//other variables are initialised here
this.updateMessage("Downloading");
}
#Override
protected Void call() {
file = new RandomAccessFile(filename, "rw");
file.seek(downloaded);
stream = con.getInputStream();
while (status.equals("Downloading")) {
byte buffer=new byte[MAX_BUFFER_SIZE];
int c=stream.read(buffer);
if (c==-1){
break;
}
file.write(buffer,0,c);
downloaded += c;
status = "Downloading";
}
if (status.equals("Downloading")) {
status = "Complete";
updateMessage("Complete");
}
return null;
}
}
You may be interested in Concurrency in JavaFX.
I guess you should also have a look at pattern Observer.
By the way I think you should not use constant string as a status ("Downloading", etc), creating an enum would be a better approach.
In your loop, around the read/write part, there should be a synchronization mechanism, controlled by your pause/resume buttons (see the two links).

RabbitMQ: Publishing from an ASP.NET MVC application

My understanding is that IModel instances are reasonably cheap to create and that's what I started with. I was creating a separate IModel for each class that was ever using it: each Application Service class gets its own IModel, as does every Controller. It was working fine, but having 30+ channels open was a bit worrisome.
I thought about serializing access to a shared IModel:
lock(publisherLock)
publisherModel.BasicPublish(...);
but now there's a point of contention for no good reason.
So, what will be the correct way of publishing messages into a RabbitMQ exchange from an ASP.NET MVC application?
What you must not do is allow a channel to be used by more than one thread, so keeping channels open over several requests is a bad idea.
IModel instances are cheap to create, but not free, so there are a couple of approaches you can take:
The safest thing to do is simply to create a channel each time you want to publish and close it again straight away. Something like this:
using(var model = connection.CreateModel())
{
var properties = model.CreateBasicProperties();
model.BasicPublish(exchange, routingKey, properties, msg);
}
You can keep the connection open for the lifetime of the application, but be sure to detect if you loose the connection and have code to reconnect.
The downside with this approach is that you have the overhead of creating a channel for each publish.
The alternative is to hold a channel open on a dedicated publishing thread and marshal all your publish calls onto that thread using a BlockingCollection or similar. This will be more efficient, but more complex to implement.
Here is something which you can use,
BrokerHelper.Publish("Aplan chaplam, chaliye aai mein :P");
and below is the defination for the BrokerHelper class.
public static class BrokerHelper
{
public static string Username = "guest";
public static string Password = "guest";
public static string VirtualHost = "/";
// "localhost" if rabbitMq is installed on the same server,
// else enter the ip address of the server where it is installed.
public static string HostName = "localhost";
public static string ExchangeName = "test-exchange";
public static string ExchangeTypeVal = ExchangeType.Direct;
public static string QueueName = "SomeQueue";
public static bool QueueExclusive = false;
public static bool QueueDurable = false;
public static bool QueueDelete = false;
public static string RoutingKey = "yasser";
public static IConnection Connection;
public static IModel Channel;
public static void Connect()
{
var factory = new ConnectionFactory();
factory.UserName = Username;
factory.Password = Password;
factory.VirtualHost = VirtualHost;
factory.Protocol = Protocols.FromEnvironment();
factory.HostName = HostName;
factory.Port = AmqpTcpEndpoint.UseDefaultPort;
Connection = factory.CreateConnection();
Channel = Connection.CreateModel();
}
public static void Disconnect()
{
Connection.Close(200, "Goodbye");
}
public static bool IsBrokerDisconnected()
{
if(Connection == null) return true;
if(Connection.IsOpen) return false;
return true;
}
public static void Publish(string message)
{
if (IsBrokerDisconnected()) Connect();
Channel.ExchangeDeclare(ExchangeName, ExchangeTypeVal.ToString());
Channel.QueueDeclare(QueueName, QueueDurable, QueueExclusive, QueueDelete, null);
Channel.QueueBind(QueueName, ExchangeName, RoutingKey);
var encodedMessage = Encoding.ASCII.GetBytes(message);
Channel.BasicPublish(ExchangeName, RoutingKey, null, encodedMessage);
Disconnect();
}
}
Further reading : Introduction to RabbitMQ with C# .NET, ASP.NET and ASP.NET MVC with examples

Twitter Follow Link

How do I create a link that will automatically make a user follow a certain Twitter user if they're logged in or send them to Twitter to login first if they're not? I had found how to do this about month or 2 ago but can't find it again. I think it was something basic like a link or a form post to something like twitter.com/[user]/follow.
I've looked at the API, but I'd need the user to authenticate themselves on my site, and I don't want to deal with that. I just want them to authenticate directly on Twitter and not worry about it. The way I had found was nice and simple and I just want to find that again.
Use Twitter's web intents.
While you can use the follow button, you can also send users directly to the Intent URL, like so:
https://twitter.com/intent/user?screen_name=NASA
how to use twitter api in my android application to implement follow button only
Android
http://code.google.com/p/android-hackathon-in-fukuoka/source/browse/trunk/sodefuri/src/jp/jagfukuoka/sodefuri/TimeLineActivity.java?spec=svn167&r=167
Code Snip: (I have converted chines string into standard English)
public class TimeLineActivity extends ListActivity {
private TwitterPreferenceManager tpm = new TwitterPreferenceManager(this);
private static final int FOLLOW = 1;
private static final CharSequence FOLLOW_LABEL = "Follow";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// timeline Obtaining process
String screenName = getIntent().getStringExtra("screen_name");
List<String> list = this.getTimeLine(screenName);
setListAdapter(new ArrayAdapter<String>(this, R.layout.timeline_item,list));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, FOLLOW, 0, FOLLOW_LABEL);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case FOLLOW:
ConfigurationBuilder builder = new ConfigurationBuilder();
Configuration conf = builder.setOAuthAccessToken(tpm.getAccessToken())
.setOAuthAccessTokenSecret(tpm.getAccessTokenSercret())
.setOAuthConsumerKey(TwitterPreferenceManager.CONSUMER_KEY)
.setOAuthConsumerSecret(TwitterPreferenceManager.CONSUMER_SERCRET)
.setDebugEnabled(true)
.build();
Twitter twitter = new TwitterFactory(conf).getInstance();
try {
String screen_name = getIntent().getStringExtra("screen_name");
twitter.createFriendship(screen_name);
Toast.makeText(getApplicationContext(), "Was to follow.", Toast.LENGTH_LONG).show();
} catch (TwitterException e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
/**
* Get the time line for the specified user
*
* #param screenName
* #return
*/
private List<String> getTimeLine(String screenName) {
List<String> result = new ArrayList<String>();
Twitter twitter = new TwitterFactory().getInstance();
ResponseList<Status> userTimeline;
try {
userTimeline = twitter.getUserTimeline(screenName);
for (Status status : userTimeline) {
result.add(status.getText());
}
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}
iPhone
http://www.chrismaddern.com/twitter-follow-button-for-ios-iphone-code/
Here is the way, How todo
The FollowMeButton can be created in Interface Builder by adding a UIButton and changing it's class to FollowMeButton or in code using the custom initialiser:
[self.view addSubview:[[FollowMeButton alloc] initWithTwitterAccount:#"chrismaddern" atOrigin:CGPointMake(205, 248) isSmallButton:YES]];
Two size modes are available controlled by setting isSmallButton in the initialiser or by later change the isSmall property of the object.

Resources