ANDROID - update status linked-in (in app's Background) - android

I am makeing one android app.
I have list of product.
If i choose one product at that time that product share on Linkedin with user name.
I want this like below code(sample code of twitter share). I want same for Linkedin.
private final static Handler mTwitterHandler = new Handler();
private static SharedPreferences prefs;
public static boolean TWEET_LOGIN = false;
final static Runnable mUpdateTwitterNotification = new Runnable() {
public void run() {
}
};
public static void sendTweet(Context con, final String msj) {
prefs = PreferenceManager.getDefaultSharedPreferences(con);
Thread t = new Thread() {
public void run() {
try {
TwitterUtils.sendTweet(prefs, msj);
mTwitterHandler.post(mUpdateTwitterNotification);
} catch (Exception ex) {
ex.printStackTrace();
Log.d("dhaval-->send tweet:", ex.getMessage().toString());
}
}
};
t.start();
}
It is possible or not if yes then how?

I have used linkedin-j-android.jar download
put this code in to AsyncTask for do in background
private void shareText_new() {
// TODO Auto-generated method stub
try {
final LinkedInApiClientFactory factory = LinkedInApiClientFactory
.newInstance(generalClass.APIKEY, generalClass.APISECRET);
final LinkedInApiClient client = factory.createLinkedInApiClient(
generalClass._Token1, generalClass._Secret1);
client.postNetworkUpdate("hello DJ");
System.out
.println("Your update has been posted. Check the LinkedIn site for confirmation.");
System.out.println("Fetching your network updates of type:"
+ NetworkUpdateType.STATUS_UPDATE);
Network network = client.getNetworkUpdates(EnumSet
.of(NetworkUpdateType.STATUS_UPDATE));
printResult(network);
} catch (Exception e) {
// TODO: handle exception
Log.e("error share st--->", "" + e.getMessage().toString());
}
}
reference link checkit
fullCode

Related

Get a string value out of a thread

I have a String variable, and I set it's value inside a thread, since it's using a netwok operation.
How can I access the values stored in the Strings?
public class HomeActivity extends AppCompatActivity {
// Initialize AWS DynamoDB Client
public static AmazonDynamoDBClient ddbClient;
public static DynamoDBMapper mapper;
public static Aqua aqua;
// App details
public static String a = "A";
public static String b;
public static Boolean c;
public static String d;
public static String e;
public static String f;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
// Initialize the Amazon Cognito credentials provider
CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
getApplicationContext(),
"******", // Identity Pool ID
Regions.**** // Region
);
// Initialize AWS DynamoDB
ddbClient = new AmazonDynamoDBClient(credentialsProvider);
mapper = new DynamoDBMapper(ddbClient);
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
// Get app details
aqua = mapper.load(Aqua.class, a);
b = aqua.getB();
c = aqua.getC();
d = aqua.getD();
e = aqua.getE();
f = aqua.getF();
} catch (Exception e) {
Log.e("error", e.getMessage());
}
}
});
thread.start();
}
}
Use ExecutorService and submit Callable (below assumes you want the data that is stored inside b,c,d,e,f):
ExecutorService exec = Executors.newSingleThreadExecutor();
Future<String[]> future = exec.submit(new Callable<String[]>() {
#Override
public String[] call() {
try {
// Get app details
aqua = mapper.load(Aqua.class, a);
b = aqua.getB();
c = aqua.getC();
d = aqua.getD();
e = aqua.getE();
f = aqua.getF();
} catch (Exception e) {
Log.e("error", e.getMessage());
}
return new String[] {b, c, d, e, f};
}
});
// ... b will be at value[0], c at value[1]
String[] value = future.get();
Declare the string globally in your Activity/Fragment. This way you can acces it from everywhere.
You could also use handler.sendMessage(message); with your String as message to send it whenever your Thread has finished or whenever you want to. You can then retrieve your String int
protected Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
String status = (String) msg.obj;
Log.i("Got a new message", "MESSAGE: "+status);
}
};
Hope it helps :)

Simple SignalR Android Example Issue

I am basically trying to send a message from my android to my server and the server to send back a response to my android app. I followed THIS tutorial.
Just a simple exercise to introduce myself in to SignalR using Azure Web API and Android.
My Complete Server code in C#:
public class TestHub: Hub {
public void SendMessage(string name, string message) {
// Call the broadcastMessage method to update clients.
Clients.All.broadcastMessage(name, message);
}
public void SendClientMessage(CustomType obj) {
Clients.All.broadcastMessage("From Server", "Server got the message bro");
}
public class CustomType {
public string Name;
public int Id;
}
}
Complete Android Java code:
public class MainActivity extends AppCompatActivity {
Handler handler;
TextView statustext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler();
statustext = (TextView) findViewById(R.id.status);
Platform.loadPlatformComponent(new AndroidPlatformComponent());
// Change to the IP address and matching port of your SignalR server.
String host = "https://My-Service-name.azure-mobile.net/";
HubConnection connection = new HubConnection(host);
HubProxy hub = connection.createHubProxy("TestHub");
SignalRFuture < Void > awaitConnection = connection.start();
try {
awaitConnection.get();
} catch (InterruptedException e) {
} catch (ExecutionException e) {
}
hub.subscribe(this);
try {
hub.invoke("SendMessage", "Client", "Hello Server!").get();
hub.invoke("SendClientMessage",
new CustomType() {
{
Name = "Android Homie";
Id = 42;
}
}).get();
} catch (InterruptedException e) {
} catch (ExecutionException e) {
}
}
//I have no idea what the following method is for. Just followed the tutorial.. (blindly)
public void UpdateStatus(String status) {
final String fStatus = status;
handler.post(new Runnable() {
#Override
public void run() {
statustext.setText(fStatus);
}
});
}
public class CustomType {
public String Name;
public int Id;
}
}
Problems with this:
1. I get an exception:
java.util.concurrent.ExecutionException:
microsoft.aspnet.signalr.client.transport.NegotiationException: There
was a problem in the negotiation with the server
2. I feel like I haven't properly called the server from the Java code.
Should the URL be:
https://My-Service-name.azure-mobile.net/
or
https://My-Service-name.azure-mobile.net/api/signalr
Can someone clarify these doubts and help me set it up?

how to implement Pub-Sub Network with a Proxy by using XPUB and XSUB in ZeroMQ(jzmq) 3.xx

I am trying to implement using XPUB and XSUB as provided in this below figure. I have gone through their examples provided but could not get one for XPUB and XSUB in Java. Here they have given an example in C which is little complex as I am new to ZeroMQ.
I am trying to use it in android using jni wrapped version. Please help me to find an example, how to implement this Pub-Sub Network with a Proxy in ZeroMQ using java.
Currently I am referring http://zguide.zeromq.org/page:all
I have tried to port it as follows.
Subscriber.java
public class Subscriber extends Thread implements Runnable {
private static final String TAG = "Subscriber";
private Context ctx;
public Subscriber(ZMQ.Context z_context) {
this.ctx = z_context;
}
#Override
public void run() {
super.run();
ZMQ.Socket mulServiceSubscriber = ctx.socket(ZMQ.SUB);
mulServiceSubscriber.connect("tcp://localhost:6001");
mulServiceSubscriber.subscribe("A".getBytes());
mulServiceSubscriber.subscribe("B".getBytes());
while (true) {
Log.d(TAG, "Subscriber loop started..");
String content = new String(mulServiceSubscriber.recv(0));
Log.d(TAG, "Subscriber Received : "+content);
}
}
}
Publisher.java
public class Publisher extends Thread implements Runnable {
private static final String TAG = "Publisher";
private Context ctx;
public Publisher(ZMQ.Context z_context) {
this.ctx = z_context;
}
#Override
public void run() {
super.run();
ZMQ.Socket publisher = ctx.socket(ZMQ.PUB);
publisher.connect("tcp://localhost:6000");
while (true) {
Log.d(TAG, "Publisher loop started..");
publisher.send(("A Hello " + new Random(100).nextInt()).getBytes() , 0);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
XListener.java (For now a simple Forwarder)
public class XListener extends Thread implements Runnable {
private static final String TAG = null;
private Socket publisherX;
private Context ctx;
private Socket subscriberX;
public XListener(ZMQ.Context ctx, ZMQ.Socket subscriberX,
ZMQ.Socket publisherX) {
this.ctx = ctx;
this.subscriberX = subscriberX;
this.publisherX = publisherX;
}
#Override
public void run() {
super.run();
while (true) {
Log.d(TAG, "XListener loop started..");
String msg = new String(subscriberX.recvStr());
Log.v(TAG, "Listener Received: " +"MSG :"+msg);
publisherX.send(msg.getBytes(), 0);
}
}
}
in application main()
private void main() {
ZMQ.Context ctx = ZMQ.context(1);
ZMQ.Socket subscriberX = ctx.socket(ZMQ.XSUB);
subscriberX.bind("tcp://*:6000");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ZMQ.Socket publisherX = ctx.socket(ZMQ.XPUB);
publisherX.bind("tcp://*:6001");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new XListener(ctx, subscriberX, publisherX).start();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new XSender(ctx, subscriberX, publisherX).start();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new Subscriber(ctx).start();
new Publisher(ctx).start();
}
With the code I am not able to listen XSUB. While porting espresso.c, I was not able to find any wrapper in java bindings of ZMQ. How to implement a simple proxy or am I missing something??
Wow I'm answering my own question. I missed to add a forwarder from publisherX to subscriberX. Here is the missing code. Now XSUB and XPUB are able to send and get data.
public class XSender extends Thread implements Runnable {
private static final String TAG = null;
private Socket publisherX;
private Context ctx;
private Socket subscriberX;
public XSender(ZMQ.Context ctx, ZMQ.Socket subscriberX,
ZMQ.Socket publisherX) {
this.ctx = ctx;
this.subscriberX = subscriberX;
this.publisherX = publisherX;
}
#Override
public void run() {
super.run();
while (true) {
// Read envelope with address
Log.d(TAG, "XListener loop started..");
String msg = new String(subscriberX.recv(0));
Log.v(TAG, "Listener Received: " +"MSG :"+msg);
publisherX.send(msg.getBytes(), 0);
}
}
}

Issue about using Async with an Android Client

I am currently creating a project that needs to have a simple async task to take care of a thread running behind the scenes. The user needs to login. I am using another class called PVAndroid Client that supplies useful methods and has an XML serializer form packets for me. I am completely new to working with threads or doing anything with servers, so this may be completely wrong or somewhat right.
I get the data the user entered: the ip address and port, their username (I split this into first and last name), their region they selected. I encrypt their password, and attempt to connect to the tcp using ip address and port number. I am trying to work in the async task but am kind of confused on what I should do. Can anyone guide me in the right direction and help me out?
Thank you I really appreciate it.
private TcpClient myTcpClient = null;
private UdpClient udpClient;
private static final String USERNAME_SHARED_PREFS = "username";
private static final String PASSWORD_SHARED_PREFS = "password";
private static final String IP_ADDRESS_SHARED_PREFS = "ipAddressPref";
private static final String PORT_SHARED_PREFS = "portNumberPref";
private String encryptedNameLoginActivity, encryptPassLoginActivity;
private EditText userText, passText;
private String getIpAddressSharedPrefs, getPortNumberPrefs;
private String getUserNameValue;
private String getPasswordValue;
private String fName, lName;
private SharedPreferences settings;
private Editor myEditor;
private boolean getCheckedRemember;
private boolean resultCheck = false;
private int portNum;
private Button submitButton;
private String userMACVARIABLE = "";
private String regionSelected, gridSelected;
private Spinner regSpinner, gridSpinner;
PVDCAndroidClient client;
private int userNum;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
client = new PVDCAndroidClient();
}
#Override
protected void onStart() {
super.onStart();
// Take care of getting user's login information:
submitButton = (Button) findViewById(R.id.submitButton);
userText = (EditText) findViewById(R.id.nameTextBox);
passText = (EditText) findViewById(R.id.passwordTextBox);
regSpinner = (Spinner) findViewById(R.id.regionSpinner);
// grid selected as well? sometime?
regSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View v,
int position, long rowId) {
regionSelected = regSpinner.getItemAtPosition(position)
.toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
submitButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
settings = PreferenceManager
.getDefaultSharedPreferences(AndroidClientCompnt.this);
getIpAddressSharedPrefs = settings.getString(
IP_ADDRESS_SHARED_PREFS, "");
portNum = Integer.parseInt(settings.getString(
PORT_SHARED_PREFS, ""));
if (getIpAddressSharedPrefs.length() != 0 && portNum != 0) {
if (userText.length() != 0 && passText.length() != 0) {
try {
try {
// encrypting the user's password.
encryptPassLoginActivity = Secure.encrypt(passText
.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// first connect attempt.
myTcpClient = new TcpClient();
myTcpClient.connect(getIpAddressSharedPrefs,
portNum);
// here is where I want to call Async to do login
// or do whatever else.
UploadTask task = new UploadTask();
task.execute();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"Could not connect.", Toast.LENGTH_LONG)
.show();
e.printStackTrace();
}
}
}
}
});
}
private class UploadTask extends AsyncTask<String, Integer, Void>
{
#Override
protected void onPreExecute() {
Toast.makeText(getApplicationContext(), "Loading...",
Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(String... names) {
resultCheck = myTcpClient.connect(getIpAddressSharedPrefs,
portNum);
if (resultCheck == true) {
while (myTcpClient.getUserNum() < 0) {
// num set? session? with proxy server?
}
String[] firstAndLast;
String spcDelmt = " ";
firstAndLast = userText.toString().split(spcDelmt);
fName = firstAndLast[0];
lName = firstAndLast[1];
// set up the tcp client to sent the information to the
// server.
client.login(fName, lName, encryptPassLoginActivity,regionSelected, 128, 128, 20);
} else {
Toast.makeText(getApplicationContext(),
"Connection not successful", Toast.LENGTH_LONG)
.show();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
Toast.makeText(getApplicationContext(), "Connected",
Toast.LENGTH_LONG).show();
}
}
}
First
#Override
protected Void doInBackground(String...params) {
new Thread (new Runnable() {
// ...
}
}
Never do this again. There is no need to create new Thread in doInBackground method which actually running on background Thread. So remove it.
The advice to you is tricky because you need to read about Threads, work with Connection etc. So the best advice to you is to read some tutorials, examples of basic applications and read references. So you can start here:
Android TCP Client and Server Communication Programming–Illustrated with Example
I cannot see, where you are yoursing your Task, but I see that you are doing something weired inside doInBackground()! There is absolutely NO reason, to create your own Thread inside it.
remove that, and you could just use your Task like this:
UploadTask task = new UploadTask();
task.execute("someString", "anotherString", "addAsManyStringsYouNeed");
The docs from AsyncTask are very helpfull, too.

Android: Can't post tweet using OAuth and twitter

I am trying to send tweets to twitter via my android app. The libraries I'm using are signpost core, signpost commonshttp, and jtwitter. My code in my main activity is as follows:
public class MainActivity extends Activity implements View.OnClickListener {
static final String TAG = "TweetExample";
private Twitter twitter;
SharedPreferences prefs;
private EditText textStatus;
private static final String CONSUMER_KEY = "my key";
private static final String CONSUMER_SECRET = "my secret";
private static String ACCESS_KEY = null;
private static String ACCESS_SECRET = null;
private static final String REQUEST_URL = "http://twitter.com/oauth/request_token";
private static final String ACCESS_TOKEN_URL = "http://twitter.com/oauth/access_token";
private static final String AUTH_URL = "http://twitter.com/oauth/authorize";
private static final String CALLBACK_URL = "TweetExample://twitt";
private static CommonsHttpOAuthConsumer consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
private static CommonsHttpOAuthProvider provider = new CommonsHttpOAuthProvider
(REQUEST_URL, ACCESS_TOKEN_URL, AUTH_URL);
//Called when the activity is first created.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Retrieve the shared preferences
prefs = getSharedPreferences(USER_PREFERENCES,
Context.MODE_PRIVATE);
// Find views by id
ImageView buttonUpdate = (ImageView) findViewById(R.id.ImageView_Update);
textStatus = (EditText) findViewById(R.id.textStatus);
ImageView btnLogin = (ImageView) findViewById(R.id.ImageView_Twit);
// Add listener
buttonUpdate.setOnClickListener(this);
btnLogin.setOnClickListener(this);
// Initialize preferences
prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences arg0, String arg1) {
twitter = null;
}
});
}
public void onClick(View v) {
switch(v.getId()){
case R.id.ImageView_Update:
String status = textStatus.getText().toString();
String message = "Status set to: " + status;
Log.d(TAG, message);
// Ignore empty updates
if (status.length() == 0)
return;
// Connect to twitter.com and update your status
try {
Log.d(TAG, "1");
twitter.setStatus(status);
Log.d(TAG, "2");
} catch (TwitterException e) {
Log.e(TAG, "Twitter exception: " + e);
}
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
break;
case R.id.ImageView_Twit:
try {
String authURL = provider.retrieveRequestToken(consumer, CALLBACK_URL);
Log.d(TAG, authURL);
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authURL)));
} catch (OAuthMessageSignerException e) {
e.printStackTrace();
} catch (OAuthNotAuthorizedException e) {
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
e.printStackTrace();
} catch (OAuthCommunicationException e) {
e.printStackTrace();
}
break;
}
}
#Override
public void onResume() {
super.onResume();
Uri uri = this.getIntent().getData();
if (uri != null && uri.toString().startsWith(CALLBACK_URL)) {
Log.d(TAG, uri.toString());
String verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);
Log.d(TAG, verifier);
try {
provider.retrieveAccessToken(consumer, verifier);
ACCESS_KEY = consumer.getToken();
ACCESS_SECRET = consumer.getTokenSecret();
Log.d(TAG, ACCESS_KEY);
Log.d(TAG, ACCESS_SECRET);
} catch (OAuthMessageSignerException e) {
e.printStackTrace();
} catch (OAuthNotAuthorizedException e) {
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
e.printStackTrace();
} catch (OAuthCommunicationException e) {
e.printStackTrace();
}
}
}
I know the callback url is right. Could it be that I authenticate using signpost and try to tweet using jtwitter? Right now, I can sign into twitter to authorize the app and get redirected back to my app, but when I type something in to try to post to twitter it gets as far as twitter.setStatus(status);
Any help would be greatly appreciated.
Possibly I'm being blind, or you forgot to include some code, but it looks like the Twitter object is never constructed. So you'd get a NullPointerException when you come to use it.
Somewhere you want code along the lines of:
OAuthSignpostClient oauthClient = new OAuthSignpostClient(app_token, app_secret, user_access_token, user_secret);
Twitter twitter = new Twitter(null, oauthClient);

Categories

Resources