Posting LinkedIn message from Android application - android

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.

Related

android java : persisitent login application

I am trying to make an persistent login application which then read sms from my phone and sends them to the an api with meaage body as well as the date and sender information. How can I proceed for the same.
I have made the login app but persistent login like facebook and other applications is not working.
Here is my code for the login application:
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import java.util.ArrayList;
public class LoginActivity extends ActionBarActivity {
private EditText un,pw;
private Button sign;
private TextView msg;
private String resp, errorMsg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
un = (EditText) findViewById(R.id.et_Username);
pw = (EditText) findViewById(R.id.et_Password);
sign = (Button) findViewById(R.id.bt_SignIn);
msg = (TextView) findViewById(R.id.tv_error);
sign.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/**
* According with the new StrictGuard policy, running long tasks
* on the Main UI thread is not possible So creating new thread
* to create and execute http operations
*/
new Thread(new Runnable() {
#Override
public void run() {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username",
un.getText().toString()));
postParameters.add(new BasicNameValuePair("password",
pw.getText().toString()));
String response = null;
try {
response = SimpleHttpClient
.executeHttpPost(
url,
postParameters);
String res = response.toString();
System.out.println(res);
resp = res.replaceAll("\\s+", "");
} catch (Exception e) {
e.printStackTrace();
errorMsg = e.getMessage();
}
}
}).start();
try {
Thread.sleep(1000);
/**
* Inside the new thread we cannot update the main thread So
* updating the main thread outside the new thread
*/
msg.setText(resp);
if (null != errorMsg && !errorMsg.isEmpty()) {
msg.setText(errorMsg);
}
} catch (Exception e) {
msg.setText(e.getMessage());
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I tried this now,got the idea for shred prefernece but somewhow its not working for me
I tried this it doesn't show my main activity:
Can you find the problem:
MainActivity:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import java.util.ArrayList;
public class MainActivity extends Activity {
private String resp, errorMsg;
private EditText username,password;
/*public static final String MyPREFERENCES = "MyPrefs" ;
public static final String name = "nameKey";
public static final String pass = "passwordKey";
SharedPreferences sharedpreferences;*/
SessionManager session;
private TextView msg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = (EditText)findViewById(R.id.editText1);
password = (EditText)findViewById(R.id.editText2);
msg = (TextView) findViewById(R.id.tv_error);
session = new SessionManager(this);
}
#Override
protected void onResume() {
//sharedpreferences=getSharedPreferences(MyPREFERENCES,
// Context.MODE_PRIVATE);
if (session.getuser()!=null)
{
if(session.getpassword()!=null){
Intent i = new Intent(this,
Welcome.class);
startActivity(i);
}
}
super.onResume();
}
public void login(View view){
String u = username.getText().toString();
String p = password.getText().toString();
{
/**
* According with the new StrictGuard policy, running long tasks
* on the Main UI thread is not possible So creating new thread
* to create and execute http operations
*/
new Thread(new Runnable() {
#Override
public void run() {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username",
username.getText().toString()));
postParameters.add(new BasicNameValuePair("password",
password.getText().toString()));
String response = null;
try {
response = SimpleHttpClient
.executeHttpPost(
"<url>",
postParameters);
String res = response.toString();
//System.out.println(res);
resp = res.replaceAll("\\s+", "");
} catch (Exception e) {
e.printStackTrace();
errorMsg = e.getMessage();
}
}
}).start();
try {
Thread.sleep(1000);
/**
* Inside the new thread we cannot update the main thread So
* updating the main thread outside the new thread
*/
msg.setText(resp);
if (null != errorMsg && !errorMsg.isEmpty()) {
msg.setText(errorMsg);
}
} catch (Exception e) {
msg.setText(e.getMessage());
}
}
if (resp.contains("false")) {
session.saveSession(u, p);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
Welcome:
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
public class Welcome extends Activity {
SessionManager session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
session = new SessionManager(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//. getMenuInflater().inflate(R.menu, menu);
return true;
}
public void logout(View view){
session.logoutUser();
moveTaskToBack(true);
Welcome.this.finish();
}
public void exit(View view){
moveTaskToBack(true);
Welcome.this.finish();
}
public List<Sms> getAllSms() {
List<Sms> lstSms = new ArrayList<Sms>();
Sms objSms = new Sms();
Uri message = Uri.parse("content://sms/inbox");
ContentResolver cr = this.getContentResolver();
Cursor c = cr.query(message, null, null, null, null);
this.startManagingCursor(c);
int totalSMS = c.getCount();
if (c.moveToFirst()) {
for (int i = 0; i < totalSMS; i++) {
if(c.getString(c.getColumnIndexOrThrow("address")).contains("icicib")|| c.getString(c.getColumnIndexOrThrow("address")).contains("hdfcbk") || c.getString(c.getColumnIndexOrThrow("address")).contains("dbalrt")
||c.getString(c.getColumnIndexOrThrow("address")).contains("citibk")||c.getString(c.getColumnIndexOrThrow("address")).contains("unionb")||c.getString(c.getColumnIndexOrThrow("address")).contains("atmsbi")
|| c.getString(c.getColumnIndexOrThrow("address")).contains("sbiinb") || c.getString(c.getColumnIndexOrThrow("address")).contains("indusb") ||c.getString(c.getColumnIndexOrThrow("address")).contains("fedbnk")
|| c.getString(c.getColumnIndexOrThrow("address")).contains("kotakb")||c.getString(c.getColumnIndexOrThrow("address")).contains("axisbk")||c.getString(c.getColumnIndexOrThrow("address")).contains("pnbsms")
|| c.getString(c.getColumnIndexOrThrow("address")).contains("hsbcin") || c.getString(c.getColumnIndexOrThrow("address")).contains("canbnk") || c.getString(c.getColumnIndexOrThrow("address")).contains("idbi")
||c.getString(c.getColumnIndexOrThrow("address")).contains("iob") || c.getString(c.getColumnIndexOrThrow("address")).contains("citibk") || c.getString(c.getColumnIndexOrThrow("address")).contains("hdfcbk")
||c.getString(c.getColumnIndexOrThrow("address")).contains("fromsc") ||c.getString(c.getColumnIndexOrThrow("address")).contains("myamex") || c.getString(c.getColumnIndexOrThrow("address")).contains("26463872")
|| c.getString(c.getColumnIndexOrThrow("address")).contains("sbicrd") || c.getString(c.getColumnIndexOrThrow("address")).contains("icici?") || c.getString(c.getColumnIndexOrThrow("address")).contains("syndbk")
|| c.getString(c.getColumnIndexOrThrow("address")).contains("121") || c.getString(c.getColumnIndexOrThrow("address")).contains("best deal(121)") || c.getString(c.getColumnIndexOrThrow("address")).contains("airtel")
|| c.getString(c.getColumnIndexOrThrow("address")).contains("vfcare") || c.getString(c.getColumnIndexOrThrow("address")).contains("vodafone") || c.getString(c.getColumnIndexOrThrow("address")).contains("mytsky")||c.getString(c.getColumnIndexOrThrow("address")).contains("dishpy") ) {
objSms = new Sms();
objSms.setAddress(c.getString(c .getColumnIndexOrThrow("address")));
objSms.setMsg(c.getString(c.getColumnIndexOrThrow("body")));
objSms.setTime(c.getString(c.getColumnIndexOrThrow("date")));
lstSms.add(objSms);
}
c.moveToNext();
}
}
// else {
// throw new RuntimeException("You have no SMS");
// }
c.close();
return lstSms;
}
}
SessionManager:
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
public class SessionManager {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
int PRIVATE_MODE = 0;
private static final String PREFER_NAME = "AndroidExamplePref";
public static final String KEY_USER = "username";
public static final String KEY_PWD = "password";
public SessionManager(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void saveSession(String user, String pwd){
editor.putString(KEY_USER, user);
editor.putString(KEY_PWD, pwd);
editor.commit();
}
public String getuser()
{
String s = pref.getString(KEY_USER,"");
return s;
}
public String getpassword()
{
String p = pref.getString(KEY_PWD,"");
return p;
}
public void logoutUser(){
editor.clear();
editor.commit();
Intent i = new Intent(_context,.MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
_context.startActivity(i);
}
}
AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package=".sample" >
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.read_sms" />
<uses-permission android:name="android.permission.SEND_SMS" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Welcome"
android:label="#string/title_activity_welcome" >
</activity>
</application>
</manifest>
UPDATED ANSWER:
IT works now
i made session as static and before logging I am checking the shared preference value and accordingly going ahead. Everything is working now.
I guess you are meaning "persistent login application" -> User will log in once & for the next time they will not need to log in again with user name & password, right?
For this the naive approach would be storing the username & password in shared preference / db. But its not a good approach as it stores the password.
Instead of doing this, you can store, the userId/access token (obtained from the response). You should also have an expiration time so that you can prompt for log in validating the userId/access token after certain time.
Facebook seems to do the same thing I guess. E.g. if you clear data from on facebook app, then you does need to log in again.
I hope this gives you a direction.
Updated Answer
I guess you are not clear about pref.getString() method. The overloaded method (with 2 param) will return the 2nd param you sent, if any value with the query KEY (the 1st param)is not found.
In your case, in
public String getuser()
{
String s = pref.getString(KEY_USER,""); // here is the error, "" is not null, its an empty String.
return s;
}
So you can change this trouble causing line into either of the following line-
String s = pref.getString(KEY_USER,null);
or
String s = pref.getString(KEY_USER);
Same problem in the getuser(). Hopefully this will solve your problem :)

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

IllegalStateException in Twitter Integration

I am trying to integrate twitter in Android and following Twitter4j library. I have given the right consumer key and secret and have added the needed lines in manifest. Have added the Callback_URL in twitter. At first, I was able to login successfully but later it started throwing IllegalStateExcetpion.
MainActivity.java :
package com.example.feb_1twitterintegration;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.Menu;
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.Activity;
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.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
static String TWITTER_CONSUMER_KEY = "XXXXXX";
static String TWITTER_CONSUMER_SECRET = "XXXXXX";
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";
static final String URL_TWITTER_AUTH = "auth_url";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
ProgressDialog pDialog;
private static Twitter twitter;
private static RequestToken requestToken = new RequestToken(PREF_KEY_OAUTH_TOKEN, PREF_KEY_OAUTH_SECRET);
private static SharedPreferences mSharedPreferences;
private ConnectionDetector cd;
AlertDialogManager alert = new AlertDialogManager();
EditText sts;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
cd = new ConnectionDetector(getApplicationContext());
if (!cd.isConnectingToInternet()) {
alert.showAlertDialog(MainActivity.this,
"Internet Connection Error",
"Please connect to working Internet connection", false);
return;
}
// Check if twitter keys are set
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;
}
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
findViewById(R.id.login).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
loginToTwitter();
}
});
findViewById(R.id.tweet).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
sts = (EditText) findViewById(R.id.editText1);
String status = sts.getText().toString();
if (status.trim().length() > 0) {
new updateTwitterStatus().execute(status);
} else {
Toast.makeText(getApplicationContext(),
"Please enter status message",
Toast.LENGTH_SHORT).show();
}
}
});
if (!isTwitterLoggedInAlready()) {
final String verifier;
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
//verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
System.out.println(verifier);
try {
System.out.println("Request token: "+requestToken.getAuthenticationURL());
requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
System.out.println("after login");
AccessToken accessToken = twitter.getOAuthAccessToken(requestToken);
System.out.println(accessToken.getToken());
// Shared Preferences
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.commit();
Log.e("Twitter OAuth Token", "> " + accessToken.getToken());
findViewById(R.id.login).setVisibility(View.GONE);
findViewById(R.id.editText1).setVisibility(View.VISIBLE);
findViewById(R.id.tweet).setVisibility(View.VISIBLE);
long userID = accessToken.getUserId();
User user = twitter.showUser(userID);
String username = user.getName();
Log.e("UserID: ", "userID: " + userID + "" + username);
Log.v("Welcome:",
"Thanks:"
+ Html.fromHtml("<b>Welcome " + username
+ "</b>"));
} catch (Exception e) {
Toast.makeText(MainActivity.this, e.getMessage(), 1000)
.show();
Log.e("Twitter Login Error", "> " + e.getMessage());
e.printStackTrace();
}
}
}
}
private void loginToTwitter() {
if (!isTwitterLoggedInAlready()) {
new Thread() {
#Override
public void run() {
// TODO Auto-generated method stub
super.run();
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
builder.setUseSSL(true);
builder.setApplicationOnlyAuthEnabled(true);
/*configurationBuilder.setOAuth2TokenType(getOAuth2Token().getTokenType());
configurationBuilder.setOAuth2AccessToken(getOAuth2Token().getAccessToken());*/
Configuration configuration = builder.build();
TwitterFactory factory = new TwitterFactory(configuration);
twitter4j.Twitter twitter = factory.getInstance();
try {
System.out.println("Request token: "+requestToken.getAuthenticationURL());
requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
System.out.println("Req Token: "+requestToken);
MainActivity.this.startActivity(new Intent(
Intent.ACTION_VIEW, Uri.parse(requestToken
.getAuthenticationURL())));
} catch (TwitterException e) {
e.printStackTrace();
}
}
}.start();
} else {
Toast.makeText(getApplicationContext(),
"Already Logged into twitter", Toast.LENGTH_LONG).show();
}
}
private boolean isTwitterLoggedInAlready() {
System.out.println("Request Token in already logged in twitter: "+requestToken);
return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}
class updateTwitterStatus extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Updating to twitter...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
Log.d("Tweet Text", "> " + args[0]);
String status = args[0];
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
// Access Token
String access_token = mSharedPreferences.getString(
PREF_KEY_OAUTH_TOKEN, "");
// Access Token Secret
String access_token_secret = mSharedPreferences.getString(
PREF_KEY_OAUTH_SECRET, "");
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;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Status tweeted successfully", Toast.LENGTH_SHORT)
.show();
// Clearing EditText field
sts.setText("");
}
});
}
}
}
Logcat :
02-03 14:01:54.407: D/Network(21178): NETWORKnAME: WIFI
02-03 14:01:54.407: I/System.out(21178): Request Token in already logged in twitter: OAuthToken{token='oauth_token', tokenSecret='oauth_token_secret', secretKeySpec=null}
02-03 14:01:54.447: D/libEGL(21178): loaded /system/lib/egl/libGLES_android.so
02-03 14:01:54.467: D/libEGL(21178): loaded /system/lib/egl/libEGL_adreno200.so
02-03 14:01:54.487: D/libEGL(21178): loaded /system/lib/egl/libGLESv1_CM_adreno200.so
02-03 14:01:54.487: D/libEGL(21178): loaded /system/lib/egl/libGLESv2_adreno200.so
02-03 14:01:54.567: I/Adreno200-EGLSUB(21178): <ConfigWindowMatch:2078>: Format RGBA_8888.
02-03 14:01:54.577: D/OpenGLRenderer(21178): Enabling debug mode 0
02-03 14:01:54.627: D/OpenGLRenderer(21178): has fontRender patch
02-03 14:01:54.657: D/OpenGLRenderer(21178): has fontRender patch
02-03 14:01:56.128: I/System.out(21178): Request Token in already logged in twitter: OAuthToken{token='oauth_token', tokenSecret='oauth_token_secret', secretKeySpec=null}
02-03 14:01:56.168: I/System.out(21178): Request token: https://api.twitter.com/oauth/authenticate?oauth_token=oauth_token
02-03 14:01:56.168: W/dalvikvm(21178): threadid=11: thread exiting with uncaught exception (group=0x40aa9228)
02-03 14:01:56.178: E/AndroidRuntime(21178): FATAL EXCEPTION: Thread-65119
02-03 14:01:56.178: E/AndroidRuntime(21178): java.lang.IllegalStateException: OAuth consumer key/secret combination not supplied
02-03 14:01:56.178: E/AndroidRuntime(21178): at twitter4j.TwitterBaseImpl.getOAuth(TwitterBaseImpl.java:403)
02-03 14:01:56.178: E/AndroidRuntime(21178): at twitter4j.TwitterBaseImpl.getOAuthRequestToken(TwitterBaseImpl.java:298)
02-03 14:01:56.178: E/AndroidRuntime(21178): at com.example.feb_1twitterintegration.MainActivity$3.run(MainActivity.java:166)
02-03 14:01:58.741: D/OpenGLRenderer(21178): Flushing caches (mode 0)
02-03 14:01:58.751: D/memalloc(21178): /dev/pmem: Unmapping buffer base:0x52368000 size:3072000 offset:1536000
And the line where it implies for error is as follows :
requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
Any idea on what might be causing this issue to appear suddenly. I have been working on this for the past 2 days but this error has appeared from nowhere. Any help will be highly appreciated. Thanks in advance.
Your error is pretty straighforward. Logcat tells you this:
FATAL EXCEPTION: Thread-65119
02-03 14:01:56.178: E/AndroidRuntime(21178): java.lang.IllegalStateException: OAuth consumer key/secret combination not supplied
You need to declare your Twitter twitter object as a class variable, because you are setting the consumer and secret keys only to an instance of the object, but when you are requesting the auth token, you get a new instance of it, that doesn't have the configuration for the keys set.
private static Twitter twitter;
Then use this twitter object in the private void loginToTwitter(), and replace this:
twitter4j.Twitter twitter = factory.getInstance();
with
twitter = factory.getInstance();
where your twitter object is now a class iVar.
Here is a sample from my own implementation, that should help you:
public class TwitterRequestTokenActivity extends Activity {
final String TAG = getClass().getName();
// Twitter oauth urls
static final String URL_TWITTER_AUTH = "auth_url";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_DENIED = "denied";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
static final String TWITTER_CALLBACK_URL = "appnameoauth://twitterLogin";
private static Twitter twitter;
private static RequestToken requestToken;
private AccessToken accessToken;
/** Progress */
ProgressDialog mProgressDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
authenticate();
}
#Override
public void onDestroy() {
super.onDestroy();
}
/**
* Called when the OAuthRequestTokenTask finishes (user has authorized the request token).
* The callback URL will be intercepted here.
*/
#Override
public void onNewIntent(Intent intent)
{
super.onNewIntent(intent);
final Uri uri = intent.getData();
if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
//check if user did cancel the twitter auth
final String error = uri.getQueryParameter(URL_TWITTER_OAUTH_DENIED);
if (error==null)
getTwitterAccessToken(uri);
else {
// Login failed
Toast.makeText(TwitterRequestTokenActivity.this, getString(R.string.twitter_login_failed), Toast.LENGTH_LONG).show();
//user did not authenticate
finish();
}
}
else {
// Assume error: such as no connection
Toast.makeText(TwitterRequestTokenActivity.this, getString(R.string.twitter_login_failed), Toast.LENGTH_LONG).show();
finish();
}
}
/**
* Gets our token data once we obtain our accessToken from the asyncTask
*/
private void uploadToken() {
// upload data to our server
mProgressDialog = ProgressDialog.show(TwitterRequestTokenActivity.this, getString(R.string.generic_wait), getString(R.string.generic_sync), true, false);
// Getting user details from twitter
long userID = accessToken.getUserId();
//upload code to our server (irrelevant to question)
}
private void getTwitterAccessToken(Uri uri) {
mProgressDialog = ProgressDialog.show(TwitterRequestTokenActivity.this, getString(R.string.generic_wait), getString(R.string.twitter_logging_in), true, false);
final String verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
// get the Token from Twitter
AsyncTask<Void, Void, Void> tokenTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
TwitterRequestTokenActivity.this.accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
hideProgress();
if (TwitterRequestTokenActivity.this.accessToken==null){
hideProgress();
finish();
}
else
uploadToken();
}
};
tokenTask.execute();
}
/**
* Starts the oAuth request with our callback URL
*/
private void authenticate() {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(Global.TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(Global.TWITTER_CONSUMER_SECRET);
Configuration configuration = builder.build();
TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_FROM_BACKGROUND);
TwitterRequestTokenActivity.this.startActivity(intent);
}
catch (Exception e) {
finish();
}
}
});
thread.start();
}
/**
* Hides the progress bar
*/
private void hideProgress() {
try {
mProgressDialog.dismiss();
} catch (Exception e) {}
}
}
Also you need to make sure this activity is declared in your manifest as single task and set to listen to your custom oAUTH callback url:
<activity
android:name=".twitter.TwitterRequestTokenActivity"
android:configChanges="keyboardHidden|orientation"
android:launchMode="singleTask" >
<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="twitterLogin"
android:scheme="appnameoauth" />
</intent-filter>
</activity>
I fixed that same issue. its blocking on your ui. u just try it in asynctask. u just call that code inside a asynctask.
requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
or
like this,
class TwitterLogin extends AsyncTask<String, String, String>
{
#Override
protected String doInBackground(String... params)
{
// TODO Auto-generated method stub
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL))
{
String verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
try
{
AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
// Shared Preferences
Editor e = loginPrefs.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.commit();
Log.e("Twitter OAuth Token", "> " + accessToken.getToken());
long userID = accessToken.getUserId();
User user = twitter.showUser(userID);
String username = user.getName();
Log.e("UserID: ", "userID: "+userID+""+username);
Log.v("Welcome:","Thanks:"+Html.fromHtml("<b>Welcome " + username + "</b>"));
}
catch (Exception e)
{
Log.e("Twitter Login Error", "> " + e.getMessage());
}
}
return null;
}
#Override
protected void onPostExecute(String result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
}
#Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
}
}

how to post message on wall on LinkedIn in 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..

Categories

Resources