Sharing on Linkedin Android - java

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>

Related

DIsplay files downloaded from json on main screen?

I'm parsing a json to display a list of files a user can tap to download. I want to display the files the users have chosen to download on my main screen. this is the code when they download a file.
public final class Main extends Activity {
// Log tag for this class
private static final String TAG = "Main";
// Callback code for request of storage permission
final private int PERMISSIONS_REQUEST_STORAGE = 735;
// JSON Node Names
private static final String TAG_TYPE = "plans";
private static final String TAG_NAME = "name";
private static final String TAG_FILENAME = "filename";
private static final String TAG_URL = "url";
private static final String TAG_SHOULD_NOT_CACHE = "shouldNotCache";
// Files to delete
private static final ArrayList<String> filesToGetDeleted = new ArrayList<>();
// Strings displayed to the user
private static String offline;
private static String noPDF;
private static String localLoc;
private static String jsonURL;
// PDF Download
private static DownloadManager downloadManager;
private static long downloadID;
private static File file;
#SuppressLint("StaticFieldLeak")
private static SwipeRefreshLayout swipeRefreshLayout;
private final BroadcastReceiver downloadReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
final DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadID);
final Cursor cursor = downloadManager.query(query);
if (cursor.moveToFirst()) {
final int columnIndex = cursor
.getColumnIndex(DownloadManager.COLUMN_STATUS);
final int status = cursor.getInt(columnIndex);
switch (status) {
case DownloadManager.STATUS_SUCCESSFUL:
final Uri path = Uri.fromFile(file);
final Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(pdfIntent);
} catch (ActivityNotFoundException e) {
Utils.makeLongToast(Main.this, noPDF);
Log.e(TAG, e.getMessage());
}
break;
case DownloadManager.STATUS_FAILED:
Utils.makeLongToast(Main.this,
getString(R.string.down_error));
break;
case DownloadManager.STATUS_PAUSED:
Utils.makeLongToast(Main.this,
getString(R.string.down_paused));
break;
case DownloadManager.STATUS_PENDING:
Utils.makeLongToast(Main.this,
getString(R.string.down_pending));
break;
case DownloadManager.STATUS_RUNNING:
Utils.makeLongToast(Main.this,
getString(R.string.down_running));
break;
}
}
}
};
// Data from JSON file
private ArrayList<HashMap<String, String>> downloadList = new ArrayList<>();
private static void checkDir() {
final File dir = new File(Environment.getExternalStorageDirectory() + "/"
+ localLoc + "/");
if (!dir.exists()) dir.mkdir();
}
#Override
protected void onResume() {
super.onResume();
final IntentFilter intentFilter = new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE);
registerReceiver(downloadReceiver, intentFilter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(downloadReceiver);
}
#Override
protected void onDestroy() {
super.onDestroy();
// Delete files which should not get cached.
for (String file : filesToGetDeleted) {
final File f = new File(file);
if (f.exists()) {
f.delete();
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSIONS_REQUEST_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Utils.makeLongToast(Main.this, getString(R.string.permission_write_external_storage_success));
}
else {
final String permission_write_external_storage_failure = getString(R.string.permission_write_external_storage_failure);
final String app_title = getString(R.string.app_name);
final String message = String.format(permission_write_external_storage_failure, app_title);
Utils.makeLongToast(Main.this, message);
boolean showRationale = ActivityCompat.shouldShowRequestPermissionRationale(Main.this, permissions[0]);
if (!showRationale) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivity(intent);
}
}
break;
}
}
private void update(boolean force, boolean firstLoad) {
downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout_main);
offline = getString(R.string.status_offline);
noPDF = getString(R.string.except_nopdf);
localLoc = getString(R.string.gen_loc);
jsonURL = getString(R.string.gen_json);
checkDir();
if (firstLoad) {
try {
downloadList = (ArrayList<HashMap<String, String>>) Utils.readObject(this, "downloadList");
if (downloadList != null) {
setList(true, true);
}
} catch (ClassNotFoundException | IOException e) {
Log.e(TAG, e.getMessage());
}
}
// Parse the JSON file of the plans from the URL
JSONParse j = new JSONParse();
j.force = force;
j.online = !Utils.isNoNetworkAvailable(this);
j.execute();
}
private void setList(final boolean downloadable, final boolean itemsAvailable) {
if (itemsAvailable) {
try {
Utils.writeObject(this, "downloadList", downloadList);
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
}
final ListView list = (ListView) findViewById(R.id.listView_main);
final ListAdapter adapter = new SimpleAdapter(this, downloadList,
android.R.layout.simple_list_item_1, new String[]{TAG_NAME},
new int[]{android.R.id.text1});
list.setAdapter(adapter);
// React when user click on item in the list
if (itemsAvailable) {
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int pos,
long id) {
int hasStoragePermission = ContextCompat.checkSelfPermission(Main.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (hasStoragePermission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(Main.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
PERMISSIONS_REQUEST_STORAGE);
return;
}
final Uri downloadUri = Uri.parse(downloadList.get(pos).get(TAG_URL));
final String title = downloadList.get(pos).get(TAG_NAME);
final String shouldNotCache = downloadList.get(pos).get(TAG_SHOULD_NOT_CACHE);
file = new File(Environment.getExternalStorageDirectory() + "/"
+ localLoc + "/"
+ downloadList.get(pos).get(TAG_FILENAME) + ".pdf");
final Uri dst = Uri.fromFile(file);
if (file.exists()) {
final Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(dst, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(pdfIntent);
} catch (ActivityNotFoundException e) {
Utils.makeLongToast(Main.this, noPDF);
Log.e(TAG, e.getMessage());
}
return;
}
if (downloadable && !Utils.isNoNetworkAvailable(Main.this)) {
// Download PDF
final Request request = new Request(downloadUri);
request.setTitle(title).setDestinationUri(dst);
downloadID = downloadManager.enqueue(request);
if (shouldNotCache.equals("true")) {
filesToGetDeleted.add(file.toString());
}
} else {
Utils.makeLongToast(Main.this, offline);
}
}
});
}
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
update(true, false);
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
public boolean force = false;
public boolean online = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
}
});
}
#Override
protected JSONObject doInBackground(String... args) {
return JSONParser.getJSONFromUrl(Main.this, jsonURL, force, online);
}
#Override
protected void onPostExecute(JSONObject json) {
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(false);
}
});
downloadList.clear();
if (json == null) {
String error = getString(R.string.except_json);
if (!online) {
error = offline;
}
final HashMap<String, String> map = new HashMap<>();
map.put(TAG_NAME, error);
downloadList.add(map);
setList(false, false);
return;
}
try {
// Get JSON Array from URL
final JSONArray j_plans = json.getJSONArray(TAG_TYPE);
for (int i = 0; i < j_plans.length(); i++) {
final JSONObject c = j_plans.getJSONObject(i);
// Storing JSON item in a Variable
final String ver = c.getString(TAG_FILENAME);
final String name = c.getString(TAG_NAME);
final String api = c.getString(TAG_URL);
String shouldNotCache = "";
if (c.has(TAG_SHOULD_NOT_CACHE)) {
shouldNotCache = c.getString(TAG_SHOULD_NOT_CACHE);
}
// Adding value HashMap key => value
final HashMap<String, String> map = new HashMap<>();
map.put(TAG_FILENAME, ver);
map.put(TAG_NAME, name);
map.put(TAG_URL, api);
map.put(TAG_SHOULD_NOT_CACHE, shouldNotCache);
downloadList.add(map);
setList(online, true);
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
}
}
SO how do I get the result of the above code and display it on main screen every time the user opens app

Android Foursquare how to get the token

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>

Can't use the SASLXFacebookPlatformMechanism class in making android xmpp facebook chat client

I m trying to make a simple version facebook messenger.The code that i used has worked well for gtalk and requires facebook authentication to be used for chatting with facebook friends.For that, i have used SASLXFacebookPlatfromMechanism class where i will store the api token and api key along with the apisecret of my app. The problem is SASLXFacebookPlatfromMechanism.java class is full of errors which i cannot resolve at all.Here are my classes-
**MainActivity.java**
public class MainActivity extends ActionBarActivity {
private ArrayList<String> messages = new ArrayList();
private Handler mHandler = new Handler();
private SettingsDialog mDialog;
private EditText mRecipient;
private EditText mSendText;
private ListView mList;
private XMPPConnection connection;
/**
* Called with the activity is first created.
*/
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
Log.i("XMPPClient", "onCreate called");
setContentView(R.layout.activity_main);
mRecipient = (EditText) this.findViewById(R.id.recipient);
Log.i("XMPPClient", "mRecipient = " + mRecipient);
mSendText = (EditText) this.findViewById(R.id.sendText);
Log.i("XMPPClient", "mSendText = " + mSendText);
mList = (ListView) this.findViewById(R.id.listMessages);
Log.i("XMPPClient", "mList = " + mList);
setListAdapter();
// Dialog for getting the xmpp settings
mDialog = new SettingsDialog(this);
// Set a listener to show the settings dialog
Button setup = (Button) this.findViewById(R.id.setup);
setup.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
mHandler.post(new Runnable() {
public void run() {
mDialog.show();
}
});
}
});
// Set a listener to send a chat text message
Button send = (Button) this.findViewById(R.id.send);
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
try
{
String to = mRecipient.getText().toString();
String text = mSendText.getText().toString();
Log.i("XMPPClient", "Sending text [" + text + "] to [" + to + "]");
Message msg = new Message(to, Message.Type.chat);
msg.setBody(text);
connection.sendPacket(msg);
messages.add(connection.getUser() + ":");
messages.add(text);
setListAdapter();
}catch(Exception e)
{
Toast.makeText(MainActivity.this, "Error="+e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
/**
* Called by Settings dialog when a connection is establised with the XMPP server
*
* #param connection
*/
public void setConnection (XMPPConnection connection) {
this.connection = connection;
if (connection != null) {
// Add a packet listener to get messages sent to us
PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
connection.addPacketListener(new PacketListener() {
public void processPacket(Packet packet) {
Message message = (Message) packet;
if (message.getBody() != null) {
String fromName = StringUtils.parseBareAddress(message.getFrom());
Log.i("XMPPClient", "Got text [" + message.getBody() + "] from [" + fromName + "]");
messages.add(fromName + ":");
messages.add(message.getBody());
// Add the incoming message to the list view
mHandler.post(new Runnable() {
public void run() {
setListAdapter();
}
});
}
}
}, filter);
}
}
private void setListAdapter
() {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.multi_line_list_item,
messages);
mList.setAdapter(adapter);
}
}
SettingsDialog.java
public class SettingsDialog extends Dialog implements android.view.View.OnClickListener {
private MainActivity xmppClient;
public SettingsDialog(MainActivity xmppClient) {
super(xmppClient);
this.xmppClient = xmppClient;
}
protected void onStart() {
super.onStart();
setContentView(R.layout.settings);
getWindow().setFlags(4, 4);
setTitle("XMPP Settings");
Button ok = (Button) findViewById(R.id.ok);
ok.setOnClickListener(this);
}
public void onClick(View v) {
final String host = "chat.facebook.com";
final String port = ""+5222;
final String service = "chat.facebook.com";
final String username = "*****";
final String password = "****";
new Thread() {
public void run() {
// Create a connection
ConnectionConfiguration connConfig =new ConnectionConfiguration(host, Integer.parseInt(port), service);
connConfig.setSASLAuthenticationEnabled(true);
XMPPConnection connection = new XMPPConnection(connConfig);
try {
connection.connect();
Log.i("XMPPClient", "[SettingsDialog] Connected to " + connection.getHost());
} catch (Exception ex) {
Log.e("XMPPClient", "[SettingsDialog] Failed to connect to " + connection.getHost());
Log.e("XMPPClient", ex.toString());
xmppClient.setConnection(null);
}
try {
connection.login(username, password);
Log.i("XMPPClient", "Logged in as " + connection.getUser());
// Set the status to available
Presence presence = new Presence(Presence.Type.available);
connection.sendPacket(presence);
xmppClient.setConnection(connection);
} catch (XMPPException ex) {
Log.e("XMPPClient", "[SettingsDialog] Failed to log in as " + username);
Log.e("XMPPClient", ex.toString());
xmppClient.setConnection(null);
}
}
}.start();
dismiss();
}
private String getText(int id) {
EditText widget = (EditText) this.findViewById(id);
return widget.getText().toString();
}
}
SASLXFacebookPlatformMechanism.java
public class SASLXFacebookPlatformMechanism extends SASLMechanism
{
private static final String NAME = "X-FACEBOOK-PLATFORM";
private String apiKey = "";
private String applicationSecret = "";
private String sessionKey = "";
/**
* Constructor.
*/
public SASLXFacebookPlatformMechanism(SASLAuthentication saslAuthentication)
{
super(saslAuthentication);
}
#Override
protected void authenticate() throws IOException, XMPPException
{
getSASLAuthentication().send(new AuthMechanism(NAME, ""));
}
#Override
public void authenticate(String apiKeyAndSessionKey, String host,
String applicationSecret) throws IOException, XMPPException
{
if (apiKeyAndSessionKey == null || applicationSecret == null)
{
throw new IllegalArgumentException("Invalid parameters");
}
String[] keyArray = apiKeyAndSessionKey.split("\\|", 2);
if (keyArray.length < 2)
{
throw new IllegalArgumentException(
"API key or session key is not present");
}
this.apiKey = keyArray[0];
this.applicationSecret = applicationSecret;
this.sessionKey = keyArray[1];
this.authenticationId = sessionKey;
this.password = applicationSecret;
this.hostname = host;
String[] mechanisms = { "DIGEST-MD5" };
Map<String, String> props = new HashMap<String, String>();
this.sc =
Sasl.createSaslClient(mechanisms, null, "xmpp", host, props,
this);
authenticate();
}
#Override
public void authenticate(String username, String host, CallbackHandler cbh)
throws IOException, XMPPException
{
String[] mechanisms = { "DIGEST-MD5" };
Map<String, String> props = new HashMap<String, String>();
this.sc =
Sasl.createSaslClient(mechanisms, null, "xmpp", host, props,
cbh);
authenticate();
}
#Override
protected String getName()
{
return NAME;
}
#Override
public void challengeReceived(String challenge) throws IOException
{
byte[] response = null;
if (challenge != null)
{
String decodedChallenge = new String(Base64.decode(challenge));
Map<String, String> parameters = getQueryMap(decodedChallenge);
String version = "1.0";
String nonce = parameters.get("nonce");
String method = parameters.get("method");
long callId = new GregorianCalendar().getTimeInMillis();
String sig =
"api_key=" + apiKey + "call_id=" + callId + "method="
+ method + "nonce=" + nonce + "session_key="
+ sessionKey + "v=" + version + applicationSecret;
try
{
sig = md5(sig);
} catch (NoSuchAlgorithmException e)
{
throw new IllegalStateException(e);
}
String composedResponse =
"api_key=" + URLEncoder.encode(apiKey, "utf-8")
+ "&call_id=" + callId + "&method="
+ URLEncoder.encode(method, "utf-8") + "&nonce="
+ URLEncoder.encode(nonce, "utf-8")
+ "&session_key="
+ URLEncoder.encode(sessionKey, "utf-8") + "&v="
+ URLEncoder.encode(version, "utf-8") + "&sig="
+ URLEncoder.encode(sig, "utf-8");
response = composedResponse.getBytes("utf-8");
}
String authenticationText = "";
if (response != null)
{
authenticationText =
Base64.encodeBytes(response, Base64.DONT_BREAK_LINES);
}
// Send the authentication to the server
getSASLAuthentication().send(new Response(authenticationText));
}
private Map<String, String> getQueryMap(String query)
{
Map<String, String> map = new HashMap<String, String>();
String[] params = query.split("\\&");
for (String param : params)
{
String[] fields = param.split("=", 2);
map.put(fields[0], (fields.length > 1 ? fields[1] : null));
}
return map;
}
private String md5(String text) throws NoSuchAlgorithmException,
UnsupportedEncodingException
{
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(text.getBytes("utf-8"), 0, text.length());
return convertToHex(md.digest());
}
private String convertToHex(byte[] data)
{
StringBuilder buf = new StringBuilder();
int len = data.length;
for (int i = 0; i < len; i++)
{
int halfByte = (data[i] >>> 4) & 0xF;
int twoHalfs = 0;
do
{
if (0 <= halfByte && halfByte <= 9)
{
buf.append((char) ('0' + halfByte));
}
else
{
buf.append((char) ('a' + halfByte - 10));
}
halfByte = data[i] & 0xF;
} while (twoHalfs++ < 1);
}
return buf.toString();
}
#Override
protected String getAuthenticationText(String arg0, String arg1, String arg2) {
// TODO Auto-generated method stub
return null;
}
#Override
protected String getChallengeResponse(byte[] arg0) {
// TODO Auto-generated method stub
return null;
}
}
The code shows error stating
"The method send(String) in the type SASLAuthentication is not applicable for arguments(Response).The constructor Response(String) is undefined"
in the line-->"getSASLAuthentication().send(new Response(authenticationText));"
I am also confused on how to use this SASLXFacebookPlatformMechanism.java class in my MainActivity.class.I have been trying to get a sense of how it works but failing.A complete guideline on how to develop a xmpp facebook chat client using asmack library would be appreciated since the internet lacks enough documentation on it.Thanks.
[I have the apikeys and apitokens,so the empty string will not remain empty]

selvin's code for integration of linkedin in android

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

linkedin: Message not getting posted

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

Categories

Resources