Withings API integration in android - 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

Related

i am using quickblox sdk v 2.0f for chat/audio/video call in our app &facing issue that when app runs in background user will not get calls

We are using qucikblox sdk 2.0 in online consultation mobile application in both platform ios & android. But recently facing issue that if A user device is locked or A user is not using app and if B user calls A user over audio/video A user will not get call.
Case 1-- Device locked app is in foreground User A will be getting a call from user B but user A will not get to know about a call when user A unlock device then only user A can see call notification.
Case 2-- App is in background & device is unlocked User A will not get a audio.video call, evn push message of chats also not receiving
Create a sticky service which will run in background even activity destroy, this service is responsible for QBsession and all other operations so it will detect call in background so you will create Session in service , not in CallActivity. Iam successfully implements this and iam successfully receiving calls in background by this.
public class BloxService extends Service implements QBRTCClientSessionCallbacks {
private QBChatService chatService;
private volatile boolean resultReceived = true;
static final String APP_ID = "";
static final String AUTH_KEY = "";
static final String AUTH_SECRET = "";
static final String ACCOUNT_KEY = "";
private QBRTCClient rtcClient;
public static BloxService bloxService;
private static final String TAG = "BloxService";
public boolean isSessionRunning;
public boolean isCallRunning;
private Date tokenExpirationDate;
private QBAuth qbAuth;
private AppPrefs prefs;
private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
/*boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);*/
NetworkInfo currentNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
//NetworkInfo otherNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);
if(currentNetworkInfo!=null && currentNetworkInfo.isConnected()){
if(!QBChatService.getInstance().isLoggedIn()){
if(!isSessionRunning) {
initializeQb();
}
}
}
}
};
#Override
public void onCreate() {
super.onCreate();
// prefs = AppPrefs.getInstance(getApplicationContext()); // for testing we put this line on start
registerReceiver(this.mConnReceiver,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d("bloxservice","onDestroy");
try{
unregisterReceiver(mConnReceiver);
}catch (Exception e){
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId){
prefs = AppPrefs.getInstance(getApplicationContext());
if (prefs.getData(IS_USER_LOGIN, false)) {
Log.d("bloxservice","start");
try {
if (!QBChatService.getInstance().isLoggedIn()) {
initializeQb();
}
}catch (Exception e)
{
initializeQb();
}
bloxService=this;
}
else {
stopSelf();
}
return START_STICKY;
}
public static BloxService getBloxService() {
return bloxService;
}
public void initializeQb(){
QBSettings.getInstance().init(getApplicationContext(), APP_ID, AUTH_KEY, AUTH_SECRET);
QBSettings.getInstance().setAccountKey(ACCOUNT_KEY);
QBChatService.setDebugEnabled(true);
// added on 20 july
QBChatService.setDefaultAutoSendPresenceInterval(60);
QBChatService.ConfigurationBuilder chatServiceConfigurationBuilder = new QBChatService.ConfigurationBuilder();
chatServiceConfigurationBuilder.setSocketTimeout(60); //Sets chat socket's read timeout in seconds
chatServiceConfigurationBuilder.setKeepAlive(true); //Sets connection socket's keepAlive option.
QBChatService.setConfigurationBuilder(chatServiceConfigurationBuilder);
// QBChatService.getInstance().startAutoSendPresence(10);// added on 20 july
chatService = QBChatService.getInstance();
/* tokenExpirationDate = qbAuth.getTokenExpirationDate();
try {
String Token= QBAuth.getSession().toString();
QBAuth.createFromExistentToken()
} catch (QBResponseException e) {
e.printStackTrace();
}
*/
if(AppPrefs.getInstance(this).getData(Constants.PrefsConstatnt.IS_USER_LOGIN,false)){
Log.e("Login Process", "Started");
isSessionRunning=true;
String userId=AppPrefs.getInstance(this).getData(Constants.PrefsConstatnt.USER_ID,"");
String name=AppPrefs.getInstance(this).getData(Constants.PrefsConstatnt.USER_NAME,"");
String picUrl=AppPrefs.getInstance(this).getData(Constants.PrefsConstatnt.USER_IMAGE,"");
String phone=prefs.getData(Constants.PrefsConstatnt.USER_PHONE, "");
if(name.isEmpty()){
name=userId;
}
createAppSession(Integer.parseInt(userId)<10?"0"+userId:userId,name,userId,picUrl,phone);
}
}
private void createAppSession(final String userId, final String name,final String exId,final String picUrl,final String phone) {
QBAuth.createSession(new QBEntityCallback<QBSession>() {
#Override
public void onSuccess(QBSession qbSession, Bundle bundle) {
loadUsers(userId, name, exId,picUrl,phone);
final SharedPreferences prefs = getGCMPreferences(getApplicationContext());
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
if (registrationId.isEmpty()) {
}
// Subscribe to Push Notifications
//subscribeToPushNotifications(registrationId);
}
#Override
public void onError(QBResponseException exc) {
exc.printStackTrace();
isSessionRunning=false;
}
});
}
//QBUser users;
public void loadUsers(String userId,String name,String exId,String picUrl,String phone) {
final QBUser userr = new QBUser(userId, DataHolder.PASSWORD);
userr.setFullName(name);
userr.setExternalId(exId);
userr.setCustomData(picUrl);
userr.setPhone(phone);
QBUsers.signUp(userr, new QBEntityCallback<QBUser>() {
#Override
public void onSuccess(QBUser user, Bundle args) {
createSession(userr.getLogin(), userr.getPassword());
}
#Override
public void onError(QBResponseException error) {
error.printStackTrace();
QBUsers.signIn(userr, new QBEntityCallback<QBUser>() {
#Override
public void onSuccess(QBUser user, Bundle args) {
createSession(userr.getLogin(), userr.getPassword());
}
#Override
public void onError(QBResponseException error) {
error.printStackTrace();
isSessionRunning = false;
}
});
}
});
}
private void createSession(final String login, final String password) {
final QBUser user = new QBUser(login, password);
QBAuth.createSession(login, password, new QBEntityCallback<QBSession>() {
#Override
public void onSuccess(QBSession session, Bundle bundle) {
user.setId(session.getUserId());
Log.e("User" + session.getUserId(), "Login");
QBSettings.getInstance().fastConfigInit(APP_ID, AUTH_KEY, AUTH_SECRET);
sendRegistrationToServer(AppPrefs.getInstance(BloxService.this).getData(Constants.PrefsConstatnt.DEVICE_TOKEN, ""));
DataHolder.setLoggedUser(user);
if (chatService.isLoggedIn()) {
resultReceived = true;
initQBRTCClient();
isSessionRunning = false;
} else {
chatService.login(user, new QBEntityCallback<Void>() {
#Override
public void onSuccess(Void result, Bundle bundle) {
initQBRTCClient();
resultReceived = true;
isSessionRunning = false;
}
#Override
public void onError(QBResponseException exc) {
resultReceived = true;
isSessionRunning = false;
}
});
}
/* QBRosterListener rosterListener = new QBRosterListener() {
#Override
public void entriesDeleted(Collection<Integer> userIds) {
Log.d("mayanks","changed");
}
#Override
public void entriesAdded(Collection<Integer> userIds) {
Log.d("mayanks","changed");
}
#Override
public void entriesUpdated(Collection<Integer> userIds) {
Log.d("mayanks","changed");
}
#Override
public void presenceChanged(QBPresence presence) {
Log.d("mayanks","changed");
}
};
QBSubscriptionListener subscriptionListener = new QBSubscriptionListener() {
#Override
public void subscriptionRequested(int userId) {
}
};
QBRoster chatRoster = QBChatService.getInstance().getRoster(QBRoster.SubscriptionMode.mutual, subscriptionListener);
chatRoster.addRosterListener(rosterListener);
Collection<QBRosterEntry> entries = chatRoster.getEntries();
QBPresence presence = chatRoster.getPresence(9);
if (presence!=null) {
if (presence.getType() == QBPresence.Type.online) {
Log.d("mayanks","online");
// User is online
}else{
Log.d("mayanks","offline");
// User is offline
}
}*/
}
#Override
public void onError(QBResponseException exc) {
resultReceived = true;
isSessionRunning = false;
}
});
}
private void sendRegistrationToServer(final String token) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
final SharedPreferences prefs = getGCMPreferences(getApplicationContext());
String deviceID = prefs.getString(PROPERTY_DEVICE_ID, null);
if(deviceID==null)
{
deviceID=DeviceUtils.getDeviceUid();
storeDeviceId(getApplicationContext(),deviceID);
}
QBSubscription qbSubscription = new QBSubscription();
qbSubscription.setNotificationChannel(QBNotificationChannel.GCM);
qbSubscription.setDeviceUdid(deviceID);
qbSubscription.setRegistrationID(token);
qbSubscription.setEnvironment(QBEnvironment.DEVELOPMENT); // Don't forget to change QBEnvironment to PRODUCTION when releasing application
QBPushNotifications.createSubscription(qbSubscription,
new QBEntityCallback<ArrayList<QBSubscription>>() {
#Override
public void onSuccess(ArrayList<QBSubscription> qbSubscriptions, Bundle bundle) {
Log.e(TAG, "Successfully subscribed for QB push messages");
//saveGcmRegIdToPreferences(gcmRegId);
isSessionRunning=false;
}
#Override
public void onError(QBResponseException error) {
Log.e(TAG, "Unable to subscribe for QB push messages; " + error.toString());
isSessionRunning=false;
}
});
}
});
}
#Override
public void onReceiveNewSession(final QBRTCSession qbrtcSession) {
Log.d("bloxservice","CallRecive");
new Handler().post(new Runnable() {
#Override
public void run() {
if(!isCallRunning) {
DataHolder.incomingSession = qbrtcSession;
/* Map<String,String> userInfo = qbrtcSession.getUserInfo();
String s=userInfo.get("mayank");*/
Intent intent = new Intent(BloxService.this, CallActivity.class);
intent.putExtra("incoming", true);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else{
Log.e("User","Busy");
}
}
});
}
#Override
public void onUserNotAnswer(QBRTCSession qbrtcSession, Integer integer) {
// ToastUtil.showShortToast(this, "no answer");
}
#Override
public void onCallRejectByUser(QBRTCSession qbrtcSession, Integer integer, Map<String, String> map) {
// ToastUtil.showShortToast(this,"rejected");
}
#Override
public void onCallAcceptByUser(QBRTCSession qbrtcSession, Integer integer, Map<String, String> map) {
//ToastUtil.showShortToast(this,"accepted");
}
#Override
public void onReceiveHangUpFromUser(QBRTCSession qbrtcSession, Integer integer, Map<String, String> map) {
}
#Override
public void onUserNoActions(QBRTCSession qbrtcSession, Integer integer) {
// ToastUtil.showShortToast(this,"no Action");
}
#Override
public void onSessionClosed(QBRTCSession qbrtcSession) {
// ToastUtil.showShortToast(this,"onSessionClosed");
}
#Override
public void onSessionStartClose(QBRTCSession qbrtcSession) {
// ToastUtil.showShortToast(this,"onSessionStartClose");
}
private void initQBRTCClient() {
rtcClient = QBRTCClient.getInstance(this);
QBVideoChatWebRTCSignalingManager qbChatService = QBChatService.getInstance().getVideoChatWebRTCSignalingManager();
if (qbChatService != null) {
qbChatService.addSignalingManagerListener(new QBVideoChatSignalingManagerListener() {
#Override
public void signalingCreated(QBSignaling qbSignaling, boolean createdLocally) {
if (!createdLocally) {
rtcClient.addSignaling((QBWebRTCSignaling) qbSignaling);
}
}
});
QBRTCConfig.setMaxOpponentsCount(2);
QBRTCConfig.setDisconnectTime(40);
QBRTCConfig.setAnswerTimeInterval(30l);
QBRTCConfig.setDebugEnabled(true);
rtcClient.addSessionCallbacksListener(this);
rtcClient.prepareToProcessCalls();
QBChatService.getInstance().addConnectionListener(new AbstractConnectionListener() {
#Override
public void connectionClosedOnError(Exception e) {
}
#Override
public void reconnectionSuccessful() {
}
#Override
public void reconnectingIn(int seconds) {
}
});
}
}
public void logout(){
chatService.logout(new QBEntityCallback<Void>() {
#Override
public void onSuccess(Void result, Bundle bundle) {
}
#Override
public void onError(QBResponseException list) {
}
});
}
/* public void subscribeToPushNotifications(String registrationID) {
QBSubscription subscription = new QBSubscription(QBNotificationChannel.GCM);
subscription.setEnvironment(QBEnvironment.DEVELOPMENT);
//
String deviceId;
final TelephonyManager mTelephony = (TelephonyManager) getSystemService(
Context.TELEPHONY_SERVICE);
if (mTelephony.getDeviceId() != null) {
deviceId = mTelephony.getDeviceId(); /*//*** use for mobiles
} else {
deviceId = Settings.Secure.getString(getContentResolver(),
Settings.Secure.ANDROID_ID); /*//*** use for tablets
}
subscription.setDeviceUdid(deviceId);
//
subscription.setRegistrationID(registrationID);
//
QBPushNotifications.createSubscription(subscription, new QBEntityCallback<ArrayList<QBSubscription>>() {
#Override
public void onSuccess(ArrayList<QBSubscription> subscriptions, Bundle args) {
Log.d("push_send","sucess");
}
#Override
public void onError(QBResponseException error) {
Log.d("push_send","sucess");
}
});
}*/
private SharedPreferences getGCMPreferences(Context context) {
// This sample app persists the registration ID in shared preferences,
// but
// how you store the regID in your app is up to you.
Log.e("getGCMPreferences", "package= " + context.getPackageName());
return getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE);
}
private void storeDeviceId(Context context, String deviceId) {
final SharedPreferences prefs = getGCMPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(PROPERTY_DEVICE_ID, deviceId);
editor.commit();
}
}

Flickr Sign out in Android programmatically

I am getting some issue when image is uploaded to flickr,oath token as well as user credentials get stored in the web browser cache.As a result am not being able to sign out from it.So when I go to flickr to upload my image again,it automatically uploads it rather than opening the login page.Now when I clear all the default browser cookies,then it ask for the login page.Is there any other way to sign out it automatically when I am redirected back to my application.Any kind of support will be appreciated.
Thanks in advance...
try this ,here....,FlickerHelper.java
public final class FlickrHelper {
private static FlickrHelper instance = null;
private static final String API_KEY = ""; //$NON-NLS-1$
public static final String API_SEC = ""; //$NON-NLS-1$
private FlickrHelper() {
}
public static FlickrHelper getInstance() {
if (instance == null) {
instance = new FlickrHelper();
}
return instance;
}
public Flickr getFlickr() {
try {
Flickr f = new Flickr(API_KEY, API_SEC, new REST());
return f;
} catch (ParserConfigurationException e) {
return null;
}
}
public Flickr getFlickrAuthed(String token, String secret) {
Flickr f = getFlickr();
RequestContext requestContext = RequestContext.getRequestContext();
OAuth auth = new OAuth();
auth.setToken(new OAuthToken(token, secret));
requestContext.setOAuth(auth);
return f;
}
public InterestingnessInterface getInterestingInterface() {
Flickr f = getFlickr();
if (f != null) {
return f.getInterestingnessInterface();
} else {
return null;
}
}
public PhotosInterface getPhotosInterface() {
Flickr f = getFlickr();
if (f != null) {
return f.getPhotosInterface();
} else {
return null;
}
}
}
FlickerjActivity.java
public class FlickrjActivity extends Activity {
public static final String CALLBACK_SCHEME = "flickrj-android-sample-oauth"; //$NON-NLS-1$
public static final String PREFS_NAME = "flickrj-android-sample-pref"; //$NON-NLS-1$
public static final String KEY_OAUTH_TOKEN = "flickrj-android-oauthToken"; //$NON-NLS-1$
public static final String KEY_TOKEN_SECRET = "flickrj-android-tokenSecret"; //$NON-NLS-1$
public static final String KEY_USER_NAME = "flickrj-android-userName"; //$NON-NLS-1$
public static final String KEY_USER_ID = "flickrj-android-userId"; //$NON-NLS-1$
String path;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getIntent().getExtras() != null) {
if (getIntent().getExtras().containsKey("flickImagePath")) {
path = getIntent().getStringExtra("flickImagePath");
}
}
new Thread() {
public void run() {
h.post(init);
};
}.start();
}
Handler h = new Handler();
Runnable init = new Runnable() {
#Override
public void run() {
OAuth oauth = getOAuthToken();
if (oauth == null || oauth.getUser() == null) {
OAuthTask task = new OAuthTask(getContext());
task.execute();
} else {
load(oauth);
}
}
};
private void load(OAuth oauth) {
if (oauth != null) {
UploadPhotoTask taskUpload = new UploadPhotoTask(this, new File(
path));
taskUpload.setOnUploadDone(new UploadPhotoTask.onUploadDone() {
#Override
public void onComplete() {
finish();
}
});
taskUpload.execute(oauth);
}
}
#Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
}
#Override
public void onResume() {
super.onResume();
Intent intent = getIntent();
String scheme = intent.getScheme();
OAuth savedToken = getOAuthToken();
if (CALLBACK_SCHEME.equals(scheme)
&& (savedToken == null || savedToken.getUser() == null)) {
Uri uri = intent.getData();
String query = uri.getQuery();
String[] data = query.split("&"); //$NON-NLS-1$
if (data != null && data.length == 2) {
String oauthToken = data[0].substring(data[0].indexOf("=") + 1); //$NON-NLS-1$
String oauthVerifier = data[1]
.substring(data[1].indexOf("=") + 1); //$NON-NLS-1$
OAuth oauth = getOAuthToken();
if (oauth != null && oauth.getToken() != null
&& oauth.getToken().getOauthTokenSecret() != null) {
GetOAuthTokenTask task = new GetOAuthTokenTask(this);
task.execute(oauthToken, oauth.getToken()
.getOauthTokenSecret(), oauthVerifier);
}
}
}
}
public void onOAuthDone(OAuth result) {
if (result == null) {
Toast.makeText(this, "Authorization failed", //$NON-NLS-1$
Toast.LENGTH_LONG).show();
} else {
User user = result.getUser();
OAuthToken token = result.getToken();
if (user == null || user.getId() == null || token == null
|| token.getOauthToken() == null
|| token.getOauthTokenSecret() == null) {
Toast.makeText(this, "Authorization failed", //$NON-NLS-1$
Toast.LENGTH_LONG).show();
return;
}
String message = String
.format(Locale.US,
"Authorization Succeed: user=%s, userId=%s, oauthToken=%s, tokenSecret=%s", //$NON-NLS-1$
user.getUsername(), user.getId(),
token.getOauthToken(), token.getOauthTokenSecret());
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
saveOAuthToken(user.getUsername(), user.getId(),
token.getOauthToken(), token.getOauthTokenSecret());
load(result);
}
}
public OAuth getOAuthToken() {
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
String oauthTokenString = settings.getString(KEY_OAUTH_TOKEN, null);
String tokenSecret = settings.getString(KEY_TOKEN_SECRET, null);
if (oauthTokenString == null && tokenSecret == null) {
// logger.warn("No oauth token retrieved"); //$NON-NLS-1$
return null;
}
OAuth oauth = new OAuth();
String userName = settings.getString(KEY_USER_NAME, null);
String userId = settings.getString(KEY_USER_ID, null);
if (userId != null) {
User user = new User();
user.setUsername(userName);
user.setId(userId);
oauth.setUser(user);
}
OAuthToken oauthToken = new OAuthToken();
oauth.setToken(oauthToken);
oauthToken.setOauthToken(oauthTokenString);
oauthToken.setOauthTokenSecret(tokenSecret);
return oauth;
}
public void saveOAuthToken(String userName, String userId, String token,
String tokenSecret) {
SharedPreferences sp = getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
Editor editor = sp.edit();
editor.putString(KEY_OAUTH_TOKEN, token);
editor.putString(KEY_TOKEN_SECRET, tokenSecret);
editor.putString(KEY_USER_NAME, userName);
editor.putString(KEY_USER_ID, userId);
editor.commit();
}
private Context getContext() {
return this;
}
}
GetAouthToken.java
public class GetOAuthTokenTask extends AsyncTask<String, Integer, OAuth> {
private FlickrjActivity activity;
public GetOAuthTokenTask(FlickrjActivity context) {
this.activity = context;
}
#Override
protected OAuth doInBackground(String... params) {
String oauthToken = params[0];
String oauthTokenSecret = params[1];
String verifier = params[2];
Flickr f = FlickrHelper.getInstance().getFlickr();
OAuthInterface oauthApi = f.getOAuthInterface();
try {
return oauthApi.getAccessToken(oauthToken, oauthTokenSecret,
verifier);
} catch (Exception e) {
return null;
}
}
#Override
protected void onPostExecute(OAuth result) {
if (activity != null) {
activity.onOAuthDone(result);
}
}
}
Oauthtask.java
public class OAuthTask extends AsyncTask<Void, Integer, String> {
private static final Uri OAUTH_CALLBACK_URI = Uri
.parse(FlickrjActivity.CALLBACK_SCHEME + "://oauth"); //$NON-NLS-1$
private Context mContext;
private ProgressDialog mProgressDialog;
public OAuthTask(Context context) {
super();
this.mContext = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = ProgressDialog.show(mContext,
"", "Generating the authorization request..."); //$NON-NLS-1$ //$NON-NLS-2$
mProgressDialog.setCanceledOnTouchOutside(true);
mProgressDialog.setCancelable(true);
mProgressDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dlg) {
OAuthTask.this.cancel(true);
}
});
}
#Override
protected String doInBackground(Void... params) {
try {
Flickr f = FlickrHelper.getInstance().getFlickr();
OAuthToken oauthToken = f.getOAuthInterface().getRequestToken(
OAUTH_CALLBACK_URI.toString());
saveTokenSecrent(oauthToken.getOauthTokenSecret());
URL oauthUrl = f.getOAuthInterface().buildAuthenticationUrl(
Permission.WRITE, oauthToken);
return oauthUrl.toString();
} catch (Exception e) {
return "error:" + e.getMessage(); //$NON-NLS-1$
}
}
private void saveTokenSecrent(String tokenSecret) {
FlickrjActivity act = (FlickrjActivity) mContext;
act.saveOAuthToken(null, null, null, tokenSecret);
}
#Override
protected void onPostExecute(String result) {
if (mProgressDialog != null) {
mProgressDialog.dismiss();
}
if (result != null && !result.startsWith("error")) { //$NON-NLS-1$
mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(result)));
} else {
Toast.makeText(mContext, result, Toast.LENGTH_LONG).show();
}
}
}
uploadphototask.java
public class UploadPhotoTask extends AsyncTask<OAuth, Void, String> {
private final FlickrjActivity flickrjAndroidSampleActivity;
private File file;
public UploadPhotoTask(FlickrjActivity flickrjAndroidSampleActivity,
File file) {
this.flickrjAndroidSampleActivity = flickrjAndroidSampleActivity;
this.file = file;
}
private ProgressDialog mProgressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = ProgressDialog.show(flickrjAndroidSampleActivity,
"", "Uploading..."); //$NON-NLS-1$ //$NON-NLS-2$
mProgressDialog.setCanceledOnTouchOutside(true);
mProgressDialog.setCancelable(true);
mProgressDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dlg) {
UploadPhotoTask.this.cancel(true);
}
});
}
#Override
protected String doInBackground(OAuth... params) {
OAuth oauth = params[0];
OAuthToken token = oauth.getToken();
try {
Flickr f = FlickrHelper.getInstance().getFlickrAuthed(
token.getOauthToken(), token.getOauthTokenSecret());
UploadMetaData uploadMetaData = new UploadMetaData();
uploadMetaData.setTitle("" + file.getName());
return f.getUploader().upload(file.getName(),
new FileInputStream(file), uploadMetaData);
} catch (Exception e) {
Log.e("boom!!", "" + e.toString());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String response) {
if (mProgressDialog != null) {
mProgressDialog.dismiss();
}
if (response != null) {
Log.e("", "" + response);
} else {
}
if (monUploadDone != null) {
monUploadDone.onComplete();
}
Toast.makeText(flickrjAndroidSampleActivity.getApplicationContext(),
response, Toast.LENGTH_SHORT).show();
}
onUploadDone monUploadDone;
public void setOnUploadDone(onUploadDone monUploadDone) {
this.monUploadDone = monUploadDone;
}
public interface onUploadDone {
void onComplete();
}
}
mainactivty.java
public class MainActivity extends Activity {
File fileUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnFlickr = (Button) findViewById(R.id.btnFlickr);
btnFlickr.setOnClickListener(mFlickrClickListener);
Button btnPick = (Button) findViewById(R.id.btnPick);
btnPick.setOnClickListener(mPickClickListener);
}
View.OnClickListener mPickClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivityForResult(intent, 102);
}
};
View.OnClickListener mFlickrClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if (fileUri == null) {
Toast.makeText(getApplicationContext(), "Please pick photo",
Toast.LENGTH_SHORT).show();
return;
}
Intent intent = new Intent(getApplicationContext(),
FlickrjActivity.class);
intent.putExtra("flickImagePath", fileUri.getAbsolutePath());
startActivity(intent);
}
};
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 102) {
if (resultCode == Activity.RESULT_OK) {
Uri tmp_fileUri = data.getData();
((ImageView) findViewById(R.id.imageView1))
.setImageURI(tmp_fileUri);
String selectedImagePath = getPath(tmp_fileUri);
fileUri = new File(selectedImagePath);
Debug.e("", "fileUri : " + fileUri.getAbsolutePath());
}
}
};
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
usercard.java
public class UserCard {
public String name;
public String url;
public int upVotes;
public int downVotes;
}
debug.java
public class Debug {
private static final boolean DEBUG = true;
public static void e(String tag, String msg) {
if (DEBUG) {
Log.e(tag, msg);
}
}public static void i(String tag, String msg) {
if (DEBUG) {
Log.i(tag, msg);
}
}
public static void w(String tag, String msg) {
if (DEBUG) {
Log.w(tag, msg);
}
}
public static void d(String tag, String msg) {
if (DEBUG) {
Log.d(tag, msg);
}
}
}

Android Intent after onpostexecute fails to start

I have a registration system. The registration is working fine. My main problem is: I would like to start MainActivity.java after logging in. After sending the login data to the Server, the Server checks in Database if it matches and sends out an int (0 for unmatched) and (1 for success). This works great as well. But if i want to start the Intent after onPostExecute Method it gives out an Error:
FATAL EXCEPTION: main
java.lang.NullPointerException
at android.app.Activity.startActivityForResult
...
This is my StartPage which exectues my AsyncTask Class. And receives success or unmatched in the Method getLoginMessage().
public class LoginPage extends Activity {
String userName;
String password;
String sendProtocolToServer;
static String matched = null;
static String unmatched;
static Context myCtx;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loginpage);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Button login = (Button) findViewById(R.id.loginBtn);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
handleLogin();
}
});
Button register = (Button) findViewById(R.id.registerBtn);
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent openMainActivityRegister = new Intent(
"com.example.fotosharing.REGISTERPAGE");
startActivity(openMainActivityRegister);
}
});
}
private void handleLogin() {
EditText editTextBox = (EditText) findViewById(R.id.EditTextUser);
EditText passwordTextBox = (EditText) findViewById(R.id.EditTextPassword);
userName = editTextBox.getText().toString();
password = passwordTextBox.getText().toString();
if (!userName.equals("") && !password.equals("")) {
sendProtocolToServer = "login" + "#" + userName + "#" + password;
ConnectToServer cts = new ConnectToServer(sendProtocolToServer);
cts.execute();
} else {
Toast.makeText(this, "Fill in Username and Password to login",
Toast.LENGTH_LONG).show();
}
}
public void getLoginMessage(String receivedMessage) {
if (receivedMessage.equals("success")) {
Intent openMainActivity = new Intent(
"com.example.fotosharing.TIMELINEACTIVITY");
openMainActivity.clone();
startActivity(openMainActivity);
}
if (receivedMessage.equals("unmatched")) {
Toast.makeText(this, "Password or username incorrect.", Toast.LENGTH_LONG).show();
}
}
}
This is my Async-Task class which receives Data from my Java-Server, and checks if it was an successful or an unmatched login. In onPostExecute im calling a Method in the LoginPage.class, which handles the Intent (here comes the Error).
public class ConnectToServer extends AsyncTask<Void, Void, String> {
public Context myCtx;
static Socket socket;
String sendStringToServer;
int protocolId = 0;
private static DataOutputStream DOS;
private static DataInputStream DIS;
StringBuffer line;
int j = 1;
String value;
static String res = null;
public ConnectToServer(String sendStringToServer) {
this.sendStringToServer = sendStringToServer;
}
public ConnectToServer(int i) {
this.protocolId = i;
}
public ConnectToServer() {
}
public ConnectToServer(Context ctx) {
this.myCtx = ctx;
}
protected String doInBackground(Void... arg0) {
try {
socket = new Socket("192.168.1.106", 25578);
DOS = new DataOutputStream(socket.getOutputStream());
if (protocolId == 1) {
DOS.writeUTF("pictureload");
protocolId = 0;
} else {
DOS.writeUTF(sendStringToServer);
}
res = receive();
// DOS.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("RES: " + res);
return res;
}
public String receive() {
String receiveResult = null;
if (socket.isConnected()) {
try {
BufferedReader input = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
DIS = new DataInputStream(socket.getInputStream());
int msg_received = DIS.readInt();
System.out.println("SERVER: " + msg_received);
if (msg_received == 1) {
receiveResult = "success";
System.out.println("IF (success): " + receiveResult);
}
if (msg_received == 0) {
receiveResult = "unmatched";
System.out.println("ELSE IF (unmatched): "
+ receiveResult);
}
} catch (IOException e) {
e.printStackTrace();
}
}
// ***** return your accumulated StringBuffer as string, not current
// line.toString();
return receiveResult;
}
protected void onPostExecute(String result1) {
if (result1 != null) {
if (result1.equals("success") || result1.equals("unmatched")) {
sendToLoginPage(result1);
}
}
}
private void sendToLoginPage(String result1) {
System.out.println("sendtologi " + result1);
LoginPage lp = new LoginPage();
lp.getLoginMessage(result1);
}
}
This is the class I want to start when it was a successful login.
What am I doing wrong?
public class MainActivity extends SherlockFragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
ActionBar actionbar = getSupportActionBar();
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionbar.setBackgroundDrawable(new ColorDrawable(Color.BLACK));
actionbar.setStackedBackgroundDrawable(new ColorDrawable(Color.parseColor("#91d100")));
ActionBar.Tab Frag1Tab = actionbar.newTab().setText("Home");
ActionBar.Tab Frag2Tab = actionbar.newTab().setText("Share Photo");
Fragment Fragment1 = new TimelineActivity();
Fragment Fragment2 = new CameraActivity();
Frag1Tab.setTabListener(new MyTabsListener(Fragment1));
Frag2Tab.setTabListener(new MyTabsListener(Fragment2));
actionbar.addTab(Frag1Tab);
actionbar.addTab(Frag2Tab);
}
}
You cannot just create instance of your activity with new keyword, like this:
private void sendToLoginPage(String result1) {
System.out.println("sendtologi " + result1);
LoginPage lp = new LoginPage();
lp.getLoginMessage(result1);
}
This is wrong and it is probably why you are getting error. Code you posted is quite complex, so i am not sure if there are any other problems.
This is how it should be done:
So... Since you probably have ConnectToServer asyncTask in separate file, you need pass events or data to your LoginPage activity. For this purpose, you should use event listener, like this:
First, create interface that will represent communication between your ConnectToServer and your LoginPage.
public interface LoginResultListener {
public void getLoginMessage(String receivedMessage);
}
Now, make your LoginPage activity implement this interface:
public class LoginPage extends Activity implements LoginResultListener {
...
}
Now, update your ConnectToServer asyncTask, so that it uses LoginResultListener to communicate login result to your activity, like this:
public class ConnectToServer extends AsyncTask<Void, Void, String> {
private LoginResultListener listener;
...
public void setListener(LoginResultListener listener) {
this.listener = listener;
}
...
private void sendToLoginPage(String result1) {
System.out.println("sendtologi " + result1);
//THIS IS WHERE YOU DID WRONG
listener.getLoginMessage(result1);
}
...
}
Now finally, when you create new ConnectToServer async task from your activity, you need to set listener that will handle events when user logs in. Since you implemented this interface in your activity, you will send your activity object as listener parameter, see below:
ConnectToServer cts = new ConnectToServer(sendProtocolToServer);
// THIS IS IMPORTANT PART - 'this' refers to your LoginPage activity, that implements LoginResultListener interface
cts.setListener(this);
cts.execute();

Android - Tumblr Access Token via OAuth

I am trying to allow Android users to post to their Tumblr blogs using my app. I am able to launch Tumblr, enter my username and password, and log in, however the problem is the Access Token I receive appears to be invalid (I get a 401 - Unauthorized when I use it with any of Tumblr's API calls).
Below is the code I am using. I am able to authenticate with Twitter, but Tumblr is giving me difficulties. If anyone has any ideas, suggestions, or improvements, they would be much appreciated. Thanks!
public final class TumblrWebView extends Activity {
private final String TAG = getClass().getSimpleName();
OAuth10Service service;
public final static String PARAMETER_CONSUMER_KEY = "CONSUMER_KEY";
public final static String PARAMETER_CONSUMER_SECRET = "CONSUMER_SECRET";
public final static String PARAMETER_CALLBACK_URL = "CALLBACK_URL";
private String consumerKey;
private String consumerSecret;
private String callbackUrl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.web_view);
/*
* Get params
*/
Intent intent = getIntent();
consumerKey = intent.getStringExtra(PARAMETER_CONSUMER_KEY);
consumerSecret = intent.getStringExtra(PARAMETER_CONSUMER_SECRET);
callbackUrl = intent.getStringExtra(PARAMETER_CALLBACK_URL);
service = OAuthService.newInstance(new TumblrApi(), consumerKey, consumerSecret, new OAuth10ServiceCallback() {
#Override
public void onOAuthAccessTokenReceived(OAuth10Token token) {
complete(token);
Log.i(TAG, "Access token recieved");
// System.out.println("token recieved " + token.getAccessToken());
// System.out.println("token recieved " + token.getUserSecret());
}
#Override
public void onOAuthRequestTokenReceived() {
loadWebView();
Log.i(TAG, "Request token recieved");
}
#Override
public void onOAuthRequestTokenFailed(HootResult result) {
Log.e(TAG, "Token request failed " + result.getException());
}
#Override
public void onOAuthAccessTokenFailed(HootResult result) {
Log.e(TAG, "Token access failed " + result);
}
});
service.start();
}
#SuppressLint("SetJavaScriptEnabled")
private void loadWebView() {
final WebView webview = (WebView) findViewById(R.id.web_view);
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// Checking for our successful callback
if(url.startsWith(callbackUrl)) {
webview.setVisibility(View.GONE);
Log.d(TAG, "token url " + url + " " + service.getOAuthAccessToken(url));
} else {
Log.d(TAG, "token url");
}
return super.shouldOverrideUrlLoading(view, url);
}
});
webview.loadUrl(service.getAuthorizeUrl());
}
private void complete(OAuth10Token token) {
Intent resultIntent = new Intent();
resultIntent.putExtra(TumblrUtils.PREF_TUMBLR_ACCESS, token.getAccessToken());
resultIntent.putExtra(TumblrUtils.PREF_TUMBLR_SECRET, token.getUserSecret());
setResult(RESULT_OK, resultIntent);
finish();
}
}
EDIT: A helper class
public class TumblrUtils {
// Consumer Key and Secret
private static final String TUMBLR_CONSUMER_KEY = "{ ENTER TUMBLR CONSUMER KEY }";
private static final String TUMBLR_CONSUMER_SECRET = "{ ENTER TUMBLR CONSUMER SECRET }";
// Callback URL
private static final String TUMBLR_CALLBACK_URL = "http://example.com";
// Request Code
public static final int TUMBLR_REQUEST_CODE = 87; /* 87 - TR */
// Preference Constants
public static final String PREF_TUMBLR_USER = "tumblr_user";
public static final String PREF_TUMBLR_ACCESS = "tumblr_access_token";
public static final String PREF_TUMBLR_SECRET = "tumblr_secret_token";
public static final String TUMBLR_REQUEST_URL = "http://www.tumblr.com/oauth/request_token";
public static final String TUMBLR_ACCESS_URL = "http://www.tumblr.com/oauth/access_token";
public static final String TUMBLR_AUTHORIZE_URL = "http://www.tumblr.com/oauth/authorize";
private static OAuthConsumer tumblrConsumer;
private static String tumblrHost;
private static String tumblrToken;
private static String tumblrTokenSecret;
private static String getConsumerKey() {
return TUMBLR_CONSUMER_KEY;
}
private static String getConsumerSecret() {
return TUMBLR_CONSUMER_SECRET;
}
private static String getCallbackUrl() {
return TUMBLR_CALLBACK_URL;
}
public static String getRequestUrl() {
return TUMBLR_REQUEST_URL;
}
public static String getAccessUrl() {
return TUMBLR_ACCESS_URL;
}
public static String getAuthorizeUrl() {
return TUMBLR_AUTHORIZE_URL;
}
public static OAuthConsumer getTumblrConsumer() {
return tumblrConsumer;
}
public static String getTumblrHost() {
return tumblrHost;
}
public static void setTumblrHost(String host) {
TumblrUtils.tumblrHost = host;
}
public static String getTumblrToken() {
return tumblrToken;
}
public static String getTumblrTokenSecret() {
return tumblrTokenSecret;
}
public static Intent getTumblrIntent(Context activity) {
Intent TumblrIntent = new Intent(activity, TumblrWebView.class);
TumblrIntent.putExtra("CONSUMER_KEY", getConsumerKey());
TumblrIntent.putExtra("CONSUMER_SECRET", getConsumerSecret());
TumblrIntent.putExtra("CALLBACK", getCallbackUrl());
return TumblrIntent;
}
public static OAuthConsumer saveTumblrResult(SharedPreferences settings,
String access_token, String secret_token) {
Editor editor = settings.edit();
editor.putString(PREF_TUMBLR_ACCESS, access_token);
editor.putString(PREF_TUMBLR_SECRET, secret_token);
editor.commit();
return saveTumblrResult(access_token, secret_token);
}
public static OAuthConsumer saveTumblrResult(String stringExtra1, String stringExtra2) {
tumblrToken = (stringExtra1);
tumblrTokenSecret = (stringExtra2);
tumblrConsumer = new CommonsHttpOAuthConsumer(
getConsumerKey(), getConsumerSecret());
tumblrConsumer.setTokenWithSecret(
tumblrToken, tumblrTokenSecret);
return tumblrConsumer;
}
}
EDIT: TumblrWebActivity - startActivityForResult
startActivityForResult(
TumblrUtils.getTumblrIntent(Settings_ShareSettings.this),
EDIT: TumblrWebActivity - onActivityResult
TumblrUtils.TUMBLR_REQUEST_CODE);
TumblrUtils.saveTumblrResult(mPrefs,
data.getStringExtra(TumblrUtils.PREF_TUMBLR_ACCESS),
data.getStringExtra(TumblrUtils.PREF_TUMBLR_SECRET));
new TumblrTask("https://api.tumblr.com/v2/user/info").execute();
EDIT: GetUserInfo - AsyncTask
private final class TumblrTask extends AsyncTask<String, Void, String> {
String url;
public TumblrTask(String url) {
this.url = url;
}
#Override
protected String doInBackground(String... params) {
String result = "";
HttpClient httpclient = GlobalContext.getHttpClient();
HttpRequestBase request = new HttpGet(url);
try {
TumblrUtils.getTumblrConsumer().sign(request);
} catch (OAuthMessageSignerException e) {
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
e.printStackTrace();
} catch (OAuthCommunicationException e) {
e.printStackTrace();
}
try {
HttpResponse response = httpclient.execute(request, GlobalContext.getLocalContext());
HttpEntity entity = response.getEntity();
InputStream instream = entity.getContent();
result = GlobalContext.convertStreamToString(instream);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String result) {
try {
JSONObject jObject = new JSONObject(result.trim());
System.out.println(jObject);
if(jObject.has("response")) {
JSONObject jResponse = jObject.getJSONObject("response");
System.out.println(jResponse);
if(jResponse.has("user")) {
JSONObject jUser = jResponse.getJSONObject("user");
System.out.println(jUser);
tumblr_name = jUser.getString("name");
TumblrUtils.saveTumblrResult(mPrefs, tumblr_name);
tvTumblr.setText(tumblr_name);
ibTumblr.setSelected(true);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
EDIT: NOTE: Requires AndrOAuth
As it turns out, the Access Token and Access Token Secret returned were valid. The problem was that I was not signing the request with the Access Token Secret.

warning: window already focused ignoring focus gain of com.android.internal.view. iinputmethod client $stub$proxy 4148db78

i have search and not found the answer. I want to call startActvity(newintent), but the page not change.
This my code:
public class MainActivity extends Activity {
private TextView IdPeserta, Password;
//private ArrayList<NameValuePair> authentication;
#SuppressWarnings("unused")
//private String temp, _nama = "";
//private readURL rL;
public static String username = "";
public static String password = "";
public static String status = "FALSE";
public void setPassword(String password){
MainActivity.password = password;
}
public void setUsername(String username){
MainActivity.username = username;
}
public void setStatus(String status){
MainActivity.status = status;
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
IdPeserta = (TextView) findViewById(R.id.idPeserta);
Password = (TextView) findViewById(R.id.password);
}
public void Login(View view){
setUsername(IdPeserta.getText().toString());
setPassword(Password.getText().toString());
if((IdPeserta.getText().length() > 0 && Password.getText().length() > 0)){
RestTask task = new RestTask();
task.applicationContext = MainActivity.this;
task.execute();
}else{
Toast.makeText(this,"fill Id Peserta and Password 1", 0).show();
}
}
public void authenticate(){
if(status.equals("TRUE")){
Intent i = new Intent(MainActivity.this, Home.class);
//PendingIntent pending = PendingIntent.getActivity(this, 0, i, 0);
startActivity(i);
finish();
}else if(status.equals("FALSE")){
Log.d("gagal", "coba lagi");
}
}
public static String getService() {
String responseString = null;
String baseurlString = "http://10.0.2.2:8080/UjianServices/authentikasi.php";
RestClient client = new RestClient(baseurlString);
client.AddParam("id_peserta", MainActivity.username);
client.AddParam("password", MainActivity.password);
try {
client.Execute(RequestMethod.POST);
} catch (Exception e) {
Log.d("error", e.getMessage());
//e.printStackTrace();
}
responseString = client.getResponse();
return responseString;
}
public class RestTask extends AsyncTask<Object, Object, Object>{
private ProgressDialog dialog;
protected Context applicationContext;
#Override
protected void onPreExecute() {
this.dialog = ProgressDialog.show(applicationContext, "Calling", "Time Service...", true);
}
#Override
protected void onPostExecute(Object result) {
this.dialog.cancel();
String status = result.toString();
setStatus(status);
authenticate();
}
#Override
protected Object doInBackground(Object... arg0) {
return MainActivity.getService();
}
}
}
When i did not using the RestTask it can change the page. How i change my activity?
because applicationContext is null you have not initialize applicationContext before using it for showing ProgressDialog from onPreExecute .
you need to initialize applicationContext before using for showing ProgressDialog or just use MainActivity.this as :
#Override
protected void onPreExecute() {
applicationContext=MainActivity.this; //<<< initialize context here
this.dialog = ProgressDialog.show(applicationContext,
"Calling", "Time Service...", true);
}

Categories

Resources