Easy Facebook Android SDK - NetworkOnMainThreadException - android

I have been Using this SDK http://www.easyfacebookandroidsdk.com/ to integrate Facebook in my App.
I only want to update a statur from my App. It worked great using this class in Android API 10. Running it on phone with API 15 gives me a android.os.NetworkOnMainThreadException. here my code:
package com.my.wod;
import android.app.Activity;
import android.content.Context;
import com.main.xfit.R;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Toast;
import com.facebook.android.*;
import com.facebook.android.Facebook.DialogListener;
public class PostFaceBookStatus extends Activity {
private static final String APP_ID = "ID OF MY APP";
private static final String[] PERMISSIONS = {"publish_stream" };
private static final String TOKEN = "access_token";
private static final String EXPIRES = "expires_in";
private static final String KEY = "facebook-credentials";
private Facebook facebook;
private String messageToPost;
public boolean saveCredentials(Facebook facebook) {
Editor editor = getApplicationContext().getSharedPreferences(KEY, Context.MODE_PRIVATE).edit();
editor.putString(TOKEN, facebook.getAccessToken());
editor.putLong(EXPIRES, facebook.getAccessExpires());
return editor.commit();
}
public boolean restoreCredentials(Facebook facebook) {
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(KEY, Context.MODE_PRIVATE);
facebook.setAccessToken(sharedPreferences.getString(TOKEN, null));
facebook.setAccessExpires(sharedPreferences.getLong(EXPIRES, 0));
return facebook.isSessionValid();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
facebook = new Facebook(APP_ID);
restoreCredentials(facebook);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.facebook);
String facebookMessage = getIntent().getStringExtra("facebookMessage");
Toast.makeText(getApplicationContext(), facebookMessage, Toast.LENGTH_LONG).show();
if (facebookMessage == null){
facebookMessage = "SUNDAY 120506 2012 CrossFit Games Regional: Individual Event 4 For time: 135 pound Back squat, 50 reps 40 Pull-ups 135 pound Shoulder-to-overhead, 30 reps 85 pound Front squat, 50 reps 40 Pull-ups 85 pound Shoulder-to-overhead, 30 reps 65 pound Overhead squat, 50 reps 40 Pull-ups 65 pound Shoulder-to-overhead, 30 reps";
}
//messageToPost = facebookMessage;
messageToPost = "Post random shit" ;
}
public void doNotShare(View button){
finish();
}
public void share(View button){
if (! facebook.isSessionValid()) {
loginAndPostToWall();
}
else {
postToWall(messageToPost);
}
}
public void loginAndPostToWall(){
facebook.authorize(this, PERMISSIONS, Facebook.FORCE_DIALOG_AUTH, new LoginDialogListener());
}
public void postToWall(String message){
Bundle parameters = new Bundle();
parameters.putString("message", message);
parameters.putString("description", "topic share");
try {
facebook.request("me");
String response = facebook.request("me/feed", parameters, "POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("") ||
response.equals("false")) {
showToast("Blank response.");
}
else {
showToast("Message posted to your facebook wall!");
}
finish();
} catch (Exception e) {
showToast("Failed to post to wall!");
e.printStackTrace();
finish();
}
}
class LoginDialogListener implements DialogListener {
public void onComplete(Bundle values) {
saveCredentials(facebook);
if (messageToPost != null){
postToWall(messageToPost);
}
}
public void onFacebookError(FacebookError error) {
showToast("Authentication with Facebook failed!");
finish();
}
public void onError(DialogError error) {
showToast("Authentication with Facebook failed!");
finish();
}
public void onCancel() {
showToast("Authentication with Facebook cancelled!");
finish();
}
}
private void showToast(String message){
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
}
Any ideas?

You can't run network operations on the UI thread, and if you think it is is the API code doing it, then you'll have to wrap the API call's in a Thread.
Looks like this line is using the network:
String response = facebook.request("me/feed", parameters, "POST");
You need to do long running tasks on a worker thread.
You used to get an ANR (Activity Not Responsding) but ICS is a little cleverer and kicks you off before this happens.
Get reading:
http://developer.android.com/guide/practices/responsiveness.html
http://developer.android.com/training/basics/network-ops/connecting.html#AsyncTask < This is one possible alternative answer

To make it work for API level 10 and higher i just employed and AsyncTask and it Worked!!
Use the below code:
//make this global declaration
private Facebook mFacebook;
private class FbLoginAsync extends AsyncTask<Void, Void, User> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(ConstantsCtc.DIALOG_PROGRESS);
}
#Override
protected User doInBackground(Void... params) {
// facebooklogin();
return getFacebookData();
}
#Override
protected void onPostExecute(User u) {
super.onPostExecute(u);
// your facebook information is in User bean 'u'.
}
}
public User getFacebookData() {
User u = new User();
try {
JSONObject jsonME = null;
JSONObject jsonfrnd = null;
try {
jsonME = Util.parseJson(mFacebook.request("me"));
// jsonfrnd =
// Util.parseJson(mFacebook
// .request("me/friends"));
} catch (FacebookError e) {
e.printStackTrace();
u = null;
}
Log.w("fbjsonMe", " *\n " + jsonME);
// Log.e("fbjsonfrnds", " *\n " + jsonfrnd);
String mUserId = jsonME.getString("id");
String mUserName = jsonME.getString("first_name");
String mUseremail = jsonME.getString("email");
String birthday = jsonME.getString("birthday");
String gender = jsonME.getString("gender");
String full_name = jsonME.getString("name");
// Log.w("UserName", mUserName + " * " + mUseremail + " *\n "
// + jsonME);
// calculate age
String ag[] = birthday.split("/");
int y = Integer.parseInt(ag[2]);// get birth year
final Calendar cal = Calendar.getInstance();
int currentyear = cal.get(Calendar.YEAR);
int age = currentyear - y;
if (gender.equalsIgnoreCase("male"))
gender = "0";
else
gender = "1";
u.setUserId(mUserId);
u.setUserFullName(full_name);
u.setEmail(mUseremail);
u.setAge(age + "");
u.setGender(gender);
} catch (Exception e) {
e.printStackTrace();
u = null;
}
return u;
}
// then make a call to below method form your activity's button click or
// else
public void facebookLogin() {
this.mFacebook = new Facebook(appId);// give your appId
if (mFacebook.isSessionValid()) {
new FbLoginAsync().execute();
} else {
SessionEvents.AuthListener listener = new SessionEvents.AuthListener() {
#Override
public void onAuthSucceed() {
new FbLoginAsync().execute();
}
#Override
public void onAuthFail(String error) {
showDialogCustome("Error in Facebook Login, please try again later");
Log.e("onAuthFail", "onAuthFail");
}
};
SessionEvents.addAuthListener(listener);
mFacebook.authorize(this.activity, this.permissions,
Facebook.FORCE_DIALOG_AUTH, new LoginDialogListener());
}
}
I hope this solves your problem. let me know

Related

Custom Login with Twitter in android

How to create custom buttons for social login auth for twitter on android application development. By default social media have different SDK, which SDK twitter already has its own button social login but i want to use my own custom button and i wrote some code but getting exception
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Object.hashCode()' on a null object reference
my code:-
TwitterConfig config = new TwitterConfig.Builder(this)
.logger(new DefaultLogger(Log.DEBUG))
.twitterAuthConfig(new TwitterAuthConfig("KEY",
"KEY"))
.debug(true)
.build();
Twitter.initialize(config);
client = new TwitterAuthClient();
final TwitterSession session = TwitterCore.getInstance().getSessionManager().getActiveSession();
twitterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
client.requestEmail(session, new Callback<String>() {
#Override
public void success(Result<String> result) {
System.out.println("Email is=====>" + result.data);
}
#Override
public void failure(TwitterException exception) {
}
});
}
});
please try this
add this gradle line in you project
compile 'com.twitter.sdk.android:twitter:3.0.0'
Write in your Activity/Fragment
//Your Custom Button
private ivTwitter;
//Twitter Login Button
private TwitterLoginButton ivTwitterMain;
//init twitter
TwitterConfig config = new TwitterConfig.Builder(this)
.logger(new DefaultLogger(Log.DEBUG))
.twitterAuthConfig(new TwitterAuthConfig(Const.CONSUMER_KEY, Const.CONSUMER_SECRET))
.debug(false)
.build();
Twitter.initialize(config);
//Write in onCreate method
ivTwitter = (ImageView) view.findViewById(R.id.ivTwitter);
ivTwitterMain = (TwitterLoginButton)view.findViewById(R.id.ivTwitterMain);
ivTwitterMain.setCallback(new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> result) {
// Do something with result, which provides a TwitterSession for making API calls
TwitterSession session = TwitterCore.getInstance().getSessionManager().getActiveSession();
TwitterAuthToken authToken = session.getAuthToken();
String token = authToken.token;
String secret = authToken.secret;
getTwitterUserProfile(session);
}
#Override
public void failure(TwitterException exception) {
// Do something on failure
Log.d(Const.FRAGMENT_REGISTER, exception.getMessage());
}
});
//getTwitterUserProfile
private void getTwitterUserProfile(TwitterSession session) {
AccountService accountService = new TwitterApiClient(session).getAccountService();
Call<User> callback = accountService.verifyCredentials(true, true, true);
callback.clone().enqueue(new Callback<User>() {
#Override
public void success(Result<User> result) {
Log.d("NAME ", result.data.name);
Log.d("EMAIL", result.data.email);
Log.d("PICTURE ", result.data.profileImageUrl);
}
#Override
public void failure(TwitterException exception) {
}
});
}
at last generate Click event of custom button
ivTwitter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//twitter login button
ivTwitterMain.performClick();
}
});
/**Try to implement Below code Snipeet**/
First Download the Twitter Library from Below mentioned Link:
Link -> http://twitter4j.org/maven2/org/twitter4j/twitter4j-core/4.0.4/
Add the library to your build.gradle
/******************************************************/
Make "Twitter_Handler" Class inside your project
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import oauth.signpost.OAuthProvider;
import oauth.signpost.basic.DefaultOAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Handler;
import android.os.Message;
import android.view.Window;
public class Twitter_Handler
{
public static Twitter twitterObj;
private final TwitterSession mSession;
private AccessToken mAccessToken;
private final CommonsHttpOAuthConsumer mHttpOauthConsumer;
private final OAuthProvider mHttpOauthprovider;
private final String mConsumerKey;
private final String mSecretKey;
private final ProgressDialog mProgressDlg;
private TwDialogListener mListener;
private final Activity context;
public static final String CALLBACK_URL = "twitterapp://connect";
private static final String TWITTER_ACCESS_TOKEN_URL = "https://api.twitter.com/oauth/access_token";
private static final String TWITTER_AUTHORZE_URL = "https://api.twitter.com/oauth/authorize";
private static final String TWITTER_REQUEST_URL = "https://api.twitter.com/oauth/request_token";
public Twitter_Handler(Activity context, String consumerKey,String secretKey)
{
this.context = context;
twitterObj = new TwitterFactory().getInstance();
mSession = new TwitterSession(context);
mProgressDlg = new ProgressDialog(context);
mProgressDlg.requestWindowFeature(Window.FEATURE_NO_TITLE);
mConsumerKey = consumerKey;
mSecretKey = secretKey;
mHttpOauthConsumer = new CommonsHttpOAuthConsumer(mConsumerKey,mSecretKey);
String request_url = TWITTER_REQUEST_URL;
String access_token_url = TWITTER_ACCESS_TOKEN_URL;
String authorize_url = TWITTER_AUTHORZE_URL;
mHttpOauthprovider = new DefaultOAuthProvider(request_url,access_token_url, authorize_url);
mAccessToken = mSession.getAccessToken();
configureToken();
}
public void setListener(TwDialogListener listener) {
mListener = listener;
}
private void configureToken()
{
if (mAccessToken != null)
{
twitterObj.setOAuthConsumer(mConsumerKey, mSecretKey);
twitterObj.setOAuthAccessToken(mAccessToken);
}
}
public boolean hasAccessToken() {
return (mAccessToken == null) ? false : true;
}
public void resetAccessToken() {
if (mAccessToken != null) {
mSession.resetAccessToken();
mAccessToken = null;
}
}
public String getUsername() {
return mSession.getUsername();
}
public void updateStatus(String status) throws Exception {
try {
twitterObj.updateStatus(status);
} catch (TwitterException e) {
throw e;
}
}
public void authorize()
{
mProgressDlg.setMessage("Loading ...");
mProgressDlg.show();
new Thread() {
#Override
public void run() {
String authUrl = "";
int what = 1;
try {
authUrl = mHttpOauthprovider.retrieveRequestToken(mHttpOauthConsumer, CALLBACK_URL);
what = 0;
} catch (Exception e) {
e.printStackTrace();
}
mHandler.sendMessage(mHandler.obtainMessage(what, 1, 0, authUrl));
}
}.start();
}
public void processToken(String callbackUrl)
{
mProgressDlg.setMessage("Finalizing ...");
mProgressDlg.show();
final String verifier = getVerifier(callbackUrl);
new Thread() {
#Override
public void run() {
int what = 1;
try {
mHttpOauthprovider.retrieveAccessToken(mHttpOauthConsumer,verifier);
mAccessToken = new AccessToken(mHttpOauthConsumer.getToken(),mHttpOauthConsumer.getTokenSecret());
configureToken();
User user = twitterObj.verifyCredentials();
mSession.storeAccessToken(mAccessToken, user.getName());
what = 0;
} catch (Exception e) {
e.printStackTrace();
}
mHandler.sendMessage(mHandler.obtainMessage(what, 2, 0));
}
}.start();
}
private String getVerifier(String callbackUrl) {
String verifier = "";
try {
callbackUrl = callbackUrl.replace("twitterapp", "http");
URL url = new URL(callbackUrl);
String query = url.getQuery();
String array[] = query.split("&");
for (String parameter : array) {
String v[] = parameter.split("=");
if (URLDecoder.decode(v[0]).equals(
oauth.signpost.OAuth.OAUTH_VERIFIER)) {
verifier = URLDecoder.decode(v[1]);
break;
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return verifier;
}
private void showLoginDialog(String url) {
final TwDialogListener listener = new TwDialogListener() {
#Override
public void onComplete(String value) {
processToken(value);
}
#Override
public void onError(String value) {
mListener.onError("Failed opening authorization page");
}
};
new TwitterDialog(context, url, listener).show();
}
#SuppressLint("HandlerLeak")
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
mProgressDlg.dismiss();
if (msg.what == 1)
{
if (msg.arg1 == 1)
mListener.onError("Error getting request token");
else
mListener.onError("Error getting access token");
}
else
{
if (msg.arg1 == 1)
showLoginDialog((String) msg.obj);
else
mListener.onComplete("");
}
}
};
public interface TwDialogListener {
public void onComplete(String value);
public void onError(String value);
}
}
/******************************************************/
Now Make "Twitt_LoginOnly" Class inside your project
import android.app.Activity;
import android.widget.Toast;
public class Twitt_LoginOnly {
private final Twitter_Handler mTwitter;
private final Activity activity;
public static interface LoginResult
{
public abstract void loginResult(String message);
}
public LoginResult loginCallback;
public Twitt_LoginOnly( Activity act, String consumer_key, String consumer_secret,LoginResult loginCallback) {
this.activity = act;
mTwitter = new Twitter_Handler(activity, consumer_key, consumer_secret);
this.loginCallback = loginCallback;
}
public void loginToTwitter()
{
mTwitter.setListener(mTwLoginDialogListener);
if (mTwitter.hasAccessToken())
{
// this will post data in asyn background thread
//showTwittDialog();
showToast("Already Logged in");
loginCallback.loginResult("Already Logged in");
}
else
{
mTwitter.authorize();
}
}
private final TwDialogListener mTwLoginDialogListener = new TwDialogListener() {
#Override
public void onError(String value) {
loginCallback.loginResult("Login Failed");
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
showToast("Login Failed");
mTwitter.resetAccessToken();
}
});
}
#Override
public void onComplete(String value)
{
//showTwittDialog();
loginCallback.loginResult("Login Successfully");
showToast("Login Successfully");
}
};
void showToast(final String msg)
{
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show();
}
});
}
}
/******************************************************/
Now Implement the Code in your Activity or Fragment Class
twitter_login = (ImageView) findViewById(R.id.twitter_login);
twitter_login.setOnClickListener(new OnClickListener()
{
public void onClick(View button)
{
Twitt_LoginOnly logintwitter = new Twitt_LoginOnly(Activity.this,
“YOUR TWITTER_CONSUMER_KEY”, “YOUR TWITTER_CONSUMER_SECRET”, new Twitt_LoginOnly.LoginResult()
{
#Override
public void loginResult(String message)
{
TwitterSession twittersession = new TwitterSession(Activity.this);
if (twittersession.getAccessToken() != null)
{
}
}
});
logintwitter.loginToTwitter();
}
});

Withings API integration in android

I am building Android App which shows Withings user's activity data in my Application.
But when I am trying to call refresh_token url:
https://oauth.withings.com/account/request_token?oauth_callback=******&oauth_consumer_key=******&oauth_nonce=******&oauth_signature=CcMrI7JaI8M5tEenye3s95wx%2BZ4%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1477386344&oauth_version=1.0
Then I am getting Invalid Signature response like below:
{
"status":0,
"message":"Invalid signature :\n CcMrI7JaI8M5tEenye3s95wx+Z4= .. \n{\"oauth_callback\":\"******\",\"oauth_consumer_key\":\"ce54bd6c671546ef8f8d394c0db4bd86688289d5f7fb39f371c5ebce4d01\",\"oauth_nonce\":\"f339febe0fdf4b53b953501e45a049db\",\"oauth_signature\":\"CcMrI7JaI8M5tEenye3s95wx+Z4=\",\"oauth_signature_method\":\"HMAC-SHA1\",\"oauth_timestamp\":\"1477386344\",\"oauth_version\":\"1.0\"}\n{\"base_string\":\"GET&https%3A%2F%2Foauth.withings.com%2Faccount%2Frequest_token&oauth_callback%3D******%26oauth_consumer_key%3D******%26oauth_nonce%3Df339febe0fdf4b53b953501e45a049db%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1477386344%26oauth_version%3D1.0\"}\n{\"key\":\"******\",\"secret\":\"******\",\"callback_url\":null}"
}
First of all you can use the scribe lib
On my sample code I have an Authentication Activity that has an WebView that the user uses to verify the app. Then that Authentication Activity sends back to the MainActivity the response.
On my example I am storing locally on a DB the authenticated user to not ask every time the credentials.
Also I am sending the access token to python server that will get all data stored on Withings Cloud to save it to my Server DB and represent them on a Graph Activity. {I have removed that part}
Because of the copy paste maybe something is missing but most of the code is here
public class WithingsApi extends DefaultApi10a {
private static final String AUTHORIZATION_URL ="https://oauth.withings.com/account/authorize?oauth_token=%s";
private static final String apiKey = "API_KEY";
private static final String apiSecret = "API_SECRET";
#Override
public String getRequestTokenEndpoint() {
return "https://oauth.withings.com/account/request_token";
}
#Override
public String getAccessTokenEndpoint() {
return "https://oauth.withings.com/account/access_token";
}
#Override
public String getAuthorizationUrl(Token requestToken) {
return String.format(getAUTHORIZATION_URL(), requestToken.getToken());
}
public static String getKey(){
return apiKey;
}
public static String getSecret(){
return apiSecret;
}
public static String getAUTHORIZATION_URL() {
return AUTHORIZATION_URL;
}
}
#SuppressLint("SetJavaScriptEnabled")
public class AuthenticationActivity extends Activity {
final String LOGTAG = "WITHINGS";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_authentication);
final WebView wvAuthorise = (WebView) findViewById(R.id.wvAuthorise);
wvAuthorise.getSettings().setJavaScriptEnabled(true);
wvAuthorise.setWebViewClient(new MyWebViewClient(wvAuthorise));
MainActivity.service = new ServiceBuilder().provider(WithingsApi.class)
.apiKey(WithingsApi.getKey())
.apiSecret(WithingsApi.getSecret())
.build();
new Thread(new Runnable() {
public void run() {
MainActivity.requestToken = MainActivity.service.getRequestToken();
final String authURL = MainActivity.service.getAuthorizationUrl(MainActivity.requestToken);
wvAuthorise.post(new Runnable() {
#Override
public void run() {
wvAuthorise.loadUrl(authURL);
}
});
}
}).start();
}
class MyWebViewClient extends WebViewClient{
WebView wvAuthorise;
MyWebViewClient(WebView wv){
wvAuthorise = wv;
}
#Override
public void onPageFinished(WebView view, String url) {
getUSERID(url);
}
}
private void getUSERID(final String url) {
try {
String divStr = "userid=";
int first = url.indexOf(divStr);
if(first!=-1){
final String userid = url.substring(first+divStr.length());
Intent intent = new Intent();
intent.putExtra("USERID",userid);
setResult(RESULT_OK,intent);
finish();
}
else
{
//...
}
} catch (Exception e) {
Log.e(LOGTAG,e.getMessage());
//...
}
}
}
public class MainActivity extends FragmentActivity {
public static OAuthService service;
public static Token requestToken;
String secret, token;
Token accessToken;
String userId = "";
private UsersDataSource datasource;
private TextView nameTV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_mainActivity = this;
nameTV = (TextView) findViewById(R.id.nameTitleTextView);
nameTV.setText("--");
getCredentials();
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == AUTHENTICATION_REQUEST) {
if (resultCode == RESULT_OK) {
Bundle extras = intent.getExtras();
if (extras != null) {
userId = extras.getString("USERID");
getAccessTokenThread.execute((Object) null);
}
}
}
}
#Override
protected void onResume() {
datasource.open();
super.onResume();
}
#Override
protected void onPause() {
datasource.close();
super.onPause();
}
private void getCredentials() {
try {
datasource = new UsersDataSource(this);
datasource.open();
List<User> users = datasource.getAllUsers();
if (users.isEmpty()) {
startAuthenticationActivity();
} else {
// TODO load all users and if isn't anyone correct
// startAuthenticationActivity
secret = users.get(0).getSecret();
token = users.get(0).getToken();
userId = users.get(0).getUserId();
Log.i(LOGTAG, "secret : " + secret);
Log.i(LOGTAG, "token : " + token);
Log.i(LOGTAG, "userId : " + userId);
try {
service = new ServiceBuilder().provider(WithingsApi.class)
.apiKey(WithingsApi.getKey())
.apiSecret(WithingsApi.getSecret()).build();
accessToken = new Token(token, secret);
loadData();
} catch (Exception ex) {
startAuthenticationActivity();
}
}
} catch (Exception ex) {
Log.e(LOGTAG, "try on create" + ex.getLocalizedMessage());
}
}
private void startAuthenticationActivity() {
Intent intent = new Intent(this,
ics.forth.withings.authentication.AuthenticationActivity.class);
startActivityForResult(intent, AUTHENTICATION_REQUEST);
}
AsyncTask<Object, Object, Object> getAccessTokenThread = new AsyncTask<Object, Object, Object>() {
#Override
protected Object doInBackground(Object... params) {
accessToken = service
.getAccessToken(requestToken, new Verifier(""));
secret = accessToken.getSecret();
token = accessToken.getToken();
return null;
}
#Override
protected void onPostExecute(Object result) {
// authentication complete send the token,secret,userid, to python
datasource.createUser(token, secret, userId);
loadData();
};
};
}
UPDATE
OAuthService class is from Scribe
Token class is from Scribe
UserDataSource class is a DB Helper Class more here

How to implement paho MQTT client in android that has to be accessed in multiple activities

I am having an app that has multiple activities and uses MQTT.
I am using the paho client in gradle dependencies as follows
compile 'org.eclipse.paho:org.eclipse.paho.android.service:1.0.3-SNAPSHOT'
compile 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.0.3-SNAPSHOT'
I would be using username and password to connect to the broker and some activities would be using diffrent user name and password.
currently I am handling the connect,subscribeand publish tasks in each activity as in the code that I will include below. As the activities get more and more I am having issues. Please suggest me how I can port the code to a service or singleton so that it can be reused and become efficient.
Here is one of the activities
package net.kindows.chitchat;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.pixplicity.easyprefs.library.Prefs;
import net.kindows.SplashScreen;
import net.kindows.common.ApplicationLoader;
import net.kindows.common.utils;
import net.kindows.intlPhone.IntlPhoneInput;
import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import butterknife.Bind;
import butterknife.ButterKnife;
import de.keyboardsurfer.android.widget.crouton.Crouton;
import static net.kindows.common.ApplicationLoader._toast;
public class LoginActivity extends AppCompatActivity implements MqttCallback {
private static final String TAG = "LoginActivity";
private static final int REQUEST_SIGNUP = 0;
private static final int REQUEST_PAS_RESET = 1;
private static final Integer LOGGED_OUT = 0;
private static final Integer LOGGING_IN = 1;
private static final Integer WAITING_FOR_SING_IN_ACK = 2;
private static final Integer LOGGED_IN = 3;
private static final Integer VERIFICATION_FAILED = 4;
#Bind(R.id.input_password)
EditText _passwordText;
#Bind(R.id.btn_login)
Button _loginButton;
#Bind(R.id.link_signup)
TextView _signupLink;
#Bind(R.id.my_phone_input)
IntlPhoneInput _phoneInputView;
String sUserName = null;
String sPassword = null;
String sDestination = null;
String sMessage = null;
private Integer state;
private Handler han = new Handler();
private MqttConnectOptions connOpt;
private ProgressDialog _progressDialog;
/*
MQTT mqtt = null;
FutureConnection connection = null;*/
private boolean isMinimized = false;
private String clientId;
private Handler loginAgain = new Handler();
private Handler timeout;
private MqttAndroidClient client;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ButterKnife.bind(this);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//connect();
_loginButton.setEnabled(false);
// _phoneInputView.setNumber(ApplicationLoader.getSim1number(LoginActivity.this));
_phoneInputView.setOnValidityChange(new IntlPhoneInput.IntlPhoneInputListener() {
#Override
public void done(View view, boolean isValid) {
if (isValid) {
_loginButton.setEnabled(true);
} else _loginButton.setEnabled(false);
}
});
_loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!ApplicationLoader.isConnected(LoginActivity.this, true)) {
} else login();
}
});
_signupLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Start the Signup activity
Prefs.putInt(getString(R.string.key_reset_pass), 2);
Intent intent = new Intent(getApplicationContext(), SignUpActivity.class);
startActivityForResult(intent, REQUEST_SIGNUP);
}
});
state = LOGGED_OUT;
connOpt = new MqttConnectOptions();
connOpt.setCleanSession(true);
connOpt.setKeepAliveInterval(30);
connOpt.setCleanSession(true);
clientId = ApplicationLoader.getClientId(LoginActivity.this);
client = new MqttAndroidClient(this, "tcp://104.131.50.64:1883", clientId, MqttAndroidClient.Ack.AUTO_ACK);//this,"tcp://104.131.50.64:1883", "app1", null);
}
#Override
protected void onStop() {
super.onStop();
isMinimized = true;
// super.onDestroy();
try {
client.close();
} catch (Exception e) {
// client.unregisterResources();
e.printStackTrace();
}
Crouton.cancelAllCroutons();
loginAgain.removeCallbacks(null);
han.removeCallbacks(null);
}
#Override
protected void onStart() {
super.onStart();
// Do not go to splash screen if came from signup activity
if (isMinimized && Prefs.getBoolean(getString(R.string.show_splash), true)) {
isMinimized = false;
han.removeCallbacks(null);
startActivity(new Intent(this, SplashScreen.class));
finish();
}
Prefs.putBoolean(getString(R.string.show_splash), true);
if (utils.getLoginState_login()) {
han.removeCallbacks(null);
utils._startActivity(this, MainActivity.class);
finish();
}
}
#Override
protected void onResume() {
super.onResume();
if (utils.getLoginState_login()) {
han.removeCallbacks(null);
utils._startActivity(this, MainActivity.class);
finish();
}
ApplicationLoader.isConnected(this, true);
}
public void login() {
Log.d(TAG, getString(R.string.login));
_toast(getString(R.string.logging_in), LoginActivity.this);
try {
client.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
client.close();
} catch (Exception e) {
e.printStackTrace();
}
// Disable login button for 5 secs
final boolean lastLoginState = _loginButton.isEnabled();
_loginButton.setEnabled(false);
loginAgain.postDelayed(new Runnable() {
#Override
public void run() {
_loginButton.setEnabled(lastLoginState);
}
}, 5000);
_progressDialog = new ProgressDialog(LoginActivity.this,
R.style.AppTheme_Dark_Dialog);
// String phone = _phoneText.getText().toString();
String password = _passwordText.getText().toString();
String numb = _phoneInputView.getNumber().replace("+", "");
connectMQTT(numb, password);
_progressDialog.setIndeterminate(true);
_progressDialog.setMessage("Authenticating...");
_progressDialog.show();
han.postDelayed(
new Runnable() {
public void run() { // On complete call either onLoginSuccess or onLoginFailed
//onLoginSuccess();
onLoginFailed();
_progressDialog.dismiss();
}
}, ApplicationLoader.timeOUT);
}
private void publish2MQQT(MqttAndroidClient client1, String topic, String msg) throws MqttException {
if (client1 != null) {
MqttMessage msg2 = new MqttMessage();
msg2.setPayload(msg.getBytes());
client1.publish(topic, msg2, this, new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
// _sendErrorLog("on sucess of publish");
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
// _sendErrorLog("on fail of publish e= " + exception.getMessage());
_progressDialog.dismiss();
_toast((exception != null ? exception.getMessage() : ""), LoginActivity.this);
}
});
// Log.e("mqtt ", "published " + msg);
}
}
private void _sendErrorLog(String s) {
Log.e("LOG", s);
}
private void connectMQTT(final String user, final String pass) {
Log.e("connectMQTT", "1");
try {
connOpt.setUserName(user);
connOpt.setPassword(pass.toCharArray());
_sendErrorLog("on connteing with " + user + " " + pass);
client.connect(connOpt, this, new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
_sendErrorLog("on success of connect");
try {
client.subscribe("astr/app/iremote/" + user.replace("+", ""), 0, this, new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
_sendErrorLog("on sucess of subscribe");
// TODO: Implement your own authentication logic here.
JsonObject msg = new JsonObject();
msg.addProperty("u", user);
msg.addProperty("P", pass);
sUserName = user;
sPassword = pass;
sDestination = "astr/admin/signin";
sMessage = msg.toString();
state = LOGGING_IN;
try {
Log.e("register", "publishing signin message");
if (client == null) {
Log.e("register", "publishing register message client is null");
}
publish2MQQT(client, sDestination, sMessage);
state = WAITING_FOR_SING_IN_ACK;
} catch (MqttException e) {
e.printStackTrace();
Log.e("register", "got exception in publish " + e.toString());
_progressDialog.dismiss();
_toast(e.getMessage(), LoginActivity.this);
}
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
_sendErrorLog("on failure of subscribe " + exception.getMessage());
_progressDialog.dismiss();
_toast((exception != null ? exception.getMessage() : ""), LoginActivity.this);
}
});
// client.subscribe("astr/app/iremote/" + _num_2b_verified.replace("+", ""));
} catch (MqttException | NullPointerException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
_sendErrorLog("on failure of connect" + exception.getMessage());
han.removeCallbacks(null);
try {
_progressDialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
_toast((exception != null ? exception.getMessage() : ""), LoginActivity.this);
}
});
client.setCallback(this);
} catch (MqttException e) {
e.printStackTrace();
Log.e("connectMQTT", "got exception :: " + e.toString());
}
}
#Override
public void connectionLost(Throwable throwable) {
Log.e("connection", "lost");
//connectMQTT();
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
client.close();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
String msgRecived = new String(mqttMessage.getPayload());
/* Log.e("message arrived", "-------------------------------------------------");
Log.e("message arrived", "| Topic:" + s);*/
Log.e("message arrived", "| Message: " + msgRecived);
/*Log.e("message arrived" , "-------------------------------------------------");*/
if (state.equals(WAITING_FOR_SING_IN_ACK)) {
han.removeCallbacks(null);
JsonParser jp = new JsonParser();
JsonObject reply = (JsonObject) jp.parse(msgRecived);
if (reply.get("s").getAsInt() == 200) {
_toast(getString(R.string.logged_in), LoginActivity.this);
_progressDialog.dismiss();
_phoneInputView.setVisibility(View.GONE);
_passwordText.setVisibility(View.VISIBLE);
_loginButton.setText(R.string.logged_in);
_loginButton.setEnabled(true);
state = LOGGED_IN;
utils.storeLoginState(true, sUserName, sPassword);
try {
client.close();
} catch (Exception e) {
e.printStackTrace();
}
state = LOGGED_IN;
han.removeCallbacks(null);
try {
client.close();
} catch (Exception e) {
e.printStackTrace();
}
startActivity(new Intent(this, MainActivity.class));
//finish();
} else {
state = VERIFICATION_FAILED;
utils.storeLoginState(false, "", "");
onLoginFailed();
}
}
}
#Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_SIGNUP) {
if (resultCode == RESULT_OK) {
// TODO: Implement successful signup logic here
// By default we just finish the Activity and log them in automatically
this.finish();
}
}
}
#Override
public void onBackPressed() {
// Disable going back to the MainActivity
moveTaskToBack(true);
}
public void onLoginFailed() {
// ApplicationLoader._toast("Login failed",LoginActivity.this);
_toast(getString(R.string.log_in_failed), LoginActivity.this);
_passwordText.setVisibility(View.VISIBLE);
_phoneInputView.setVisibility(View.VISIBLE);
_loginButton.setEnabled(false);
// Enable Login after 5000 ms with editing the number
loginAgain.postDelayed(new Runnable() {
#Override
public void run() {
_loginButton.setEnabled(_phoneInputView.isValid());
}
}, 5000);
}
#Override
public void onPause() {
super.onPause();
//disconnect();
}
public void resetPass(View view) {
// Start the Signup activity
Prefs.putInt(getString(R.string.key_reset_pass), 1);
Intent intent = new Intent(getApplicationContext(), SignUpActivity.class);
startActivityForResult(intent, REQUEST_PAS_RESET);
}
}
I believe the best option for you would be to implement those same functionalities in a Fragment. I won't read through your whole source code because it's enormous and I ain't got time for that, but I'll give you some ideas and directions and you can migrate it yourself.
Step 1: Create a MQTTFragment:
public class MQTTFragment extends Fragment implements MqttCallback {
public static final String TAG = "MQTTFragment.tag";
#Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// avoid this frag getting destroyed during rotation
setRetainInstance(true);
}
// DO NOT #Override onCreateView, this fragment have no views
// Put here ALL the code related to MQTT,
// any functionality you want to be able to call from Activity, make public, all the rest is private
// this fragment should also remember the current state of the connection
// this fragment can also have interface and listener pattern in case to past result back to activity.
... your mqtt code
}
Step 2: Every activity u want to use MQTT functionality includes the MQTTFragment
public class MyActivity extends AppCompatActivity {
private MQTTFragment mqttFragment;
// during onCreate you get or create the fragment
#Override public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState == null) {
mqttFragment = new MQTTFragment();
getSupportFragmentManager()
.beginTransaction()
.add(mqttFragment, MQTTFragment.TAG)
.commit();
} else {
mqttFragment =
(MQTTFragment) getSupportFragmentManager()
.findFragmentByTag(MQTTFragment.TAG);
}
}
// now on this activity you can call anything MQTT related functionality from the Fragment
}

login issue using twitter api in android

what is the procedure to login throw twitter api1.1.
i have used old api that will show me twitter connection failed because of api 1 is deprecated.
private final TwDialogListener mTwLoginDialogListener = new TwDialogListener()
{
public void onComplete(String value)
{
getTwitterDetail();
}
public void onError(String value) {
Toast.makeText(LoginActivity.this, "Twitter connection failed", Toast.LENGTH_LONG).show();
}
};
LOG
{"errors": [{"message": "The Twitter REST API v1 is no longer active.
Please migrate to API v1.1. https://dev.twitter.com/docs/api/1.1/overview.", "code": 68}]}
As you see from error log API v.1 is no longer active and everybody must migrate to v1.1. In API v1.1. you must log in via OAUTH to get connected. So you also have to register your app on dev.twitter.com.
You can find below example here
public class Main extends Activity{
public static final String TAG = Main.class.getSimpleName();
public static final String TWITTER_OAUTH_REQUEST_TOKEN_ENDPOINT = "..."; //cannot share more then 2 lins, sorry
public static final String TWITTER_OAUTH_ACCESS_TOKEN_ENDPOINT = "...";
public static final String TWITTER_OAUTH_AUTHORIZE_ENDPOINT = "...";
private CommonsHttpOAuthProvider commonsHttpOAuthProvider;
private CommonsHttpOAuthConsumer commonsHttpOAuthConsumer;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
commonsHttpOAuthProvider = new CommonsHttpOAuthProvider(TWITTER_OAUTH_REQUEST_TOKEN_ENDPOINT,
TWITTER_OAUTH_ACCESS_TOKEN_ENDPOINT, TWITTER_OAUTH_AUTHORIZE_ENDPOINT);
commonsHttpOAuthConsumer = new CommonsHttpOAuthConsumer(getString(R.string.twitter_oauth_consumer_key),
getString(R.string.twitter_oauth_consumer_secret));
commonsHttpOAuthProvider.setOAuth10a(true);
TwDialog dialog = new TwDialog(this, commonsHttpOAuthProvider, commonsHttpOAuthConsumer,
dialogListener, R.drawable.android);
dialog.show();
}
private Twitter.DialogListener dialogListener = new Twitter.DialogListener() {
public void onComplete(Bundle values) {
String secretToken = values.getString("secret_token");
Log.i(TAG,"secret_token=" + secretToken);
String accessToken = values.getString("access_token");
Log.i(TAG,"access_token=" + accessToken);
new Tweeter(accessToken,secretToken).tweet(
"Tweet from sample Android OAuth app. unique code: " + System.currentTimeMillis());
}
public void onTwitterError(TwitterError e) { Log.e(TAG,"onTwitterError called for TwitterDialog",
new Exception(e)); }
public void onError(DialogError e) { Log.e(TAG,"onError called for TwitterDialog", new Exception(e)); }
public void onCancel() { Log.e(TAG,"onCancel"); }
};
public static final Pattern ID_PATTERN = Pattern.compile(".*?\"id_str\":\"(\\d*)\".*");
public static final Pattern SCREEN_NAME_PATTERN = Pattern.compile(".*?\"screen_name\":\"([^\"]*).*");
public class Tweeter {
protected CommonsHttpOAuthConsumer oAuthConsumer;
public Tweeter(String accessToken, String secretToken) {
oAuthConsumer = new CommonsHttpOAuthConsumer(getString(R.string.twitter_oauth_consumer_key),
getString(R.string.twitter_oauth_consumer_secret));
oAuthConsumer.setTokenWithSecret(accessToken, secretToken);
}
public boolean tweet(String message) {
if (message == null && message.length() > 140) {
throw new IllegalArgumentException("message cannot be null and must be less than 140 chars");
}
// create a request that requires authentication
try {
HttpClient httpClient = new DefaultHttpClient();
Uri.Builder builder = new Uri.Builder();
builder.appendPath("statuses").appendPath("update.json")
.appendQueryParameter("status", message);
Uri man = builder.build();
HttpPost post = new HttpPost("http://twitter.com" + man.toString());
oAuthConsumer.sign(post);
HttpResponse resp = httpClient.execute(post);
String jsonResponseStr = convertStreamToString(resp.getEntity().getContent());
Log.i(TAG,"response: " + jsonResponseStr);
String id = getFirstMatch(ID_PATTERN,jsonResponseStr);
Log.i(TAG,"id: " + id);
String screenName = getFirstMatch(SCREEN_NAME_PATTERN,jsonResponseStr);
Log.i(TAG,"screen name: " + screenName);
final String url = MessageFormat.format("https://twitter.com/#!/{0}/status/{1}",screenName,id);
Log.i(TAG,"url: " + url);
Runnable runnable = new Runnable() {
public void run() {
((TextView)Main.this.findViewById(R.id.textView)).setText("Tweeted: " + url);
}
};
Main.this.runOnUiThread(runnable);
return resp.getStatusLine().getStatusCode() == 200;
} catch (Exception e) {
Log.e(TAG,"trying to tweet: " + message, e);
return false;
}
}
}
public static String convertStreamToString(java.io.InputStream is) {
try {
return new java.util.Scanner(is).useDelimiter("\\A").next();
} catch (java.util.NoSuchElementException e) {
return "";
}
}
public static String getFirstMatch(Pattern pattern, String str){
Matcher matcher = pattern.matcher(str);
if(matcher.matches()){
return matcher.group(1);
}
return null;
}

Upgrage Twitter login to use Twitter API 1.1

I use this sample to login Twitter, post status and photo. I used it for a long time. Now Twitter requires upgrading from Twitter API 1.0 to Twitter API 1.1. What do I have to do to upgrade it? I tried to replace the old lib with this lib and there is no problem so far but I'm scared of I didn't do the change completely.
You must log in via OAUTH (https://dev.twitter.com/docs/auth/using-oauth) to get connected. So you also have to register your app on dev.twitter.com.
You can find below example here https://github.com/browep/Android-OAuth-Twitter-Example.
public class Main extends Activity{
public static final String TAG = Main.class.getSimpleName();
public static final String TWITTER_OAUTH_REQUEST_TOKEN_ENDPOINT = "..."; //cannot share more then 2 lins, sorry
public static final String TWITTER_OAUTH_ACCESS_TOKEN_ENDPOINT = "...";
public static final String TWITTER_OAUTH_AUTHORIZE_ENDPOINT = "...";
private CommonsHttpOAuthProvider commonsHttpOAuthProvider;
private CommonsHttpOAuthConsumer commonsHttpOAuthConsumer;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
commonsHttpOAuthProvider = new CommonsHttpOAuthProvider(TWITTER_OAUTH_REQUEST_TOKEN_ENDPOINT,
TWITTER_OAUTH_ACCESS_TOKEN_ENDPOINT, TWITTER_OAUTH_AUTHORIZE_ENDPOINT);
commonsHttpOAuthConsumer = new CommonsHttpOAuthConsumer(getString(R.string.twitter_oauth_consumer_key),
getString(R.string.twitter_oauth_consumer_secret));
commonsHttpOAuthProvider.setOAuth10a(true);
TwDialog dialog = new TwDialog(this, commonsHttpOAuthProvider, commonsHttpOAuthConsumer,
dialogListener, R.drawable.android);
dialog.show();
}
private Twitter.DialogListener dialogListener = new Twitter.DialogListener() {
public void onComplete(Bundle values) {
String secretToken = values.getString("secret_token");
Log.i(TAG,"secret_token=" + secretToken);
String accessToken = values.getString("access_token");
Log.i(TAG,"access_token=" + accessToken);
new Tweeter(accessToken,secretToken).tweet(
"Tweet from sample Android OAuth app. unique code: " + System.currentTimeMillis());
}
public void onTwitterError(TwitterError e) { Log.e(TAG,"onTwitterError called for TwitterDialog",
new Exception(e)); }
public void onError(DialogError e) { Log.e(TAG,"onError called for TwitterDialog", new Exception(e)); }
public void onCancel() { Log.e(TAG,"onCancel"); }
};
public static final Pattern ID_PATTERN = Pattern.compile(".*?\"id_str\":\"(\\d*)\".*");
public static final Pattern SCREEN_NAME_PATTERN = Pattern.compile(".*?\"screen_name\":\"([^\"]*).*");
public class Tweeter {
protected CommonsHttpOAuthConsumer oAuthConsumer;
public Tweeter(String accessToken, String secretToken) {
oAuthConsumer = new CommonsHttpOAuthConsumer(getString(R.string.twitter_oauth_consumer_key),
getString(R.string.twitter_oauth_consumer_secret));
oAuthConsumer.setTokenWithSecret(accessToken, secretToken);
}
public boolean tweet(String message) {
if (message == null && message.length() > 140) {
throw new IllegalArgumentException("message cannot be null and must be less than 140 chars");
}
// create a request that requires authentication
try {
HttpClient httpClient = new DefaultHttpClient();
Uri.Builder builder = new Uri.Builder();
builder.appendPath("statuses").appendPath("update.json")
.appendQueryParameter("status", message);
Uri man = builder.build();
HttpPost post = new HttpPost("http://twitter.com" + man.toString());
oAuthConsumer.sign(post);
HttpResponse resp = httpClient.execute(post);
String jsonResponseStr = convertStreamToString(resp.getEntity().getContent());
Log.i(TAG,"response: " + jsonResponseStr);
String id = getFirstMatch(ID_PATTERN,jsonResponseStr);
Log.i(TAG,"id: " + id);
String screenName = getFirstMatch(SCREEN_NAME_PATTERN,jsonResponseStr);
Log.i(TAG,"screen name: " + screenName);
final String url = MessageFormat.format("https://twitter.com/#!/{0}/status/{1}",screenName,id);
Log.i(TAG,"url: " + url);
Runnable runnable = new Runnable() {
public void run() {
((TextView)Main.this.findViewById(R.id.textView)).setText("Tweeted: " + url);
}
};
Main.this.runOnUiThread(runnable);
return resp.getStatusLine().getStatusCode() == 200;
} catch (Exception e) {
Log.e(TAG,"trying to tweet: " + message, e);
return false;
}
}
}
public static String convertStreamToString(java.io.InputStream is) {
try {
return new java.util.Scanner(is).useDelimiter("\\A").next();
} catch (java.util.NoSuchElementException e) {
return "";
}
}
public static String getFirstMatch(Pattern pattern, String str){
Matcher matcher = pattern.matcher(str);
if(matcher.matches()){
return matcher.group(1);
}
return null;
}

Categories

Resources