This is done based on selvin's coding, but it doesnt work for me, that is message is not getting posted on the linked wall in android. after login stays in the same page.
This is the code `public class LITestActivity extends Activity {
// /change keysssssssssssssssssssssssssssss!!!!!!!!!!
static final String CONSUMER_KEY = "key";
static final String CONSUMER_SECRET = "secret";
static final String APP_NAME = "abc";
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 = "token secret";
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));
i.putExtra("sms_body", "Welcome to Rebuix, http://www.rebuix.com");
startActivity(i);
Toast.makeText(this,
"Successfuly posted: " ,
Toast.LENGTH_LONG).show();
}
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());
}
}`
Try the below URL to integration of social network like facebook, Twitter & LinkedIn
Related
I have an app that connects to my Foursquare account. The authentication is successful, but when it comes to showing my username (it shows null) and the list of venues around me, I can't get through it.
What should be done?
Main.java
public class Main extends Activity {
private FoursquareApp mFsqApp;
private ListView mListView;
private NearbyAdapter mAdapter;
private ArrayList<FsqVenue> mNearbyList;
private ProgressDialog mProgress;
public static final String CLIENT_ID = "XXXXXXXXXXXXXXX";
public static final String CLIENT_SECRET = "XXXXXXXXXXXXXXXXXXX";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView nameTv = (TextView) findViewById(R.id.tv_name);
Button connectBtn = (Button) findViewById(R.id.b_connect);
final EditText latitudeEt = (EditText) findViewById(R.id.et_latitude);
final EditText longitudeEt = (EditText)findViewById(R.id.et_longitude);
Button goBtn = (Button) findViewById(R.id.b_go);
mListView = (ListView) findViewById(R.id.lv_places);
mFsqApp = new FoursquareApp(this, CLIENT_ID, CLIENT_SECRET);
mAdapter = new NearbyAdapter(this);
mNearbyList = new ArrayList<FsqVenue>();
mProgress = new ProgressDialog(this);
mProgress.setMessage("Loading data ...");
if (mFsqApp.hasAccessToken()) nameTv.setText("Connected as " + mFsqApp.getUserName());
FsqAuthListener listener = new FsqAuthListener() {
#Override
public void onSuccess() {
Toast.makeText(Main.this, "Connected as " + mFsqApp.getUserName(), Toast.LENGTH_SHORT).show();
nameTv.setText("Connected as " + mFsqApp.getUserName());
}
#Override
public void onFail(String error) {
Toast.makeText(Main.this, error, Toast.LENGTH_SHORT).show();
}
};
mFsqApp.setListener(listener);
//get access token and user name from foursquare
connectBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mFsqApp.authorize();
}
});
//use access token to get nearby places
goBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String latitude = latitudeEt.getText().toString();
String longitude = longitudeEt.getText().toString();
if (latitude.equals("") || longitude.equals("")) {
Toast.makeText(Main.this, "Latitude or longitude is empty", Toast.LENGTH_SHORT).show();
return;
}
double lat = Double.valueOf(latitude);
double lon = Double.valueOf(longitude);
loadNearbyPlaces(lat, lon);
}
});
}
private void loadNearbyPlaces(final double latitude, final double longitude) {
mProgress.show();
new Thread() {
#Override
public void run() {
int what = 0;
try {
mNearbyList = mFsqApp.getNearby(latitude, longitude);
} catch (Exception e) {
what = 1;
e.printStackTrace();
}
mHandler.sendMessage(mHandler.obtainMessage(what));
}
}.start();
}
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
mProgress.dismiss();
if (msg.what == 0) {
if (mNearbyList.size() == 0) {
Toast.makeText(Main.this, "No nearby places available", Toast.LENGTH_SHORT).show();
return;
}
mAdapter.setData(mNearbyList);
mListView.setAdapter(mAdapter);
} else {
Toast.makeText(Main.this, "Failed to load nearby places", Toast.LENGTH_SHORT).show();
}
}
};
}
FoursquareApp.java
public class FoursquareApp {
private FoursquareSession mSession;
private FoursquareDialog mDialog;
private FsqAuthListener mListener;
private ProgressDialog mProgress;
private String mTokenUrl;
private String mAccessToken;
public static final String CALLBACK_URL = "https://www.foursquare.com";
private static final String AUTH_URL = "https://foursquare.com/oauth2/authenticate";
private static final String TOKEN_URL = "https://foursquare.com/oauth2/access_token";
private static final String API_URL = "https://api.foursquare.com/v2";
private static final String TAG = "FoursquareApi";
public FoursquareApp(Context context, String clientId, String clientSecret) {
mSession = new FoursquareSession(context);
mAccessToken = mSession.getAccessToken();
mTokenUrl = TOKEN_URL + "?client_id=" + clientId + "&client_secret=" + clientSecret + "&grant_type=authorization_code"
+ "&redirect_uri=" + CALLBACK_URL;
String url = AUTH_URL + "?client_id=" + clientId + "&response_type=code" + "&redirect_uri=" + CALLBACK_URL;
FsqDialogListener listener = new FsqDialogListener() {
#Override
public void onComplete(String code) {
getAccessToken(code);
}
#Override
public void onError(String error) {
mListener.onFail("Authorization failed");
}
};
mDialog = new FoursquareDialog(context, url, listener);
mProgress = new ProgressDialog(context);
mProgress.setCancelable(false);
}
private void getAccessToken(final String code) {
mProgress.setMessage("Getting access token ...");
mProgress.show();
new Thread() {
#Override
public void run() {
Log.i(TAG, "Getting access token");
int what = 0;
try {
URL url = new URL(mTokenUrl + "&code=" + code);
Log.i(TAG, "Opening URL " + url.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
//urlConnection.setDoOutput(true);
urlConnection.connect();
JSONObject jsonObj = (JSONObject) new JSONTokener(streamToString(urlConnection.getInputStream())).nextValue();
mAccessToken = jsonObj.getString("access_token");
} catch (Exception ex) {
what = 1;
ex.printStackTrace();
}
mHandler.sendMessage(mHandler.obtainMessage(what, 1, 0));
}
}.start();
}
private void fetchUserName() {
mProgress.setMessage("Finalizing ...");
new Thread() {
#Override
public void run() {
Log.i(TAG, "Fetching user name");
int what = 0;
try {
String v = timeMilisToString(System.currentTimeMillis());
URL url = new URL(API_URL + "/users/self?oauth_token=" + mAccessToken + "&v=" + v);
Log.d(TAG, "Opening URL " + url.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.connect();
String response = streamToString(urlConnection.getInputStream());
JSONObject jsonObj = (JSONObject) new JSONTokener(response).nextValue();
JSONObject resp = (JSONObject) jsonObj.get("response");
JSONObject user = (JSONObject) resp.get("user");
String firstName = user.getString("firstName");
String lastName = user.getString("lastName");
Log.i(TAG, "Got user name: " + firstName + " " + lastName);
mSession.storeAccessToken(mAccessToken, firstName + " " + lastName);
} catch (Exception ex) {
what = 1;
ex.printStackTrace();
}
mHandler.sendMessage(mHandler.obtainMessage(what, 2, 0));
}
}.start();
}
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (msg.arg1 == 1) {
if (msg.what == 0) {
fetchUserName();
} else {
mProgress.dismiss();
mListener.onFail("Failed to get access token");
}
} else {
mProgress.dismiss();
mListener.onSuccess();
}
}
};
public boolean hasAccessToken() {
return (mAccessToken == null) ? false : true;
}
public void setListener(FsqAuthListener listener) {
mListener = listener;
}
public String getUserName() {
return mSession.getUsername();
}
public void authorize() {
mDialog.show();
}
public ArrayList<FsqVenue> getNearby(double latitude, double longitude) throws Exception {
ArrayList<FsqVenue> venueList = new ArrayList<FsqVenue>();
try {
String v = timeMilisToString(System.currentTimeMillis());
String ll = String.valueOf(latitude) + "," + String.valueOf(longitude);
URL url = new URL(API_URL + "/venues/search?ll=" + ll + "&oauth_token=" + mAccessToken + "&v=" + v);
Log.d(TAG, "Opening URL " + url.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
//urlConnection.setDoOutput(true);
urlConnection.connect();
String response = streamToString(urlConnection.getInputStream());
JSONObject jsonObj = (JSONObject) new JSONTokener(response).nextValue();
JSONArray groups = (JSONArray) jsonObj.getJSONObject("response").getJSONArray("groups");
int length = groups.length();
if (length > 0) {
for (int i = 0; i < length; i++) {
JSONObject group = (JSONObject) groups.get(i);
JSONArray items = (JSONArray) group.getJSONArray("items");
int ilength = items.length();
for (int j = 0; j < ilength; j++) {
JSONObject item = (JSONObject) items.get(j);
FsqVenue venue = new FsqVenue();
venue.id = item.getString("id");
venue.name = item.getString("name");
JSONObject location = (JSONObject) item.getJSONObject("location");
Location loc = new Location(LocationManager.GPS_PROVIDER);
loc.setLatitude(Double.valueOf(location.getString("lat")));
loc.setLongitude(Double.valueOf(location.getString("lng")));
venue.location = loc;
venue.address = location.getString("address");
venue.distance = location.getInt("distance");
venue.herenow = item.getJSONObject("hereNow").getInt("count");
venue.type = group.getString("type");
venueList.add(venue);
}
}
}
} catch (Exception ex) {
throw ex;
}
return venueList;
}
private String streamToString(InputStream is) throws IOException {
String str = "";
if (is != null) {
StringBuilder sb = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
} finally {
is.close();
}
str = sb.toString();
}
return str;
}
private String timeMilisToString(long milis) {
SimpleDateFormat sd = new SimpleDateFormat("yyyyMMdd");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milis);
return sd.format(calendar.getTime());
}
public interface FsqAuthListener {
public abstract void onSuccess();
public abstract void onFail(String error);
}
}
FsqVenue.java
public class FsqVenue {
public String id;
public String name;
public String address;
public String type;
public Location location;
public int direction;
public int distance;
public int herenow;
}
FoursquareDialog.java
public class FoursquareDialog extends Dialog {
static final float[] DIMENSIONS_LANDSCAPE = {460, 260};
static final float[] DIMENSIONS_PORTRAIT = {280, 420};
static final FrameLayout.LayoutParams FILL = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT);
static final int MARGIN = 4;
static final int PADDING = 2;
private String mUrl;
private FsqDialogListener mListener;
private ProgressDialog mSpinner;
private WebView mWebView;
private LinearLayout mContent;
private TextView mTitle;
private static final String TAG = "Foursquare-WebView";
public FoursquareDialog(Context context, String url, FsqDialogListener listener) {
super(context);
mUrl = url;
mListener = listener;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSpinner = new ProgressDialog(getContext());
mSpinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
mSpinner.setMessage("Loading...");
mContent = new LinearLayout(getContext());
mContent.setOrientation(LinearLayout.VERTICAL);
setUpTitle();
setUpWebView();
Display display = getWindow().getWindowManager().getDefaultDisplay();
final float scale = getContext().getResources().getDisplayMetrics().density;
float[] dimensions = (display.getWidth() < display.getHeight()) ? DIMENSIONS_PORTRAIT : DIMENSIONS_LANDSCAPE;
addContentView(mContent, new FrameLayout.LayoutParams((int) (dimensions[0] * scale + 0.5f),
(int) (dimensions[1] * scale + 0.5f)));
CookieSyncManager.createInstance(getContext());
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
}
private void setUpTitle() {
requestWindowFeature(Window.FEATURE_NO_TITLE);
Drawable icon = getContext().getResources().getDrawable(R.drawable.foursquare_icon);
mTitle = new TextView(getContext());
mTitle.setText("Foursquare");
mTitle.setTextColor(Color.WHITE);
mTitle.setTypeface(Typeface.DEFAULT_BOLD);
mTitle.setBackgroundColor(0xFF0cbadf);
mTitle.setPadding(MARGIN + PADDING, MARGIN, MARGIN, MARGIN);
mTitle.setCompoundDrawablePadding(MARGIN + PADDING);
mTitle.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null);
mContent.addView(mTitle);
}
private void setUpWebView() {
mWebView = new WebView(getContext());
mWebView.setVerticalScrollBarEnabled(false);
mWebView.setHorizontalScrollBarEnabled(false);
mWebView.setWebViewClient(new TwitterWebViewClient());
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl(mUrl);
mWebView.setLayoutParams(FILL);
mContent.addView(mWebView);
}
private class TwitterWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.d(TAG, "Redirecting URL " + url);
if (url.startsWith(FoursquareApp.CALLBACK_URL)) {
String urls[] = url.split("=");
mListener.onComplete(urls[1]);
FoursquareDialog.this.dismiss();
return true;
}
return false;
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.d(TAG, "Page error: " + description);
super.onReceivedError(view, errorCode, description, failingUrl);
mListener.onError(description);
FoursquareDialog.this.dismiss();
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
Log.d(TAG, "Loading URL: " + url);
super.onPageStarted(view, url, favicon);
mSpinner.show();
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
String title = mWebView.getTitle();
if (title != null && title.length() > 0) {
mTitle.setText(title);
}
mSpinner.dismiss();
}
}
public interface FsqDialogListener {
public abstract void onComplete(String accessToken);
public abstract void onError(String error);
}
}
FoursquareSession.java
public class FoursquareSession {
private SharedPreferences sharedPref;
private Editor editor;
private static final String SHARED = "Foursquare_Preferences";
private static final String FSQ_USERNAME = "username";
private static final String FSQ_ACCESS_TOKEN = "access_token";
public FoursquareSession(Context context) {
sharedPref = context.getSharedPreferences(SHARED, Context.MODE_PRIVATE);
editor = sharedPref.edit();
}
public void storeAccessToken(String accessToken, String username) {
editor.putString(FSQ_ACCESS_TOKEN, accessToken);
editor.putString(FSQ_USERNAME, username);
editor.commit();
}
public void resetAccessToken() {
editor.putString(FSQ_ACCESS_TOKEN, null);
editor.putString(FSQ_USERNAME, null);
editor.commit();
}
public String getUsername() {
return sharedPref.getString(FSQ_USERNAME, null);
}
public String getAccessToken() {
return sharedPref.getString(FSQ_ACCESS_TOKEN, null);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.londatiga.fsq"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".Main" android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET"></uses- permission>
</manifest>
GCM is always returning SENDER_INVALID with following code..
All I could find is project id to be valid, which is valid and i have also tried changing the project but that is not helping.
I also tried going though entire stackoverflow and google groups, also changing google account and tried creating Application with old and as well new Google API console.
public class GCM {
private static final String TAG = "GCM";
public static final String EXTRA_MESSAGE = "message";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
Context mContext=null;
Activity mActivity=null;
String SENDER_ID = "44843754432";
GoogleCloudMessaging gcm;
String regid;
public GCM(Context ctx, Activity act){
mContext=ctx;
mActivity=act;
gcm = GoogleCloudMessaging.getInstance(ctx);
}
public String getRegistrationId(Context context) {
final SharedPreferences prefs = context.getSharedPreferences("DealsGeo_GCM", Context.MODE_PRIVATE);
String registrationId = prefs.getString(PROPERTY_REG_ID, PROPERTY_REG_ID);
if (registrationId.isEmpty()) {
Log.i(TAG, "Registration not found.");
return "";
}
int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int currentVersion = getAppVersion(context);
if (registeredVersion != currentVersion) {
Log.i(TAG, "App version changed.");
return "";
}
return registrationId;
}
public boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(mContext);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, mActivity, PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Log.i(TAG, "This device is not supported.");
return false;
}
return false;
}
return true;
}
private static int getAppVersion(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (NameNotFoundException e) {
throw new RuntimeException("Could not get package name: " + e);
}
}
public void registerInBackground() {
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... arg0) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(mContext);
}
Log.i(TAG,"Registering "+SENDER_ID);
regid = gcm.register(SENDER_ID);
storeRegistrationId(mContext, regid);
} catch (IOException ex) {
Log.i(TAG,"Error: "+ex.getMessage());
}
return msg;
}
}.execute(null, null, null);
}
private void storeRegistrationId(Context context, String regId) {
final SharedPreferences prefs = context.getSharedPreferences("DealsGeo_GCM", Context.MODE_PRIVATE);
int appVersion = getAppVersion(mContext);
Log.i(TAG, "Saving regId on app version " + appVersion);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regId);
editor.putInt(PROPERTY_APP_VERSION, appVersion);
editor.commit();
}
}
You have a URL like https://code.google.com/apis/console/?noredirect#project:581054524740:access in your project google console, so you must put the sender code : 581054524740
Perhaps you forgot a digit when copying the Google API project ID.
Your project ID - 44843754432 - has 11 digits, while all the project IDs I've seen had 12 digits.
I want to share text on Linkedin for that i have used below code
public class ShareWithLinkedIn extends Activity {
public static final String CONSUMER_KEY = "YOUR_COUSUMER_KEY";
public static final String CONSUMER_SECRET = "YOUR_SECRET_KEY";
public static final String APP_NAME = "SharePhotoImage";
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
it shows me login and allow screen which is looking like below when i click that button again same screen will be shown,, but i want like when (i click on that button it should share a text with image url)...
can any body help me to solve this problem
By below code i have done
public class ShareInLinkedIn extends Activity implements OnClickListener {
private LinkedInOAuthService oAuthService;
private LinkedInApiClientFactory factory;
private LinkedInRequestToken liToken;
private LinkedInApiClient client;
public static final String LINKEDIN_PREF = "GamePrefs";
#SuppressLint({ "NewApi", "NewApi", "NewApi" })
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.linkedin);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
oAuthService = LinkedInOAuthServiceFactory.getInstance().createLinkedInOAuthService(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET, Constants.SCOPE_PARAMS);
System.out.println("oAuthService : " + oAuthService);
factory = LinkedInApiClientFactory.newInstance(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
liToken = oAuthService.getOAuthRequestToken(Constants.OAUTH_CALLBACK_URL);
System.out.println("onCreate:linktoURL : " + liToken.getAuthorizationUrl());
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(liToken.getAuthorizationUrl()));
startActivity(i);
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
try {
linkedInImport(intent);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
private void linkedInImport(Intent intent) {
String verifier = intent.getData().getQueryParameter("oauth_verifier");
System.out.println("liToken " + liToken);
System.out.println("verifier " + verifier);
LinkedInAccessToken accessToken = oAuthService.getOAuthAccessToken(liToken, verifier);
//SharedPreferences settings = getSharedPreferences(LINKEDIN_PREF, MODE_PRIVATE);
// final Editor edit = settings.edit();
// edit.putString(OAuth.OAUTH_TOKEN, accessToken.getToken());
// edit.putString(OAuth.OAUTH_TOKEN_SECRET,
// accessToken.getTokenSecret());
// edit.putString("linkedin_login", "valid");
// edit.commit();
client = factory.createLinkedInApiClient(accessToken);
// client.postNetworkUpdate("LinkedIn Android app test");
Person profile = client.getProfileForCurrentUser(EnumSet.of(ProfileField.ID, ProfileField.FIRST_NAME, ProfileField.LAST_NAME, ProfileField.HEADLINE));
System.out.println("First Name :: " + profile.getFirstName());
System.out.println("Last Name :: " + profile.getLastName());
System.out.println("Head Line :: " + profile.getHeadline());
OAuthConsumer consumer = new CommonsHttpOAuthConsumer(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
consumer.setTokenWithSecret(accessToken.getToken(), accessToken.getTokenSecret());
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost("https://api.linkedin.com/v1/people/~/shares");
try {
consumer.sign(post);
post.setHeader("content-type", "text/XML");
String myEntity = "<share><comment>This is a test</comment><visibility><code>anyone</code></visibility></share>";
post.setEntity(new StringEntity(myEntity));
org.apache.http.HttpResponse response = httpclient.execute(post);
// Get the response
BufferedReader rd = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuffer strBfr = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
strBfr.append(line);
}
System.out.println("Response is : "+strBfr.toString());
Toast.makeText(ShareInLinkedIn.this, strBfr.toString(), Toast.LENGTH_LONG).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
Constants.java
public class Constants {
public static final String CONSUMER_KEY = "YOUR_CONSUMER_KEY";
public static final String CONSUMER_SECRET = "YOUR_CONSUMER_SECRET_KEY";
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;
public static final String SCOPE_PARAMS = "rw_nus+r_basicprofile";
}
AndroidManifiest.xml file
<activity
android:name="com.linkedin.ShareInLinkedIn"
android:launchMode="singleInstance" >
<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>
I'm doing linkedin integration for sharing the data in android, after giving the username and password and clicked on "sign in and allow" button i'm not able to move to the next page instead coming back to the previous page, and also data not posted on the wall, i tried out many tutorials, links, but could not findout my mistake and struggling alot, can anyone please help me.
here's my MainActivity code
public class MainActivity extends Activity {
public static final String CONSUMER_KEY = "key";
public static final String CONSUMER_SECRET = "secret";
public static final String APP_NAME = "rebuix";
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;
LinkedInOAuthService oAuthService = LinkedInOAuthServiceFactory
.getInstance().createLinkedInOAuthService(CONSUMER_KEY,
CONSUMER_SECRET);
LinkedInApiClientFactory factory = LinkedInApiClientFactory
.newInstance(CONSUMER_KEY, CONSUMER_SECRET);
LinkedInRequestToken liToken;
LinkedInApiClient client;
#SuppressLint({ "NewApi", "NewApi", "NewApi" })
Button btnLinkedin;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
Button btnLinkedinMain = (Button) findViewById(R.id.btnLinkedin);
btnLinkedinMain.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (v.getId() == R.id.btnLinkedin) {
oAuthService = LinkedInOAuthServiceFactory.getInstance()
.createLinkedInOAuthService(Constants.CONSUMER_KEY,
Constants.CONSUMER_SECRET);
System.out.println("oAuthService : " + oAuthService);
factory = LinkedInApiClientFactory.newInstance(
Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
liToken = oAuthService
.getOAuthRequestToken(Constants.OAUTH_CALLBACK_URL);
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(liToken
.getAuthorizationUrl()));
i.putExtra( "sms_body", false );
try
{
startActivity(i);
} catch (ActivityNotFoundException e) {
// Display some sort of error message here.
}
}
}
protected void onNewIntent(Intent intent) {
try {
linkedInImport(intent);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
private void linkedInImport(Intent intent) {
String verifier = intent.getData().getQueryParameter("oauth_verifier");
System.out.println("liToken " + liToken);
System.out.println("verifier " + verifier);
LinkedInAccessToken accessToken = oAuthService.getOAuthAccessToken(
liToken, verifier);
client = factory.createLinkedInApiClient(accessToken);
// client.postNetworkUpdate("LinkedIn Android app test");
Person profile = client.getProfileForCurrentUser(EnumSet.of(
ProfileField.ID, ProfileField.FIRST_NAME,
ProfileField.LAST_NAME, ProfileField.HEADLINE));
System.out.println("First Name :: " + profile.getFirstName());
System.out.println("Last Name :: " + profile.getLastName());
System.out.println("Head Line :: " + profile.getHeadline());
};
});
}
}
try out this tutorial...you will get message post feature in this tutorial..and for step by step integration in your app see this link... http://code.google.com/p/socialauth-android/wiki/Linkedin
https://github.com/srivastavavivek1987/LinkedIn-Connection-in-Android
I have to develop a login form android application.Here, i have to enter the username and password. If it is correct, fetch the email belonging to the username and display it in the textview and if the username and password is wrong, display login failed message.
This is my webservice code:
public class Login {
public String authentication(String username,String password) {
String retrievedUserName = "";
String retrievedPassword = "";
String retrievedEmail = "";
String status = "";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/xcart-432pro","root","");
PreparedStatement statement = con.prepareStatement("SELECT * FROM xcart_customers WHERE login = '"+username+"'");
ResultSet result = statement.executeQuery();
while(result.next()){
retrievedUserName = result.getString("login");
retrievedPassword = result.getString("password");
retrievedEmail = result.getString("email");
}
if(retrievedUserName.equals(username)&&retrievedPassword.equals(password)&&!(retrievedUserName.equals("") && retrievedPassword.equals(""))){
status = "Success";
}
else {
status = "Login fail!!!";
}
}
catch(Exception e){
e.printStackTrace();
}
return status;
}
};
This is my android code:
public class CustomerLogin extends Activity {
private static final String SPF_NAME = "vidslogin";
private static final String USERNAME = "login";
private static final String PASSWORD = "password";
private static final String PREFS_NAME = null;
CheckBox chkRememberMe;
private String login;
String mGrandTotal,total,mTitle;
EditText username,userPassword;
private final String NAMESPACE = "http://xcart.com";
private final String URL = "http://10.0.0.75:8085/XcartLogin/services/Login?wsdl";
private final String SOAP_ACTION = "http://xcart.com/authentication";
private final String METHOD_NAME = "authentication";
private String uName;
/**Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.customer_login);
Bundle b = getIntent().getExtras();
total = b.getString("GrandTotal");
mTitle = b.getString("Title");
TextView grandtotal = (TextView) findViewById(R.id.grand_total);
grandtotal.setText("Welcome ," + mTitle );
chkRememberMe = (CheckBox) findViewById(R.id.rempasswordcheckbox);
username = (EditText) findViewById(R.id.tf_userName);
userPassword = (EditText) findViewById(R.id.tf_password);
SharedPreferences loginPreferences = getSharedPreferences(SPF_NAME, Context.MODE_PRIVATE);
username.setText(loginPreferences.getString(USERNAME, ""));
userPassword.setText(loginPreferences.getString(PASSWORD, ""));
Button login = (Button) findViewById(R.id.btn_login);
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
loginAction();
}
});
}
private void loginAction(){
boolean isUserValidated = true;
boolean isPasswordValidated = true;
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
EditText username = (EditText) findViewById(R.id.tf_userName);
String user_Name = username.getText().toString();
EditText userPassword = (EditText) findViewById(R.id.tf_password);
String user_Password = userPassword.getText().toString();
//Pass value for userName variable of the web service
PropertyInfo unameProp =new PropertyInfo();
unameProp.setName("username");//Define the variable name in the web service method
unameProp.setValue(user_Name);//set value for userName variable
unameProp.setType(String.class);//Define the type of the variable
request.addProperty(unameProp);//Pass properties to the variable
//Pass value for Password variable of the web service
PropertyInfo passwordProp =new PropertyInfo();
passwordProp.setName("password");
passwordProp.setValue(user_Password);
passwordProp.setType(String.class);
request.addProperty(passwordProp);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try{
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
String status = response.toString();
TextView result = (TextView) findViewById(R.id.tv_status);
result.setText(response.toString());
if(status.equals("Success")) {
// ADD to save and read next time
String strUserName = username.getText().toString().trim();
String strPassword = userPassword.getText().toString().trim();
if (null == strUserName || strUserName.length() == 0) {
// showToast("Enter Your Name");
username.setError( "username is required!" );
isUserValidated = false;
}
if (null == strPassword || strPassword.length() == 0) {
// showToast("Enter Your Password");
isPasswordValidated = false;
userPassword.setError( "password is required!" );
}
if (isUserValidated = true && isPasswordValidated == true) {
if (chkRememberMe.isChecked()) {
SharedPreferences loginPreferences = getSharedPreferences(SPF_NAME, Context.MODE_PRIVATE);
loginPreferences.edit().putString(USERNAME, strUserName).putString(PASSWORD, strPassword).commit();
}
else {
SharedPreferences loginPreferences = getSharedPreferences(SPF_NAME, Context.MODE_PRIVATE);
loginPreferences.edit().clear().commit();
}
}
if (isUserValidated && isPasswordValidated) {
Intent intent = new Intent(CustomerLogin.this,PayPalIntegrationActivity.class);
intent.putExtra("GrandTotal", total);
intent.putExtra("Title", mTitle);
intent.putExtra("login",username.getText().toString());
startActivity(intent);
}
}
else {
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_custom_layout,
(ViewGroup) findViewById(R.id.toast_layout_root));
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.TOP, 0, 30);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
}
}
catch(Exception e){
}
}
}
If the login is success, it will have to display the email on textview. How can i do that?
You can use asy task to do this,
in doInBackground
Do your login operations. Asyctask makes this operation in another task.
when complated in onPostExecute
show the success message. But you need to use runOnUiThread because you cant reach ui controls from non ui thread.
private class loginTask extends AsyncTask<URL, Integer, int> {
protected Long doInBackground(URL... urls) {
// start login process
return 1;
}
protected void onPostExecute(int result) {
_activity.runOnUiThread(new Runnable() {
#Override
public void run() {
textview.setText("login success");
}
});
}
}