how to post message on wall on LinkedIn in android - android

i'm using Selvin's code in my apps..but not getting how to post a message on wall..
here is my code..
i have refer this link for Integration Here Posting LinkedIn message from Android application
package pl.osadkowski.LITest;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import com.google.code.linkedinapi.client.LinkedInApiClient;
import com.google.code.linkedinapi.client.LinkedInApiClientException;
import com.google.code.linkedinapi.client.LinkedInApiClientFactory;
import com.google.code.linkedinapi.client.oauth.LinkedInAccessToken;
import com.google.code.linkedinapi.client.oauth.LinkedInOAuthService;
import com.google.code.linkedinapi.client.oauth.LinkedInOAuthServiceFactory;
import com.google.code.linkedinapi.client.oauth.LinkedInRequestToken;
import com.google.code.linkedinapi.schema.Person;
public class LITestActivity extends Activity {
// /change keysssssssssssssssssssssssssssss!!!!!!!!!!
static final String CONSUMER_KEY = "6oj6vol2hva6";
static final String CONSUMER_SECRET = "rreH5PzHDgzXZMpq";
static final String APP_NAME = "LITest";
static final String OAUTH_CALLBACK_SCHEME = "x-oauthflow-linkedin";
static final String OAUTH_CALLBACK_HOST = "litestcalback";
static final String OAUTH_CALLBACK_URL = String.format("%s://%s",
OAUTH_CALLBACK_SCHEME, OAUTH_CALLBACK_HOST);
static final String OAUTH_QUERY_TOKEN = "oauth_token";
static final String OAUTH_QUERY_VERIFIER = "oauth_verifier";
static final String OAUTH_QUERY_PROBLEM = "oauth_problem";
final LinkedInOAuthService oAuthService = LinkedInOAuthServiceFactory
.getInstance().createLinkedInOAuthService(CONSUMER_KEY,
CONSUMER_SECRET);
final LinkedInApiClientFactory factory = LinkedInApiClientFactory
.newInstance(CONSUMER_KEY, CONSUMER_SECRET);
static final String OAUTH_PREF = "LIKEDIN_OAUTH";
static final String PREF_TOKEN = "token";
static final String PREF_TOKENSECRET = "tokenSecret";
static final String PREF_REQTOKENSECRET = "requestTokenSecret";
TextView tv = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tv = new TextView(this);
setContentView(tv);
final SharedPreferences pref = getSharedPreferences(OAUTH_PREF,
MODE_PRIVATE);
final String token = pref.getString(PREF_TOKEN, null);
final String tokenSecret = pref.getString(PREF_TOKENSECRET, null);
if (token == null || tokenSecret == null) {
startAutheniticate();
} else {
showCurrentUser(new LinkedInAccessToken(token, tokenSecret));
}
}
void startAutheniticate() {
final LinkedInRequestToken liToken = oAuthService
.getOAuthRequestToken(OAUTH_CALLBACK_URL);
final String uri = liToken.getAuthorizationUrl();
getSharedPreferences(OAUTH_PREF, MODE_PRIVATE).edit()
.putString(PREF_REQTOKENSECRET, liToken.getTokenSecret())
.commit();
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(i);
}
void finishAuthenticate(final Uri uri) {
if (uri != null && uri.getScheme().equals(OAUTH_CALLBACK_SCHEME)) {
final String problem = uri.getQueryParameter(OAUTH_QUERY_PROBLEM);
if (problem == null) {
final SharedPreferences pref = getSharedPreferences(OAUTH_PREF,
MODE_PRIVATE);
final LinkedInAccessToken accessToken = oAuthService
.getOAuthAccessToken(
new LinkedInRequestToken(uri
.getQueryParameter(OAUTH_QUERY_TOKEN),
pref.getString(PREF_REQTOKENSECRET,
null)),
uri.getQueryParameter(OAUTH_QUERY_VERIFIER));
pref.edit()
.putString(PREF_TOKEN, accessToken.getToken())
.putString(PREF_TOKENSECRET,
accessToken.getTokenSecret())
.remove(PREF_REQTOKENSECRET).commit();
showCurrentUser(accessToken);
} else {
Toast.makeText(this,
"Appliaction down due OAuth problem: " + problem,
Toast.LENGTH_LONG).show();
finish();
}
}
}
void clearTokens() {
getSharedPreferences(OAUTH_PREF, MODE_PRIVATE).edit()
.remove(PREF_TOKEN).remove(PREF_TOKENSECRET)
.remove(PREF_REQTOKENSECRET).commit();
}
void showCurrentUser(final LinkedInAccessToken accessToken) {
final LinkedInApiClient client = factory
.createLinkedInApiClient(accessToken);
try {
final Person p = client.getProfileForCurrentUser();
// /////////////////////////////////////////////////////////
// here you can do client API calls ...
// client.postComment(arg0, arg1);
// client.updateCurrentStatus(arg0);
// or any other API call (this sample only check for current user
// and shows it in TextView)
// /////////////////////////////////////////////////////////
tv.setText(p.getLastName() + ", " + p.getFirstName());
} catch (LinkedInApiClientException ex) {
clearTokens();
Toast.makeText(
this,
"Appliaction down due LinkedInApiClientException: "
+ ex.getMessage()
+ " Authokens cleared - try run application again.",
Toast.LENGTH_LONG).show();
finish();
}
}
#Override
protected void onNewIntent(Intent intent) {
finishAuthenticate(intent.getData());
}
}
plz provide me java and xml code as well...Thanks in advance

Once you got the accessToken just like you got in finishAuthenticate() method, write the following code to post update in any AsyncTask's doInBackground Method.
LinkedInApiClient client = factory.createLinkedInApiClient(accessToken);
client.postNetworkUpdate(YOUR_MESSAGE_STRING);
Simple, isn't it?

1.You can download source code from http://socialauth-android.googlecode.com/files/socialauth-android-sdk-3.0.zip .
2.Go to socialauth-android-sdk-3.0 -->examples, now import the share-button project.
3.Now go back to socialauth-android-sdk-3.0 --> src, now import socialauth-android as a library for share-button project.
4.Run the share-button project.

Follow Android LinkedIn OAuth implementation from
http://www.sourcetricks.com/2012/07/android-linkedin-oauth-implementation.html
you can also download the sample project from here..

Related

How to know that specific document is present in Cloudant Database using Android App

I have successfully created document in Cloudant database through my Android App. But I can not find a specific document present in Cloudant database. What I have tried is like below....
TabTwo_Fragment.java
package com.example.android02.insightapp11;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.cloudant.sync.datastore.BasicDocumentRevision;
import com.cloudant.sync.datastore.Datastore;
import com.cloudant.sync.datastore.DatastoreManager;
import com.cloudant.sync.datastore.DatastoreNotCreatedException;
import com.cloudant.sync.datastore.DocumentBodyFactory;
import com.cloudant.sync.datastore.DocumentException;
import com.cloudant.sync.datastore.DocumentNotFoundException;
import com.cloudant.sync.datastore.DocumentRevision;
import com.cloudant.sync.datastore.MutableDocumentRevision;
import com.cloudant.sync.replication.Replicator;
import com.cloudant.sync.replication.ReplicatorBuilder;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
/**
* A simple {#link Fragment} subclass.
*/
public class TabTwo_Fragment extends Fragment implements View.OnClickListener, SharedPreferences.OnSharedPreferenceChangeListener {
private static final String DATASTORE_MANGER_DIR = "data";
private static final String TASKS_DATASTORE_NAME = "tasks";
Datastore DataStore;
private Replicator PushReplicator, PullReplicator;
DocumentRevision revision;
static final String CLOUDANT_USER = "user_default";
static final String CLOUDANT_DB = "database_name";
static final String CLOUDANT_API_KEY = "api_key";
static final String CLOUDANT_API_SECRET = "api_key_pwd";
long TWITTER_ID = MainActivity.twitterID;
String TWITTER_NAME = MainActivity.userName;
Button btn_submit;
Spinner sp1, sp2, sp3, sp4, sp5, sp6, sp7, sp8;
TextView ans_total;
String user = "old";
HashMap<String, String> qa_hashmap;
public TabTwo_Fragment() {
// Required empty public constructor
}
public static TabTwo_Fragment newInstance() {
return new TabTwo_Fragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tabtwo_fragment, container, false);
try {
init(rootView);
} catch (DocumentNotFoundException e) {
} catch (DocumentException e) {
} catch (URISyntaxException e) {
}
return rootView;
}
void init(View rootView) throws DocumentException, URISyntaxException {
Log.e("init: ", "in init");
find_view_by_id(rootView);
registerClickEvents();
defaultConfig();
checkForRegisteredUser();
}
void find_view_by_id(View rootView) {
Log.e("find_view_by_id: ", "in find_view_by_id");
btn_submit = (Button) rootView.findViewById(R.id.btn_submit);
sp1 = (Spinner) rootView.findViewById(R.id.sp1);
sp2 = (Spinner) rootView.findViewById(R.id.sp2);
sp3 = (Spinner) rootView.findViewById(R.id.sp3);
sp4 = (Spinner) rootView.findViewById(R.id.sp4);
sp5 = (Spinner) rootView.findViewById(R.id.sp5);
sp6 = (Spinner) rootView.findViewById(R.id.sp6);
sp7 = (Spinner) rootView.findViewById(R.id.sp7);
sp8 = (Spinner) rootView.findViewById(R.id.sp8);
ans_total = (TextView) rootView.findViewById(R.id.ans_total);
}
void registerClickEvents() {
Log.e("registerClickEvents: ", "in registerClickEvents");
btn_submit.setOnClickListener(this);
}
void defaultConfig() {
Log.e("defaultConfig: ", "in defaultConfig");
PreferenceManager.setDefaultValues(getContext(), R.xml.preferences, false);
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
sharedPref.registerOnSharedPreferenceChangeListener(this);
File path = getContext().getDir(DATASTORE_MANGER_DIR, Context.MODE_PRIVATE);
DatastoreManager manager = new DatastoreManager(path.getAbsolutePath());
try {
DataStore = manager.openDatastore(TASKS_DATASTORE_NAME);
setUriPlusReplicators();
} catch (DatastoreNotCreatedException e) {
Toast.makeText(getContext(), "Unable to open Datastore!", Toast.LENGTH_SHORT).show();
} catch (URISyntaxException e) {
Toast.makeText(getContext(), "URI Exception!!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
try {
setUriPlusReplicators();
} catch (URISyntaxException e) {
}
}
void setUriPlusReplicators() throws URISyntaxException {
Log.e("setUriPlusReplicators: ", "in setUriPlusReplicators");
URI uri = this.createServerUri();
Log.e("URI: ", "" + uri);
PushReplicator = ReplicatorBuilder.push().from(DataStore).to(uri).build();
PushReplicator.getEventBus().register(this);
PullReplicator = ReplicatorBuilder.pull().to(DataStore).from(uri).build();
PullReplicator.getEventBus().register(this);
}
private URI createServerUri() throws URISyntaxException {
Log.e("createServerUri: ", "in createServerUri");
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
String username = sharedPref.getString(CLOUDANT_USER, "");
String dbName = sharedPref.getString(CLOUDANT_DB, "");
String apiKey = sharedPref.getString(CLOUDANT_API_KEY, "");
String apiSecret = sharedPref.getString(CLOUDANT_API_SECRET, "");
String host = username + ".cloudant.com";
return new URI("https", apiKey + ":" + apiSecret, host, 443, "/" + dbName, null, null);
}
private URI createServerUri2(long twitterId) throws URISyntaxException {
Log.e("createServerUri2: ", "in createServerUri2");
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
String username = sharedPref.getString(CLOUDANT_USER, "");
String dbName = sharedPref.getString(CLOUDANT_DB, "");
String apiKey = sharedPref.getString(CLOUDANT_API_KEY, "");
String apiSecret = sharedPref.getString(CLOUDANT_API_SECRET, "");
String host = username + ".cloudant.com";
return new URI("https", apiKey + ":" + apiSecret, host, 443, "/" + dbName + "/_all_docs?", null, null);
}
void checkForRegisteredUser() throws DocumentNotFoundException, DocumentException, URISyntaxException {
BasicDocumentRevision retrieved = DataStore.getDocument(TWITTER_ID + "");
if (user.equals("new")) {
setQuizData(retrieved.getBody().toString());
} else {
newUser();
}
}
void setQuizData(String DataRetrieved) {
Log.e("setQuizData: ", "In setQuizData");
user = "old";
Log.e("DataRetrieved: ", "In " + DataRetrieved);
String[] ANSWERS = getResources().getStringArray(R.array.ans);
try {
JSONObject jsonObject = new JSONObject(DataRetrieved);
JSONObject jsonObject1 = jsonObject.getJSONObject("questions");
String qs1 = jsonObject1.getString("q1");
String qs2 = jsonObject1.getString("q2");
String qs3 = jsonObject1.getString("q3");
String qs4 = jsonObject1.getString("q4");
String qs5 = jsonObject1.getString("q5");
String qs6 = jsonObject1.getString("q6");
String qs7 = jsonObject1.getString("q7");
String qs8 = jsonObject1.getString("q8");
sp1.setSelection(Arrays.asList(ANSWERS).indexOf(qs1));
sp2.setSelection(Arrays.asList(ANSWERS).indexOf(qs2));
sp3.setSelection(Arrays.asList(ANSWERS).indexOf(qs3));
sp4.setSelection(Arrays.asList(ANSWERS).indexOf(qs4));
sp5.setSelection(Arrays.asList(ANSWERS).indexOf(qs5));
sp6.setSelection(Arrays.asList(ANSWERS).indexOf(qs6));
sp7.setSelection(Arrays.asList(ANSWERS).indexOf(qs7));
sp8.setSelection(Arrays.asList(ANSWERS).indexOf(qs8));
} catch (JSONException e) {
}
}
void newUser() {
Log.e("newUser: ", "In newUser");
user = "new";
}
void createDocument() throws DocumentException {
Log.e("createDocument: ", "In createDocument");
MutableDocumentRevision rev = new MutableDocumentRevision();
rev.docId = TWITTER_ID + "";
gatherQAData();
/*HashMap<String, Object> map_main = new HashMap<String, Object>();*/
HashMap<String, Object> map = new HashMap<String, Object>();
ArrayList<HashMap<String, Object>> arrayTeachers = new ArrayList<>();
map.put("twitter_id", TWITTER_ID + "");
map.put("twitter_name", TWITTER_NAME);
map.put("questions", qa_hashmap);
/*arrayTeachers.add(map);*/
/*map_main.put("user", arrayTeachers);*/
rev.body = DocumentBodyFactory.create(map);
revision = DataStore.createDocumentFromRevision(rev);
PushReplicator.start();
}
void updateDocument() {
Log.e("updateDocument: ", "In updateDocument");
}
void gatherQAData() {
Log.e("gatherQAData: ", "In gatherQAData");
qa_hashmap = new HashMap<String, String>();
String a1, a2, a3, a4, a5, a6, a7, a8;
a1 = sp1.getSelectedItem().toString();
a2 = sp2.getSelectedItem().toString();
a3 = sp3.getSelectedItem().toString();
a4 = sp4.getSelectedItem().toString();
a5 = sp5.getSelectedItem().toString();
a6 = sp6.getSelectedItem().toString();
a7 = sp7.getSelectedItem().toString();
a8 = sp8.getSelectedItem().toString();
qa_hashmap.put("q1", a1);
qa_hashmap.put("q2", a2);
qa_hashmap.put("q3", a3);
qa_hashmap.put("q4", a4);
qa_hashmap.put("q5", a5);
qa_hashmap.put("q6", a6);
qa_hashmap.put("q7", a7);
qa_hashmap.put("q8", a8);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_submit:
if (user.equals("new")) {
try {
createDocument();
} catch (DocumentException e) {
}
} else {
updateDocument();
}
break;
default:
}
}
}
I can get the document which is stored in DataStore. But I am unable to get document stored in Cloudant database.
FYI: I am finding document in checkForRegisteredUser method.
Yes, I have done it. Below is my code for checkForRegisteredUser method of TabTwo_Fragment.java
void checkForRegisteredUser() {
String url = "https://your_cloudant_user_name.cloudant.com/" + DB_NAME + "/" + DOC_ID;
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
JsonObjectRequest jor = new JsonObjectRequest(Request.Method.GET, url, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if (response.toString().length() > 0) {
setQuizData(response.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
newUser();
}
});
requestQueue.add(jor);
Here is s Official Documentation LINK.
Here DOC_ID is the id of document that you want to check. Hope this will help to somebody.
What happens in Cloudant is that there are already two fields by default given by cloudant to each document namely _id and _rev where _id acts as primarykey for indexing. So there will be a default index created by cloudant on the _id field. If you already have these fields in your document than cloudant won't insert extra _id and _rev.
Now you can have this _id field in your document and set it according to yourself or let cloudant set it. But when you are not setting it than you won't be able to query Cloudant on the primary index because you don't know the _id of the document.
So to search or find on basis of some other field like the twitter_id as you have stored you have to create one more index than you'll be able to search/find according to that.
we can create index in java using the function provided by cloudant api
public void createIndex(java.lang.String indexName,
java.lang.String designDocName,
java.lang.String indexType,
IndexField[] fields)
or If you are assigning _id in your function than you can simply call a function
db.contains(doc_id);
which is a lot easier as you don't need to create any index and using default index.
EDIT-1
So the db here is the database instance you have acquired.
Database db=client.database(db_name,create_flag);
where create_flag is a boolean to if the database should be created if not existed so true means yes create false means no don't create if not there.
and client is CloudantClient object.
But alternatively you can call createDB also if you know the db is not there. You can do it as follow
Database db=client.createDB("DBNAME");
How to get a CloudantClient is dependent on the version of cloudant api you are using. for ex 1.0.1 is different from the latest.
in version 1.0.1 you do it as follow
CloudantClient client=new CloudantClient(URL_OF_YOUR_CLOUDANT,USERNAME,PASSWORD);
But in latest release they use
CloudantClient client=ClientBuilder.url(new URL("your url")).username("your username string").password("your password").build();
SO I don't know why you were not able to find createIndex. I suppose you are unable to find Cloudant-api javadocs .Just google for Cloudant javadocs or check this github
GitHub link

Twitter's access token isnt valid

I have a problem with my Android app when I try to login with Twitter. When I login and Twitter has given permission to my account to access, it shows the next message:
"Wait a moment!
The request form's token for this page isnt being valid. Is possible that it had was used or be expired because is a few old. Please, back to the site or aplicattion which sent to here an try again, probably it only was an error."
This is my code:
AlertManager:
package com.fsvp.manocio;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
public class AlertManager {
public void showAlertDialog(Context context, String title, String message, Boolean status) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(title);
builder.setMessage(message);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
Connection Manager:
package com.fsvp.manocio;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class ConnectionManager {
private Context _context;
public ConnectionManager(Context context){
this._context = context;
}
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
}
Activity Main:
package com.fsvp.manocio;
import com.fsvp.manocio.AlertManager;
import com.fsvp.manocio.ConnectionManager;
import com.fsvp.manocio.MainActivity;
import com.fsvp.manocio.R;
import android.support.v7.app.ActionBarActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
public static final String TAG = MainActivity.class.getSimpleName();
static String TWITTER_CONSUMER_KEY = "****";
static String TWITTER_CONSUMER_SECRET = "*****";
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_ACCESS_TOKEN = "*****";
static final String PREF_KEY_ACCESS_SECRET = "*****";
static final String PREF_KEY_USER_NAME = "user_name";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
static final String TWITTER_CALLBACK_URL = "https://api.twitter.com/oauth/authenticate?oauth_token=*****";
static final String URL_TWITTER_AUTH = "https://api.twitter.com/oauth/authorize";
static final String URL_TWITTER_OAUTH_VERIFIER = "https://api.twitter.com/oauth/access_token";
static final String URL_TWITTER_OAUTH_TOKEN = "https://api.twitter.com/oauth/request_token";
Button loginTwitter;
Button logoutTwitter;
TextView userName;
ImageView twitterLogo;
ProgressDialog pDialog;
private static Twitter twitter;
private static RequestToken requestToken;
private static SharedPreferences mSharedPreferences;
private ConnectionManager cm;
AlertManager alert = new AlertManager();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
cm = new ConnectionManager(getApplicationContext());
if (!cm.isConnectingToInternet()) {
alert.showAlertDialog(MainActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
return;
}
if(TWITTER_CONSUMER_KEY.trim().length() == 0 || TWITTER_CONSUMER_SECRET.trim().length() == 0){
alert.showAlertDialog(MainActivity.this, "Twitter oAuth tokens", "Please set your twitter oauth tokens first!", false);
return;
}
loginTwitter = (Button) findViewById(R.id.loginTwitter);
twitterLogo = (ImageView) findViewById(R.id.twitterLogo);
logoutTwitter = (Button) findViewById(R.id.logoutTwitter);
userName = (TextView) findViewById(R.id.userName);
mSharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
loginTwitter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
new TwitterLogin().execute();
}
});
logoutTwitter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
logoutFromTwitter();
}
});
if (!isTwitterLoggedInAlready()) {
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
String verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
new TwitterAccessToken().execute(verifier);
}
}else {
String userName = mSharedPreferences.getString(PREF_KEY_USER_NAME, "");
enableTwitterStatus(userName);
}
}
private class TwitterLogin extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// Check if already logged in
if (!isTwitterLoggedInAlready()) {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
Configuration configuration = builder.build();
TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();
try {
requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
MainActivity.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())));
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (isTwitterLoggedInAlready()) {
Toast.makeText(MainActivity.this, "Already Logged into Twitter", Toast.LENGTH_LONG).show();
}
}
}
private class TwitterAccessToken extends AsyncTask<String, Void, User> {
#Override
protected User doInBackground(String... params) {
String verifier = params[0];
AccessToken accessToken = null;
User user = null;
try {
accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
Editor e = mSharedPreferences.edit();
e.putString(PREF_KEY_ACCESS_TOKEN, accessToken.getToken());
e.putString(PREF_KEY_ACCESS_SECRET, accessToken.getTokenSecret());
e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
Log.d(TAG, "Twitter OAuth Token: " + accessToken.getToken());
long userID = accessToken.getUserId();
user = twitter.showUser(userID);
e.putString(PREF_KEY_USER_NAME, user.getName());
e.commit();
} catch (TwitterException e) {
Log.e(TAG, "Twitter Login Error: " + e.getMessage());
e.printStackTrace();
}
return user;
}
#Override
protected void onPostExecute(User user) {
super.onPostExecute(user);
if (user != null) {
enableTwitterStatus(user.getName());
}
}
}
private void enableTwitterStatus(String user) {
// Hide login button
loginTwitter.setVisibility(View.GONE);
logoutTwitter.setVisibility(View.VISIBLE);
twitterLogo.setVisibility(View.GONE);
userName.setText(Html.fromHtml("<b>Welcome " + userName + "</b>"));
userName.setVisibility(View.GONE);
}
private void logoutFromTwitter() {
// Clear the shared preferences
Editor e = mSharedPreferences.edit();
e.remove(PREF_KEY_ACCESS_TOKEN);
e.remove(PREF_KEY_ACCESS_SECRET);
e.remove(PREF_KEY_TWITTER_LOGIN);
e.commit();
logoutTwitter.setVisibility(View.GONE);
userName.setText("");
userName.setVisibility(View.GONE);
loginTwitter.setVisibility(View.VISIBLE);
twitterLogo.setVisibility(View.VISIBLE);
}
private boolean isTwitterLoggedInAlready() {
// return twitter login status from Shared Preferences
return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}
}
Finally, this is my manifest:
Anyone knows a solution?
Thanks and cheers!

Tweet Multiple Pictures Android

Twitter recently released an update allowing users to attach up to four images to a tweet. I was wondering how to implement this in an Android application.
I've found a post that was made BEFORE Twitter released the update called "Posting multiple photos in a single tweet" (I'm not showing the link because I'm only allowed to show two links with less than 10 reputation).
Now, here is the Twitter API documentation describing how to attach multiple images to a tweet, the only problem is that I have no idea how to implement this in Android:
https://dev.twitter.com/docs/api/1.1/post/statuses/update_with_media
So I was thinking of two possible solutions - either modify one of these methods from the Twitter4j library( https://github.com/yusuke/twitter4j/tree/master/twitter4j-media-support/src/main/java/twitter4j/media) to allow for multiple image attachments OR directly implement the Twitter API documentation.
Any ideas how to do this?
Input is greatly appreciated!
I have shared the multiple images on Twitter in android using twitter4j library,it is working fine to share multiple and single image on twitter
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import twitter4j.Status;
import twitter4j.StatusUpdate;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.UploadedMedia;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
public class SharingActivity extends AppCompatActivity implements View.OnClickListener {
private static final String PREF_NAME = "sample_twitter_pref";
private static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
private static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
private static final String PREF_KEY_TWITTER_LOGIN = "is_twitter_loggedin";
private static final String PREF_USER_NAME = "twitter_user_name";
private static final int WEBVIEW_REQUEST_CODE = 223;
private static Twitter twitter;
private static RequestToken requestToken;
private static SharedPreferences mSharedPreferences;
private String consumerKey = null;
private String consumerSecret = null;
private String callbackUrl = null;
private String oAuthVerifier = null;
ImageView loginLayout,shareLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initTwitterConfigs();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.activity_main);
findViewById(R.id.twitBtnId).setOnClickListener(this);
findViewById(R.id.btn_share).setOnClickListener(this);
mSharedPreferences = getSharedPreferences(PREF_NAME, 0);
boolean isLoggedIn = mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
if (isLoggedIn) {
loginLayout.setVisibility(View.VISIBLE);
shareLayout.setVisibility(View.GONE);
} else {
loginLayout.setVisibility(View.VISIBLE);
shareLayout.setVisibility(View.GONE);
}
}
private void saveTwitterInfo(AccessToken accessToken) {
long userID = accessToken.getUserId();
User user;
try {
user = twitter.showUser(userID);
String username = user.getName();
SharedPreferences.Editor e = mSharedPreferences.edit();
e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
e.putString(PREF_KEY_OAUTH_SECRET, accessToken.getTokenSecret());
e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
e.putString(PREF_USER_NAME, username);
e.commit();
} catch (TwitterException e1) {
e1.printStackTrace();
}
}
private void initTwitterConfigs() {
consumerKey = getString(R.string.twitter_consumer_key);
consumerSecret = getString(R.string.twitter_consumer_secret);
callbackUrl = getString(R.string.twitter_callback);
oAuthVerifier = getString(R.string.twitter_oauth_verifier);
}
private void loginToTwitter() {
boolean isLoggedIn = mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
if (!isLoggedIn) {
final ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecret);
final Configuration configuration = builder.build();
final TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();
try {
requestToken = twitter.getOAuthRequestToken(callbackUrl);
final Intent intent = new Intent(this, WebViewActivity.class);
intent.putExtra(WebViewActivity.EXTRA_URL, requestToken.getAuthenticationURL());
startActivityForResult(intent, WEBVIEW_REQUEST_CODE);
} catch (TwitterException e) {
e.printStackTrace();
}
} else {
loginLayout.setVisibility(View.GONE);
shareLayout.setVisibility(View.VISIBLE);
}
}
#Override
protected void onActivityResult(int requestCode, int responseCode, Intent data) {
super.onActivityResult(requestCode, responseCode, data);
if (responseCode == Activity.RESULT_OK) {
String verifier = data.getExtras().getString(oAuthVerifier);
try {
AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
saveTwitterInfo(accessToken);
loginLayout.setVisibility(View.GONE);
shareLayout.setVisibility(View.VISIBLE);
} catch (Exception e) {
Log.e("Twitter Login Failed", e.getMessage());
}
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.twitBtnId:
loginToTwitter();
break;
case R.id.btn_share:
new ShareImage().execute();
break;
}
}
public class ShareImage extends AsyncTask<Void,Void,String>{
#Override
protected void onPreExecute() {
//show progress here
super.onPreExecute();
}
#Override
protected String doInBackground(Void... voids) {
return uploadMultipleImages();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//hide progress here
Toast.makeText(SharingActivity.this,""+result,Toast.LENGTH_LONG).show();
}
}
public String uploadMultipleImages() {
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecret);
String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");
AccessToken accessToken = new AccessToken(access_token, access_token_secret);
try {
Bitmap bmp[] = {BitmapFactory.decodeResource(getResources(), R.drawable.lakeside_view1),
BitmapFactory.decodeResource(getResources(), R.drawable.lakeside_view2),
BitmapFactory.decodeResource(getResources(), R.drawable.lakeside_view3),
BitmapFactory.decodeResource(getResources(), R.mipmap.lakeside_view4),
BitmapFactory.decodeResource(getResources(), R.mipmap.lakeside_view5)};
String dir = Environment.getExternalStorageDirectory() + File.separator + "myDirectory";
File folder = new File(dir);
if (!folder.exists())
folder.mkdirs();
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
long[] mediaIds = new long[4];
for (int i=0; i<4; i++) {
File tempFile = new File(dir,"image_file"+(i));
FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
boolean isCompres = bmp[i].compress(Bitmap.CompressFormat.JPEG,100, fileOutputStream);
if (isCompres) {
UploadedMedia media = twitter.uploadMedia(tempFile);
mediaIds[i] = media.getMediaId();
tempFile.deleteOnExit();
}
}
StatusUpdate update = new StatusUpdate("test_name0");
update.setMediaIds(mediaIds);
Status status = twitter.updateStatus(update);
return "Successfully uploaded";
} catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to update status: " + te.getMessage());
}
} catch (Exception e){
e.printStackTrace();
}
return "not uloaded";
}
public String uploadSingleImage() {
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecret);
String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");
AccessToken accessToken = new AccessToken(access_token, access_token_secret);
try {
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.lakeside_view1);
String dir = Environment.getExternalStorageDirectory() + File.separator + "myDirectory";
File folder = new File(dir);
if (!folder.exists())
folder.mkdirs();
File tempFile = new File(dir,"image_file"+(i));
FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
boolean isCompres = bmp.compress(Bitmap.CompressFormat.JPEG,100, fileOutputStream);
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
StatusUpdate update = new StatusUpdate("test_name0");
update.setMedia(tempFile);
Status status = twitter.updateStatus(update);
return "Successfully uploaded";
} catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to update status: " + te.getMessage());
}
} catch (Exception e){
e.printStackTrace();
}
return "not uloaded";
}
}
public class WebViewActivity extends Activity {
private WebView webView;
public static String EXTRA_URL = "extra_url";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview);
final String url = this.getIntent().getStringExtra(EXTRA_URL);
if (null == url) {
finish();
}
webView = (WebView) findViewById(R.id.webView);
webView.setWebViewClient(new MyWebViewClient());
webView.loadUrl(url);
}
class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Uri uri = Uri.parse(url);
String verifier = uri.getQueryParameter(getString(R.string.twitter_oauth_verifier));
Intent resultIntent = new Intent();
resultIntent.putExtra(getString(R.string.twitter_oauth_verifier), verifier);
setResult(RESULT_OK, resultIntent);
finish();
return true;
}
}
}
for running above code please download the below library and put it in your app libs folder and add it as dependency in gradle file
(1)twitter4j-core-4.0.4.jar
(2)twitter4j-media-support-4.0.4.jar
(3)twitter4j-stream-4.0.4.jar
(4)signpost-commonshttp4-1.2.1.1.jar
(5)signpost-core-1.2.1.1.jar
(6)signpost-jetty6-1.2.1.1.jar
It is working fine, hope it will help for you also

How do I post and retrieve tweets in an Android app?

I'm trying to make a Twitter app which includes posting and retrieving tweets from the user's timeline and setting it in a list view which also updates when someone tweets.
I also wish to allow the user to upload photos to Twitter.
Here's my code:
package com.example.listtweetdemo;
import java.util.ArrayList;
import java.util.List;
import twitter4j.Paging;
import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import twitter4j.internal.org.json.JSONArray;
import twitter4j.internal.org.json.JSONObject;
import twitter4j.json.DataObjectFactory;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
private Button twitt;
private Button read;
private Button login;
private Button logout;
private EditText edt;
private boolean man = true;
private TextView textName;
private ListView list;
List<Status> statuses = new ArrayList<Status>();
static final String consumerKey = "RVVVPnAUa8e1XXXXXXXXX";
static final String consumerSecretKey = "eCh0Bb12n9oDmcomBdfisKZIfJmChC2XXXXXXXXXXXX";
static final String prefName = "twitter_oauth";
static final String prefKeyOauthToken = "oauth_token";
static final String prefKeyOauthSecret = "oauth_token_secret";
static final String prefKeyTwitterLogin = "isTwitterLogedIn";
static final String twitterCallbackUrl = "oauth://t4jsample";
static final String urlTwitterOauth = "auth_url";
static final String urlTwitterVerify = "oauth_verifier";
static final String urlTwitterToken = "oauth_token";
static SharedPreferences pref;
private static Twitter twitter;
private static RequestToken reqToken;
private connectionDetector cd;
AlertDailogManager alert = new AlertDailogManager();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpIds();
cd = new connectionDetector(getApplicationContext());
if(!cd.isConnectivityToInternet())
{
alert.showAlert(MainActivity.this, "Internet Connection Error", "Please Connect to working Internet connection", false);
return;
}
if(consumerKey.trim().length() == 0 || consumerSecretKey.trim().length() == 0)
{
alert.showAlert(MainActivity.this, "Twitter Oauth Token", "Please set your Twitter oauth token first!", false);
return;
}
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
loginToTwitter();
}
});
logout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
logoutFromTwitter();
}
});
read.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Paging paging = new Paging(200); // MAX 200 IN ONE CALL. SET YOUR OWN NUMBER <= 200
try {
statuses = twitter.getHomeTimeline();
} catch (TwitterException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
String strInitialDataSet = DataObjectFactory.getRawJSON(statuses);
JSONArray JATweets = new JSONArray(strInitialDataSet);
for (int i = 0; i < JATweets.length(); i++) {
JSONObject JOTweets = JATweets.getJSONObject(i);
Log.e("TWEETS", JOTweets.toString());
}
} catch (Exception e) {
// TODO: handle exception
}
/*try {
ResponseList<Status> statii = twitter.getHomeTimeline();
statusListAdapter adapter = new statusListAdapter(getApplicationContext(), statii);
setListAdapter(adapter);
Log.d("HOME TIMELINE", statii.toString());
} catch (TwitterException e) {
e.printStackTrace();
}
//list.setVisibility(View.VISIBLE);
read.setVisibility(View.GONE);*/
}
});
twitt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String status = edt.getText().toString();
if(status.trim().length() > 0)
{
new updateTwitter().execute(status);
}
}
});
if(!isTwitterLogedInAlready())
{
Uri uri = getIntent().getData();
if(uri != null && uri.toString().startsWith(twitterCallbackUrl))
{
String verify = uri.getQueryParameter(urlTwitterVerify);
try
{
AccessToken accessToken = twitter.getOAuthAccessToken(reqToken,verify);
Editor edit = pref.edit();
edit.putString(prefKeyOauthToken, accessToken.getToken());
edit.putString(prefKeyOauthSecret, accessToken.getTokenSecret());
edit.putBoolean(prefKeyTwitterLogin, true);
edit.commit();
Log.d("Twitter oauth Token", ">" + accessToken.getToken());
login.setVisibility(View.INVISIBLE);
twitt.setVisibility(View.VISIBLE);
edt.setVisibility(View.VISIBLE);
read.setVisibility(View.VISIBLE);
textName.setVisibility(View.VISIBLE);
if(man == true)
{
logout.setVisibility(View.VISIBLE);
}
long userId = accessToken.getUserId();
User user = twitter.showUser(userId);
//User user = twitter.getHomeTimeline();
Status n = user.getStatus();
String userName = user.getName();
textName.setText(userName);
}
catch(Exception e)
{
Log.d("Twitter Login Error", ">" + e.getMessage());
}
}
}
}
private void setUpIds() {
twitt = (Button)findViewById(R.id.buttTwitt);
login = (Button)findViewById(R.id.buttLogin);
read = (Button)findViewById(R.id.buttRead);
edt = (EditText)findViewById(R.id.editText1);
logout = (Button)findViewById(R.id.buttLogout);
textName = (TextView)findViewById(R.id.textName);
//list = (ListView)findViewById(R.id.listView1);
pref = getApplicationContext().getSharedPreferences("myPref", 0);
}
protected void logoutFromTwitter() {
Editor e = pref.edit();
e.remove(prefKeyOauthSecret);
e.remove(prefKeyOauthToken);
e.remove(prefKeyTwitterLogin);
e.commit();
login.setVisibility(View.VISIBLE);
logout.setVisibility(View.GONE);
twitt.setVisibility(View.GONE);
edt.setVisibility(View.GONE);
read.setVisibility(View.GONE);
textName.setVisibility(View.GONE);
}
protected void loginToTwitter() {
if(!isTwitterLogedInAlready())
{
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecretKey);
builder.setJSONStoreEnabled(true);
builder.setIncludeEntitiesEnabled(true);
builder.setIncludeMyRetweetEnabled(true);
builder.setIncludeRTsEnabled(true);
Configuration config = builder.build();
TwitterFactory factory = new TwitterFactory(config);
twitter = factory.getInstance();
try{
reqToken = twitter.getOAuthRequestToken(twitterCallbackUrl);
this.startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse(reqToken.getAuthenticationURL())));
}
catch(TwitterException e)
{
e.printStackTrace();
}
}
else
{
Toast.makeText(getApplicationContext(), "Already Logged In", Toast.LENGTH_LONG).show();
logout.setVisibility(View.VISIBLE);
man = false;
}
}
private boolean isTwitterLogedInAlready() {
return pref.getBoolean(prefKeyTwitterLogin, false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class updateTwitter extends AsyncTask<String , String, String>{
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Updating to Twitter status..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
Log.d("Tweet Text", "> " + args[0]);
String status = args[0];
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecretKey);
// Access Token
String access_token = pref.getString(prefKeyOauthToken, "");
// Access Token Secret
String access_token_secret = pref.getString(prefKeyOauthSecret, "");
AccessToken accessToken = new AccessToken(access_token, access_token_secret);
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
// Update status
twitter4j.Status response = twitter.updateStatus(status);
Log.d("Status", "> " + response.getText());
} catch (TwitterException e) {
// Error in updating status
Log.d("Twitter Update Error", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Status update successfully", Toast.LENGTH_SHORT).show();
edt.setText("");
}
});
}
}
}
Use the new Twitter Fabric SDK for Android. Requires sign up first. If you don't want to wait to be approved for the sign up, then I recommend using the following link
https://github.com/Rockncoder/TwitterTutorial
The link above explains how to retrieve tweets. You should be able to use the above link COMBINED with the information in the link below to POST tweets!
https://dev.twitter.com/overview/documentation

Posting LinkedIn message from Android application

I want to integrate my Android application with LinkedIn and post a message. Can anyone provide an example for how to do this?
did you even try google it ?
from http://developer.linkedin.com/docs/DOC-1255 we got
http://code.google.com/p/linkedin-j/
EDIT:
here is my sample project http://esilo.pl/LITest.zip
EDIT2: minimal sample, with tokens stored in SharedPreferences (so you don't need to do authorization every time(i'll update LITest.zip))
EDIT3: AsyncTask code added ... to avoid NetworkOnMainThreadException :)
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="pl.selvin.android.LinkedInTest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="4" />
<uses-permission android:name="android.permission.INTERNET" />
<application android:label="LinkedInTest" >
<activity
android:name=".LITestActivity"
android:label="LinkedIn Test"
android:launchMode="singleInstance" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="litestcalback"
android:scheme="x-oauthflow-linkedin" />
</intent-filter>
</activity>
</application>
</manifest>
LITestActivity.java:
package pl.selvin.android.LinkedInTest;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import com.google.code.linkedinapi.client.LinkedInApiClient;
import com.google.code.linkedinapi.client.LinkedInApiClientException;
import com.google.code.linkedinapi.client.LinkedInApiClientFactory;
import com.google.code.linkedinapi.client.oauth.LinkedInAccessToken;
import com.google.code.linkedinapi.client.oauth.LinkedInOAuthService;
import com.google.code.linkedinapi.client.oauth.LinkedInOAuthServiceFactory;
import com.google.code.linkedinapi.client.oauth.LinkedInRequestToken;
import com.google.code.linkedinapi.schema.Person;
public class LITestActivity extends Activity {
// /change keysssssssssssssssssssssssssssss!!!!!!!!!!
static final String CONSUMER_KEY = "keykeykeykey";
static final String CONSUMER_SECRET = "secretsecret";
static final String APP_NAME = "LITest";
static final String OAUTH_CALLBACK_SCHEME = "x-oauthflow-linkedin";
static final String OAUTH_CALLBACK_HOST = "litestcalback";
static final String OAUTH_CALLBACK_URL = String.format("%s://%s",
OAUTH_CALLBACK_SCHEME, OAUTH_CALLBACK_HOST);
static final String OAUTH_QUERY_TOKEN = "oauth_token";
static final String OAUTH_QUERY_VERIFIER = "oauth_verifier";
static final String OAUTH_QUERY_PROBLEM = "oauth_problem";
final LinkedInOAuthService oAuthService = LinkedInOAuthServiceFactory
.getInstance().createLinkedInOAuthService(CONSUMER_KEY,
CONSUMER_SECRET);
final LinkedInApiClientFactory factory = LinkedInApiClientFactory
.newInstance(CONSUMER_KEY, CONSUMER_SECRET);
static final String OAUTH_PREF = "LIKEDIN_OAUTH";
static final String PREF_TOKEN = "token";
static final String PREF_TOKENSECRET = "tokenSecret";
static final String PREF_REQTOKENSECRET = "requestTokenSecret";
TextView tv = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tv = new TextView(this);
setContentView(tv);
final SharedPreferences pref = getSharedPreferences(OAUTH_PREF,
MODE_PRIVATE);
final String token = pref.getString(PREF_TOKEN, null);
final String tokenSecret = pref.getString(PREF_TOKENSECRET, null);
if (token == null || tokenSecret == null) {
startAutheniticate();
} else {
showCurrentUser(new LinkedInAccessToken(token, tokenSecret));
}
}
void startAutheniticate() {
new AsyncTask<Void, Void, LinkedInRequestToken>() {
#Override
protected LinkedInRequestToken doInBackground(Void... params) {
return oAuthService.getOAuthRequestToken(OAUTH_CALLBACK_URL);
}
#Override
protected void onPostExecute(LinkedInRequestToken liToken) {
final String uri = liToken.getAuthorizationUrl();
getSharedPreferences(OAUTH_PREF, MODE_PRIVATE)
.edit()
.putString(PREF_REQTOKENSECRET,
liToken.getTokenSecret()).commit();
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(i);
}
}.execute();
}
void finishAuthenticate(final Uri uri) {
if (uri != null && uri.getScheme().equals(OAUTH_CALLBACK_SCHEME)) {
final String problem = uri.getQueryParameter(OAUTH_QUERY_PROBLEM);
if (problem == null) {
new AsyncTask<Void, Void, LinkedInAccessToken>() {
#Override
protected LinkedInAccessToken doInBackground(Void... params) {
final SharedPreferences pref = getSharedPreferences(
OAUTH_PREF, MODE_PRIVATE);
final LinkedInAccessToken accessToken = oAuthService
.getOAuthAccessToken(
new LinkedInRequestToken(
uri.getQueryParameter(OAUTH_QUERY_TOKEN),
pref.getString(
PREF_REQTOKENSECRET,
null)),
uri.getQueryParameter(OAUTH_QUERY_VERIFIER));
pref.edit()
.putString(PREF_TOKEN, accessToken.getToken())
.putString(PREF_TOKENSECRET,
accessToken.getTokenSecret())
.remove(PREF_REQTOKENSECRET).commit();
return accessToken;
}
#Override
protected void onPostExecute(LinkedInAccessToken accessToken) {
showCurrentUser(accessToken);
}
}.execute();
} else {
Toast.makeText(this,
"Appliaction down due OAuth problem: " + problem,
Toast.LENGTH_LONG).show();
finish();
}
}
}
void clearTokens() {
getSharedPreferences(OAUTH_PREF, MODE_PRIVATE).edit()
.remove(PREF_TOKEN).remove(PREF_TOKENSECRET)
.remove(PREF_REQTOKENSECRET).commit();
}
void showCurrentUser(final LinkedInAccessToken accessToken) {
final LinkedInApiClient client = factory
.createLinkedInApiClient(accessToken);
new AsyncTask<Void, Void, Object>() {
#Override
protected Object doInBackground(Void... params) {
try {
final Person p = client.getProfileForCurrentUser();
// /////////////////////////////////////////////////////////
// here you can do client API calls ...
// client.postComment(arg0, arg1);
// client.updateCurrentStatus(arg0);
// or any other API call
// (this sample only check for current user
// and pass it to onPostExecute)
// /////////////////////////////////////////////////////////
return p;
} catch (LinkedInApiClientException ex) {
return ex;
}
}
#Override
protected void onPostExecute(Object result) {
if (result instanceof Exception) {
//result is an Exception :)
final Exception ex = (Exception) result;
clearTokens();
Toast.makeText(
LITestActivity.this,
"Appliaction down due LinkedInApiClientException: "
+ ex.getMessage()
+ " Authokens cleared - try run application again.",
Toast.LENGTH_LONG).show();
finish();
} else if (result instanceof Person) {
final Person p = (Person) result;
tv.setText(p.getLastName() + ", " + p.getFirstName());
}
}
}.execute();
}
#Override
protected void onNewIntent(Intent intent) {
finishAuthenticate(intent.getData());
}
}
very helpful answer #Selvin!
this code should work fine on pre Honeycomb (API 11) targets, but it will fail with NetworkOnMainThreadException on (post) API 11. On pre IAPI 11 it's best avoided to run (possible long) network activity on the UI thread too, since it may lock it up.
I've updated Selvin's code to make it post API 10 compatible.
package com.package.my;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.google.code.linkedinapi.client.LinkedInApiClient;
import com.google.code.linkedinapi.client.LinkedInApiClientException;
import com.google.code.linkedinapi.client.LinkedInApiClientFactory;
import com.google.code.linkedinapi.client.oauth.LinkedInAccessToken;
import com.google.code.linkedinapi.client.oauth.LinkedInOAuthService;
import com.google.code.linkedinapi.client.oauth.LinkedInOAuthServiceFactory;
import com.google.code.linkedinapi.client.oauth.LinkedInRequestToken;
import com.google.code.linkedinapi.schema.Person;
public class your_class_name extends Activity {
public static final String CONSUMER_KEY = "your_app_key";
public static final String CONSUMER_SECRET = "your_app_secret";
public static final String APP_NAME = "your app name";
public static final String OAUTH_CALLBACK_SCHEME = "x-oauthflow-linkedin";
public static final String OAUTH_CALLBACK_HOST = "litestcalback";
public static final String OAUTH_CALLBACK_URL = OAUTH_CALLBACK_SCHEME + "://" + OAUTH_CALLBACK_HOST;
static final String OAUTH_QUERY_TOKEN = "oauth_token";
static final String OAUTH_QUERY_VERIFIER = "oauth_verifier";
static final String OAUTH_QUERY_PROBLEM = "oauth_problem";
static final String OAUTH_PREF = "AppPreferences";
static final String PREF_TOKEN = "linkedin_token";
static final String PREF_TOKENSECRET = "linkedin_token_secret";
static final String PREF_REQTOKENSECRET = "linkedin_request_token_secret";
final LinkedInOAuthService oAuthService = LinkedInOAuthServiceFactory.getInstance().createLinkedInOAuthService(CONSUMER_KEY, CONSUMER_SECRET);
final LinkedInApiClientFactory factory = LinkedInApiClientFactory.newInstance(CONSUMER_KEY, CONSUMER_SECRET);
LinkedInRequestToken liToken;
LinkedInApiClient client;
TextView tv = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tv = new TextView(this);
setContentView(tv);
final SharedPreferences pref = getSharedPreferences(OAUTH_PREF, MODE_PRIVATE);
final String token = pref.getString(PREF_TOKEN, null);
final String tokenSecret = pref.getString(PREF_TOKENSECRET, null);
if (token == null || tokenSecret == null) {
startAutheniticate();
} else {
LinkedInAccessToken accessToken = new LinkedInAccessToken(token, tokenSecret);
showCurrentUser(accessToken);
}
}//end method
void startAutheniticate() {
new Thread(){//added because this will make code work on post API 10
#Override
public void run(){
final LinkedInRequestToken liToken = oAuthService.getOAuthRequestToken(OAUTH_CALLBACK_URL);
final String uri = liToken.getAuthorizationUrl();
final SharedPreferences pref = getSharedPreferences(OAUTH_PREF, MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString(PREF_REQTOKENSECRET, liToken.getTokenSecret());
editor.commit();
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(i);
}
}.start();
}//end method
void finishAuthenticate(final Uri uri) {
new Thread(){
#Override
public void run(){
Looper.prepare();
if (uri != null && uri.getScheme().equals(OAUTH_CALLBACK_SCHEME)) {
final String problem = uri.getQueryParameter(OAUTH_QUERY_PROBLEM);
if (problem == null) {
final SharedPreferences pref = getSharedPreferences(OAUTH_PREF, MODE_PRIVATE);
final String request_token_secret = pref.getString(PREF_REQTOKENSECRET, null);
final String query_token = uri.getQueryParameter(OAUTH_QUERY_TOKEN);
final LinkedInRequestToken request_token = new LinkedInRequestToken(query_token, request_token_secret);
final LinkedInAccessToken accessToken = oAuthService.getOAuthAccessToken(request_token, uri.getQueryParameter(OAUTH_QUERY_VERIFIER));
SharedPreferences.Editor editor = pref.edit();
editor.putString(PREF_TOKEN, accessToken.getToken());
editor.putString(PREF_TOKENSECRET, accessToken.getTokenSecret());
editor.remove(PREF_REQTOKENSECRET);
editor.commit();
showCurrentUser(accessToken);
} else {
Toast.makeText(getApplicationContext(), "Application down due OAuth problem: " + problem, Toast.LENGTH_LONG).show();
finish();
}
}
Looper.loop();
}
}.start();
}//end method
void clearTokens() {
getSharedPreferences(OAUTH_PREF, MODE_PRIVATE).edit().remove(PREF_TOKEN).remove(PREF_TOKENSECRET).remove(PREF_REQTOKENSECRET).commit();
}//end method
void showCurrentUser(final LinkedInAccessToken accessToken) {
new Thread(){
#Override
public void run(){
Looper.prepare();
final LinkedInApiClient client = factory.createLinkedInApiClient(accessToken);
try {
final Person p = client.getProfileForCurrentUser();
// /////////////////////////////////////////////////////////
// here you can do client API calls ...
// client.postComment(arg0, arg1);
// client.updateCurrentStatus(arg0);
// or any other API call (this sample only check for current user
// and shows it in TextView)
// /////////////////////////////////////////////////////////
runOnUiThread(new Runnable() {//updating UI thread from different thread not a good idea...
public void run() {
tv.setText(p.getLastName() + ", " + p.getFirstName());
}
});
//or use Toast
//Toast.makeText(getApplicationContext(), "Lastname:: "+p.getLastName() + ", First name: " + p.getFirstName(), 1).show();
} catch (LinkedInApiClientException ex) {
clearTokens();
Toast.makeText(getApplicationContext(),
"Application down due LinkedInApiClientException: "+ ex.getMessage() + " Authokens cleared - try run application again.",
Toast.LENGTH_LONG).show();
finish();
}
Looper.loop();
}
}.start();
}//end method
#Override
protected void onNewIntent(Intent intent) {
finishAuthenticate(intent.getData());
}//end method
}//end class
Hope someone finds this useful! Credits go to Selvin.

Categories

Resources