Listing Google Drive File on Android using Files.List() API - android

Currently i need to make an application that can list all of Google Drive file.
i already did the account choosing and oauth process, an already get the token. but when i try to use API call to list all my file on Google Drive (By using drive.files.list) i didn't get any result, the arraylist of files which is supposed to hold all the file is still empty. i also got error :
java.net.unknownHostException www.googleapis.com cannot be resolved
this is my code :
SharedPreferences settings = getSharedPreferences(PREF, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("accountName", got.name);
editor.commit();
account=got;
amf=accMgr.getAuthToken(account, authTokenType, true,
new AccountManagerCallback<Bundle>(){
public void run(AccountManagerFuture<Bundle> arg0) {
try {
Bundle result;
Intent i;
String token;
Drive a;
result = arg0.getResult();
if (result.containsKey(accMgr.KEY_INTENT)) {
i = (Intent)result.get(accMgr.KEY_INTENT);
if (i.toString().contains("GrantCredentialsPermissionActivity")) {
// Will have to wait for the user to accept
// the request therefore this will have to
// run in a foreground application
cbt.startActivity(i);
} else {
cbt.startActivity(i);
}
}
else if (result.containsKey(accMgr.KEY_AUTHTOKEN)) {
accessProtectedResource.setAccessToken(result
.getString(accMgr.KEY_AUTHTOKEN));
buildService(result
.getString(accMgr.KEY_AUTHTOKEN),API_KEY);
/*else {
token = (String)result.get(AccountManager.KEY_AUTHTOKEN);*/
/*
* work with token
*/
// Remember to invalidate the token if the web service rejects it
// if(response.isTokenInvalid()){
// accMgr.invalidateAuthToken(authTokenType, token);
// }
}
} catch (OperationCanceledException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AuthenticatorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, handler);
}
private void buildService(final String authToken, final String ApiKey) {
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
Drive.Builder b = new Drive.Builder(httpTransport, jsonFactory, null);
b.setJsonHttpRequestInitializer(new JsonHttpRequestInitializer() {
#Override
public void initialize(JsonHttpRequest request) throws IOException {
DriveRequest driveRequest = (DriveRequest) request;
driveRequest.setPrettyPrint(true);
driveRequest.setKey(ApiKey);
driveRequest.setOauthToken(authToken);
}
});
System.out.println(authToken);
service= b.build();
List<File> a=new ArrayList<File>();
try {
a = retrieveDriveFile(service);
System.out.println(a.size());
File c=a.get(0);
TextView ad=(TextView) findViewById(R.id.test);
ad.setText(c.getOriginalFilename());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public List<File> retrieveDriveFile(Drive service) throws IOException{
List<File> result = new ArrayList<File>();
Files.List request = service.files().list();
do {
try {
FileList files = request.execute();
result.addAll(files.getItems());
request.setPageToken(files.getNextPageToken());
} catch (IOException e) {
System.out.println("An error ssoccurred: " + e);
request.setPageToken(null);
}
} while (request.getPageToken() != null &&
request.getPageToken().length() > 0);
return result;
}

This would typically happen if you don't have a working internet connection on your device.
Also don't forget to add the following permission:
<uses-permission android:name="android.permission.INTERNET" />
This could happen also if you are behind a proxy. If that's the case please have a look at this question.

If you want to get all the file from Goolge Drive. Assume that you have already done the Account Choosing process and creating Drive (Drive mService) etc.
Now Under Button Click Event call this function
ButtonClickEvent
{
GetDriveData();
}
// FUNCTION TO RETRIEVE GOOGLE DRIVE DATA
private void GetDriveData()
{
private List<File> mResultList;
Thread t = new Thread(new Runnable()
{
#Override
public void run()
{
mResultList = new ArrayList<File>();
com.google.api.services.drive.Drive.Files f1 = mService.files();
com.google.api.services.drive.Drive.Files.List request = null;
do
{
try
{
request = f1.list();
request.setQ("trashed=false");
com.google.api.services.drive.model.FileList fileList = request.execute();
mResultList.addAll(fileList.getItems());
}
catch (UserRecoverableAuthIOException e)
{
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
}
catch (IOException e)
{
e.printStackTrace();
if (request != null)
{
request.setPageToken(null);
}
}
} while (request.getPageToken() !=null && request.getPageToken().length() > 0);
populateListView();//Calling to Populate Data to the List
}
});
t.start();
}
//Populating Retrieved data to List
private void populateListView()
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
mFileArray = new String[mResultList.size()];
int i = 0;
for(File tmp : mResultList)
{
//System.out.println("FILE DATA "+tmp.getId()+"."+tmp.getFileSize()+".."+tmp.getFileExtension()+",,"+tmp.getMimeType()+"/"+tmp.getTitle());
mFileArray[i] = tmp.getTitle();
i++;
}
mAdapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_1, mFileArray);
mListView.setAdapter(mAdapter);
button2.setText("yes");
}
});
}

Related

java.lang.NullPointerException: No authentication header information #467

private void setOauthParameter() {
GoogleOAuthParameters oauthParam = new GoogleOAuthParameters();
oauthParam.setOAuthConsumerKey(ClientId);
oauthParam.setOAuthConsumerSecret(ClientSecrate);
oauthParam.setOAuthType(OAuthParameters.OAuthType.TWO_LEGGED_OAUTH);
// Init the service and set the auth
service = new ContactsService("chat.com.contactssharing");
try {
service.setOAuthCredentials(oauthParam, new OAuthHmacSha1Signer());
service.getRequestFactory().setHeader("User-Agent", "chat.com.contactssharing");
} catch (OAuthException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void queryEntries() throws IOException, ServiceException {
Query myQuery = new Query(feedUrl);
myQuery.setMaxResults(50);
myQuery.setStartIndex(1);
myQuery.setStringCustomParameter("showdeleted", "false");
myQuery.setStringCustomParameter("requirealldeleted", "false");
myQuery.setStringCustomParameter("sortorder", "ascending");
try {
// Execution of this line i'm getting an exception
ContactFeed resultFeed = (ContactFeed) this.service.query(myQuery, ContactFeed.class);
Log.d(TAG, resultFeed.toString());
for (ContactEntry entry : resultFeed.getEntries()) {
printContact(entry);
}
System.err.println("Total: " + resultFeed.getEntries().size() + " entries found");
} catch (Exception ex) {
System.err.println("Not all placehorders of deleted entries are available");
}
}
My objective to get the friends contacts list from gmail and i have check no's of post for this Exception but no one is commented by correct solution.It's become blocker for me so please help me to out this problem and guide what is doing wrong at above code.

How to generate token with bank account in stripe?

I integrated stripe in my android project. Now, I am generating token with card in stripe. That is working fine. But, I want to generate token with Bank Account. I searched in StackOverflow referred some of links. But, it doesn't worked for me. Is there is any way to generate stripe token with bank account in android?
The following code I used. But, it not worked.
Stripe.apiKey = "sk_test_...";
Map<String, Object> tokenParams = new HashMap<String, Object>();
Map<String, Object> bank_accountParams = new HashMap<String, Object>();
bank_accountParams.put("country", "US");
bank_accountParams.put("currency", "usd");
bank_accountParams.put("account_holder_name", "Jane Austen");
bank_accountParams.put("account_holder_type", "individual");
bank_accountParams.put("routing_number", "11000000");
bank_accountParams.put("account_number", "000123456789");
tokenParams.put("bank_account", bank_accountParams);
try {
Token s = Token.create(tokenParams);
Log.d("Token",s.getId());
tokens = s.getId();
} catch (AuthenticationException e) {
showAlertMessage("",e.getMessage());
} catch (CardException e) {
showAlertMessage("",e.getMessage());
} catch (APIException e) {
showAlertMessage("",e.getMessage());
} catch (InvalidRequestException e) {
showAlertMessage("", e.getMessage());
} catch (APIConnectionException e) {
showAlertMessage("",e.getMessage());
}
According to the new docs you need to add following line to gradle build:
compile 'com.stripe:stripe-android:4.0.1'
check for the latest version at this link
Then use the following code snippet:
Stripe stripe = new Stripe(this);
stripe.setDefaultPublishableKey("your_publishable_key");
BankAccount bankAccount = new BankAccount("accountNumber","countryCode","currency","routingNumber");
stripe.createBankAccountToken(bankAccount, new TokenCallback() {
#Override
public void onError(Exception error) {
Log.e("Stripe Error",error.getMessage());
}
#Override
public void onSuccess(com.stripe.android.model.Token token) {
Log.e("Bank Token", token.getId());
}
});
This should work like charm.
I made a mistake in my code. That is Token.create(tokenParams); should be handled with in AysncTask. Because it deals with network. After gone through their git repository I came to know. So, I handled that create token part in async task. The code I have changed is below:
int SDK_INT = android.os.Build.VERSION.SDK_INT;
final String[] tokens = {"new"};
Stripe.apiKey = "sk_test_0wgmvQOVjIpspIgKsoW7wtTp";
final Map<String, Object> tokenParams = new HashMap<String, Object>();
Map<String, Object> bank_accountParams = new HashMap<String, Object>();
bank_accountParams.put("country", "US");
bank_accountParams.put("currency", "usd");
bank_accountParams.put("account_holder_name", "Jayden Moore");
bank_accountParams.put("account_holder_type", "individual");
bank_accountParams.put("routing_number", "110000000");
bank_accountParams.put("account_number", "000123456789");
tokenParams.put("bank_account", bank_accountParams);
final Token[] responseToken = {null};
if (SDK_INT > 8)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
//your codes here
com.stripe.Stripe.apiKey = "sk_test_0wgmvQOVjIpspIgKsoW7wtTp";
new AsyncTask<Void, Void, Token>() {
String errorMsg = null;
#Override
protected Token doInBackground(Void... params) {
try {
return Token.create(tokenParams);
} catch (AuthenticationException e) {
e.printStackTrace();
return null;
} catch (InvalidRequestException e) {
e.printStackTrace();
return null;
} catch (APIConnectionException e) {
e.printStackTrace();
return null;
} catch (CardException e) {
e.printStackTrace();
return null;
} catch (APIException e) {
e.printStackTrace();
return null;
}
}
protected void onPostExecute(Token result) {
if (errorMsg == null) {
// success
} else {
// handleError(errorMsg);
}
}
}.execute();
}
I had the same problem and I fixed it by changing this line
compile 'com.stripe:stripe-android:+
into this line
compile 'com.stripe:stripe-android:1.1.1'
in my app.gradle file.
This might change for future releases.

Android: Google Authentication + Ubertoken

Ok, I give up. Anyone have experience using Google's IssueAuthToken and MergeSession to authenticate with certain Google services that do not have official API access? In this case I'm trying to get Google bookmarks (from google.com/bookmarks).
I get the SID and LSID using getAuthToken and that works fine. I then call
Uri ISSUE_AUTH_TOKEN_URL = Uri.parse("https://accounts.google.com/IssueAuthToken?service=bookmarks&Session=false");
String url = ISSUE_AUTH_TOKEN_URL.buildUpon()
.appendQueryParameter("SID", sid)
.appendQueryParameter("LSID", lsid)
.build().toString();
I receive the "ubertoken".
I then do a GET to MergeSession and that's where it all goes wrong:
String url2 = "https://accounts.google.com/MergeSession?source=chrome&uberauth="+uberToken+"&service=bookmarks&continue=https%3A%2F%2Fwww.google.com%2Fbookmarks%2F";
HttpGet getCookies = new HttpGet(url2);
Looking through the headers of getCookies I am not seeing the extra cookies I should see, and I also see things like X-Frame-Options: DENY.
Help (please)!
Okay friends, here we go. It seems the above is now unreliable/broken at least occasionally as of August 2013. This is how I'm doing it now and it seems to work. It tries the above first, and if it fails, goes on to method #2.
final Account acct = am.getAccountsByType("com.google")[acctid];
final String tokenType = "weblogin:service=bookmarks&continue=https://www.google.com/bookmarks/";
am.getAuthToken(acct, tokenType, null, this, new AccountManagerCallback<Bundle>() {
#Override
public void run(AccountManagerFuture<Bundle> future) {
try {
final String accessToken = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);
if (accessToken.contains("WILL_NOT_SIGN_IN")) {
am.getAuthToken(acct, "SID", null, MainActivity.this, new AccountManagerCallback<Bundle>() {
#Override
public void run(AccountManagerFuture<Bundle> future) {
try {
sid = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);
} catch (OperationCanceledException e) {
finish();
} catch (Exception e) {
e.printStackTrace();
}
am.getAuthToken(acct, "LSID", null, MainActivity.this, new AccountManagerCallback<Bundle>() {
#Override
public void run(AccountManagerFuture<Bundle> future) {
try {
lsid = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);
} catch (OperationCanceledException e) {
finish();
} catch (Exception e) {
e.printStackTrace();
}
Thread t = new Thread() {
public void run() {
try {
Uri ISSUE_AUTH_TOKEN_URL = Uri.parse("https://www.google.com/accounts/IssueAuthToken?service=gaia&Session=false");
Uri TOKEN_AUTH_URL = Uri.parse("https://www.google.com/accounts/TokenAuth");
final HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
httpclient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
String url = ISSUE_AUTH_TOKEN_URL.buildUpon().appendQueryParameter("SID", sid).appendQueryParameter("LSID", lsid).build().toString();
HttpPost getUberToken = new HttpPost(url);
HttpResponse response = httpclient.execute(getUberToken);
String uberToken = EntityUtils.toString(response.getEntity(), "UTF-8");
final String accessToken2 = TOKEN_AUTH_URL.buildUpon()
.appendQueryParameter("source", "android-browser")
.appendQueryParameter("auth", uberToken)
.appendQueryParameter("continue", "https://www.google.com/bookmarks/").build().toString();
//do stuff
} catch (Exception e) {
e.printStackTrace();
}
}
};
t.start();
}
}, null);
}
}, null);
} else {
//do stuff
}
} catch (OperationCanceledException e) {
finish();
} catch (Exception e) {
finish();
}
}
}, null);

Get access token from google plus Android

Can anyone tell me what am I doing wrong? I need to get the access token from Google Plus..
I put this in my onConnected() method but I am not getting the access token, instead I am getting error...
Code:
try {
String token = GoogleAuthUtil.getToken(this, mPlusClient.getAccountName() + "", "oauth2:" + Scopes.PLUS_PROFILE +
"https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email");
Log.d("AccessToken", token);
} catch (UserRecoverableAuthException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (GoogleAuthException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Error:
08-07 10:10:24.199: E/GoogleAuthUtil(17203): Calling this from your main thread can lead to deadlock and/or ANRs
Can anyone tell me what would be the correct way to get the Google Plus access token from the user?
You need to put the request for a token in a background thread. I've posted some example code showing how to do it in this question:
"Calling this from your main thread can lead to deadlock and/or ANRs while getting accesToken" from GoogleAuthUtil(Google Plus integration in Android)
You can access token in onConnected() method. add this code onConnected() methods scope.
final String SCOPES = "https://www.googleapis.com/auth/userinfo.profile";
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
String ace = "";
try {
ace = GoogleAuthUtil.getToken(getApplicationContext(),
Plus.AccountApi.getAccountName(mGoogleApiClient),
"oauth2:" + SCOPES);
}
catch (IOException e) {
e.printStackTrace();
}
catch (GoogleAuthException e) {
e.printStackTrace();
}
Log.i("", "mustafa olll " + ace);
return null;
}
}.execute();
You need to fetch it using async task.
public void onConnected(Bundle connectionHint) {
// Reaching onConnected means we consider the user signed in.
Log.i(TAG, "onConnected");
// Update the user interface to reflect that the user is signed in.
mSignInButton.setEnabled(false);
mSignOutButton.setEnabled(true);
mRevokeButton.setEnabled(true);
// Retrieve some profile information to personalize our app for the user.
Person currentUser = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
AsyncTask<Void, Void, String > task = new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String token = null;
final String SCOPES = "https://www.googleapis.com/auth/plus.login ";
try {
token = GoogleAuthUtil.getToken(
getApplicationContext(),
Plus.AccountApi.getAccountName(mGoogleApiClient),
"oauth2:" + SCOPES);
} catch (IOException e) {
e.printStackTrace();
} catch (GoogleAuthException e) {
e.printStackTrace();
}
return token;
}
#Override
protected void onPostExecute(String token) {
Log.i(TAG, "Access token retrieved:" + token);
}
};
task.execute();
System.out.print("email" + email);
mStatus.setText(String.format(
getResources().getString(R.string.signed_in_as),
currentUser.getDisplayName()));
Plus.PeopleApi.loadVisible(mGoogleApiClient, null)
.setResultCallback(this);
// Indicate that the sign in process is complete.
mSignInProgress = STATE_DEFAULT; }
Your access token will be stored into token variable.
Here is the code you can use. If someone has better suggestion then please post:
/**
* Successfully connected (called by PlusClient)
*/
#Override
public void onConnected(Bundle connectionHint) {
/* First do what ever you wanted to do in onConnected() */
....
....
/* Now get the token using and async call*/
GetGooglePlusToken token = new GetGooglePlusToken(this.getActivity(), mPlusClient);
token.execute();
}
class GetGooglePlusToken extends AsyncTask<Void, Void, String> {
Context context;
private GoogleApiClient mGoogleApiClient;
private String TAG = this.getClass().getSimpleName();
public GetGooglePlusToken(Context context, GoogleApiClient mGoogleApiClient) {
this.context = context;
this.mGoogleApiClient = mGoogleApiClient;
}
#Override
protected String doInBackground(Void... params) {
String accessToken1 = null;
try {
Bundle bundle = new Bundle();
String accountname = Plus.AccountApi.getAccountName(mGoogleApiClient);
String scope = "oauth2:" + Scopes.PLUS_LOGIN + " " + "https://www.googleapis.com/auth/userinfo.email" + " https://www.googleapis.com/auth/plus.profile.agerange.read";
accessToken1 = GoogleAuthUtil.getToken(context,
accountname,
scope);
return accessToken1;
} catch (IOException transientEx) {
// network or server error, the call is expected to succeed if you try again later.
// Don't attempt to call again immediately - the request is likely to
// fail, you'll hit quotas or back-off.
//TODO: HANDLE
Log.e(TAG, "transientEx");
transientEx.printStackTrace();
accessToken1 = null;
} catch (UserRecoverableAuthException e) {
// Recover
Log.e(TAG, "UserRecoverableAuthException");
e.printStackTrace();
accessToken1 = null;
} catch (GoogleAuthException authEx) {
// Failure. The call is not expected to ever succeed so it should not be
// retried.
Log.e(TAG, "GoogleAuthException");
authEx.printStackTrace();
accessToken1 = null;
} catch (Exception e) {
Log.e(TAG, "RuntimeException");
e.printStackTrace();
accessToken1 = null;
throw new RuntimeException(e);
}
Log.wtf(TAG, "Code should not go here");
accessToken1 = null;
return accessToken1;
}
#Override
protected void onPostExecute(String response) {
Log.d(TAG, "Google access token = " + response);
}
}

OAuth1a retrieveRequestToken throw null

i have some trouble with the OAuth signing.
on the point i expect to get the retrieveRequestToken i got the following error:
01-05 17:26:02.775: W/System.err(24358): oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: null
i have no idea why i get this. Any suggestions here?
My Code:
connectionDec = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!connectionDec.isConnectingToInternet())
{
// Internet Connection is not present
// alert.showAlertDialog(MainActivity.this,
// "Internet Connection Error",
// "Please connect to working Internet connection", false);
// stop executing code by return
return;
}
CommonsHttpOAuthConsumer consumer =
new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
CommonsHttpOAuthProvider provider =
new CommonsHttpOAuthProvider(REQUEST_TOKEN_URL, ACCESS_TOKEN_URL,
AUTHORIZE_URL);
provider.setOAuth10a(true);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String token = sharedPreferences.getString("token", null);
String tokenSecret = sharedPreferences.getString("token_secret", null);
if (token == null || tokenSecret == null)
{
Map requestHeaders = provider.getRequestHeaders();
requestHeaders.put("User-Agent", USER_AGENT);
requestHeaders.put("Accept-Encoding", "gzip");
try
{
String authUrl = provider.retrieveRequestToken(consumer, CALLBACK_URL);
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
}
catch (OAuthMessageSignerException e)
{
e.printStackTrace();
}
catch (OAuthNotAuthorizedException e)
{
e.printStackTrace();
}
catch (OAuthExpectationFailedException e)
{
e.printStackTrace();
}
catch (OAuthCommunicationException e)
{
e.printStackTrace();
}
}
else
{
}
any tipps and helps ... thank you
PS: It is Discogs and not Twitter
Greets Mad
OK, i have answered the question myself ... i have implement a asynctask like the following and it works:
public class StartUpActivity extends Activity implements OnClickListener
{
private static String CONSUMER_KEY = "consumerkey";
private static String CONSUMER_SECRET = "yourconsumersecret";
private static String REQUEST_TOKEN_URL = "http://api.discogs.com/oauth/request_token";
private static String AUTHORIZE_URL = "http://www.discogs.com/oauth/authorize";
private static String ACCESS_TOKEN_URL = "http://api.discogs.com/oauth/access_token";
private static String USER_AGENT = "youruseragent";
private static String CALLBACK_URL = "http://www.callback.com";
private ConnectionDetector connectionDec;
private SharedPreferences sharedPreferences;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.start_up_layout);
connectionDec = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!connectionDec.isConnectingToInternet())
{
// Internet Connection is not present
// alert.showAlertDialog(MainActivity.this,
// "Internet Connection Error",
// "Please connect to working Internet connection", false);
// stop executing code by return
return;
}
}
class ProgressTask extends AsyncTask<Integer, Integer, Void>{
#Override
protected void onPreExecute() {
// initialize the progress bar
// set maximum progress to 100.
}
#Override
protected void onCancelled() {
// stop the progress
}
#Override
protected Void doInBackground(Integer... params) {
// get the initial starting value
int start=params[0];
// increment the progress
try {
CommonsHttpOAuthConsumer consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
CommonsHttpOAuthProvider provider =
new CommonsHttpOAuthProvider(REQUEST_TOKEN_URL, ACCESS_TOKEN_URL, AUTHORIZE_URL);
provider.setOAuth10a(true);
// Check if token and tokensecret are already stored at app preferences
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String token = sharedPreferences.getString("token", null);
String tokenSecret = sharedPreferences.getString("token_secret", null);
if (token == null || tokenSecret == null)
{
Map<String, String> requestHeaders = provider.getRequestHeaders();
requestHeaders.put("User-Agent", USER_AGENT);
requestHeaders.put("Accept-Encoding", "gzip");
try
{
String authUrl = provider.retrieveRequestToken(consumer, CALLBACK_URL);
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
}
catch (OAuthMessageSignerException e)
{
e.printStackTrace();
}
catch (OAuthNotAuthorizedException e)
{
e.printStackTrace();
}
catch (OAuthExpectationFailedException e)
{
e.printStackTrace();
}
catch (OAuthCommunicationException e)
{
e.printStackTrace();
}
}
else
{
}
}
catch (Exception e) {
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
// increment progress bar by progress value
}
#Override
protected void onPostExecute(Void result) {
// async task finished
}
}
}

Categories

Resources