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

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.

Related

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.

Getting JSONException with Retrofit 2 on Android

I am using Fabric.io Twitter Kit. Created a custom service class and used Retrofit to convert the interface within that class. Code at the bottom (CustomTwitterApiClient Class).
I either get NullPointerException and if I catch that, I get JSONException. As can be seen in the log, I can get trends response but I cant read it. If I try to readLine() it and append it to a StringBuilder, I get null.
I wrote the code with the guidance of this SO answer.
What I am doing wrong ?
Thanks in advance.
PS: Those extra exception handlers just to get a clean log.
D/LOG-DEBUG: Line 86 : [{"trends":[{"name":"#Worlds","url":"http:\/\/twitter.com\/search?q=%23Worlds","promoted_content":null,"query":"%23Worlds","tweet_volume":99974},{"name":"#LaNocheDeML","url":"http:\/\/twitter.com\/search?q=%23LaNocheDeML","promoted_content":null,"query":"%23LaNocheDeML","tweet_volume":56697},{"name":"#CLEMVSFSU","url":"http:\/\/twitter.com\/search?q=%23CLEMVSFSU","promoted_content":null,"query":"%23CLEMVSFSU","tweet_volume":10016},{"name":"#\u0634\u064A_\u062A\u062D\u0628_\u062A\u0634\u0645\u0647","url":"http:\/\/twitter.com\/search?q=%23%D8%B4%D9%8A_%D8%AA%D8%AD%D8%A8_%D8%AA%D8%B4%D9%85%D9%87","promoted_content":null,"query":"%23%D8%B4%D9%8A_%D8%AA%D8%AD%D8%A8_%D8%AA%D8%B4%D9%85%D9%87","tweet_volume":52441},{"name":"#DiosdadoEsPueblo","url":"http:\/\/twitter.com\/search?q=%23DiosdadoEsPueblo","promoted_content":null,"query":"%23DiosdadoEsPueblo","tweet_volume":44538},{"name":"Juanma","url":"http:\/\/twitter.com\/search?q=Juanma","promoted_content":null,"query":"Juanma","tweet_volume":13642},{"name":"Vince Vaughn","url":"http:\/\/twitter.com\/search?q=%22Vince+Vaughn%22","promoted_content":null,"query":"%22Vince+Vaughn%22","tweet_volume":10409},{"name":"Florida State","url":"http:\/\/twitter.com\/search?q=%22Florida+State%22","promoted_content":null,"query":"%22Florida+State%22","tweet_volume":10936},{"name":"Francois","url":"http:\/\/twitter.com\/search?q=Francois","promoted_content":null,"query":"Francois","tweet_volume":24324},{"name":"HOJE TEM TWD","url":"http:\/\/twitter.com\/search?q=%22HOJE+TEM+TWD%22","promoted_content":null,"query":"%22HOJE+TEM+TWD%22","tweet_volume":null},{"name":"Atividade Paranormal 4","url":"http:\/\/twitter.com\/search?q=%22Atividade+Paranormal+4%22","promoted_content":null,"query":"%22Atividade+Paranormal+4%22","tweet_volume":null},{"name":"BELIEBERS VOTANDO","url":"http:\/\/twitter.com\/search?q=%22BELIEBERS+VOTANDO%22","promoted_content":null,"query":"%22BELIEBERS+VOTANDO%22","tweet_volume":56259},{"name":"South Carolina","url":"http:\/\/twitter.com\/search?q=%22South+Carolina%22","promoted_content":null,"query":"%22South+Carolina%22","tweet_volume":16795},{"name":"Deshaun Watson","url":"http:\/\/twitter.com\/search?q=%22Deshaun+Watson%22","promoted_content":null,"query":"%22Deshaun+Watson%22","tweet_volume":12224},{"name":"Soulja Boy","url":"http:\/\/twitter.com\/search?q=%22Soulja+Boy%22","promoted_content":null,"query":"%22Soulja+Boy%22","tweet_volume":196642},{"name":"\uB864\uB4DC\uCEF5","url":"http:\/\/twitter.com\/search?q=%EB%A1%A4%EB%93%9C%EC%BB%B5","promoted_content":null,"query":"%EB%A1%A4%EB%93%9C%EC%BB%B5","tweet_volume":null},{"name":"Racing","url":"http:\/\/twitter.com\/search?q=Racing","promoted_content":null,"query":"Racing","tweet_volume":69655},{"name":"Jimbo","url":"http:\/\/twitter.com\/search?q=Jimbo","promoted_content":null,"query":"Jimbo","tweet_volume":null},{"name":"Silver Scrapes","url":"http:\/\/twitter.com\/search?q=%22Silver+Scrapes%22","promoted_content":null,"query":"%22Silver+Scrapes%22","tweet_volume":null},{"name":"#\u0627\u0646\u0627_\u0645\u0648\u0627\u0637\u0646_\u0645\u062B\u0644\u064A_\u0645\u062B\u0644\u0643\u0645","url":"http:\/\/twitter.com\/search?q=%23%D8%A7%D9%86%D8%A7_%D9%85%D9%88%D8%A7%D8%B7%D9%86_%D9%85%D8%AB%D9%84%D9%8A_%D9%85%D8%AB%D9%84%D9%83%D9%85","promoted_content":null,"query":"%23%D8%A7%D9%86%D8%A7_%D9%85%D9%88%D8%A7%D8%B7%D9%86_%D9%85%D8%AB%D9%84%D9%8A_%D9%85%D8%AB%D9%84%D9%83%D9%85","tweet_volume":23899},{"name":"#\u0627\u0637\u0631\u062F\u0648_\u0627\u0635\u062D\u0627\u0628_\u0627\u0644\u0642\u0647\u0648\u0647_\u0627\u0644\u0633\u0648\u062F\u0627\u0621","url":"http:\/\/twitter.com\/search?q=%23%D8%A7%D8%B7%D8%B1%D8%AF%D9%88_%D8%A7%D8%B5%D8%AD%D8%A7%D8%A8_%D8%A7%D9%84%D9%82%D9%87%D9%88%D9%87_%D8%A7%D9%84%D8%B3%D9%88%D8%AF%D8%A7%D8%A1","promoted_content":null,"query":"%23%D8%A7%D8%B7%D8%B1%D8%AF%D9%88_%D8%A7%D8%B5%D8%AD%D8%A7%D8%A8_%D8%A7%D9%84%D9%82%D9%87%D9%88%D9%87_%D8%A7%D9%84%D8%B3%D9%88%D8%AF%D8%A7%D8%A1","tweet_volume":null},{"name":"#\u0627\u0646\u0627_\u0645\u062F\u0627\u0648\u0
D/LOG-DEBUG: Line 111:
W/System.err: org.json.JSONException: End of input at character 0 of
W/System.err: at org.json.JSONTokener.syntaxError(JSONTokener.java:450)
W/System.err: at org.json.JSONTokener.nextValue(JSONTokener.java:97)
W/System.err: at org.json.JSONArray.<init>(JSONArray.java:92)
W/System.err: at org.json.JSONArray.<init>(JSONArray.java:108)
W/System.err: at .MainActivity$1$1.onResponse(MainActivity.java:113)
W/System.err: at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
And this the code block the error pointing :
#Override
public void success(Result<TwitterSession> result) {
// The TwitterSession is also available through:
// Twitter.getInstance().core.getSessionManager().getActiveSession()
TwitterSession session = result.data;
// TODO: Remove toast and use the TwitterSession's userID
// with your app's user model
String msg = "#" + session.getUserName() + " logged in! (#" + session.getUserId() + ")";
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
CustomTwitterApiClient customTwitterApiClient = new CustomTwitterApiClient(session);
Call<ResponseBody> cevap = customTwitterApiClient.getCustomService().show(1);
cevap.enqueue(new retrofit2.Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
BufferedReader reader = null;
StringBuilder stringBuilder2 = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(response.body().byteStream()));
} catch (Exception e) {
e.printStackTrace();
}
try {
Log.d("READER", "86 : reader.readLine() : "+reader.readLine());
} catch (IOException e) {
e.printStackTrace();
}
String line= "";
try{
while ((line = reader.readLine())!= null)
{
try {
stringBuilder2.append(line);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
catch(IOException e){
e.printStackTrace();
}
try {
Log.d("READER", "111: stringBuilder2.toString(): " +stringBuilder2.toString());
} catch (Exception e) {
e.printStackTrace();
}
try {
JSONArray sonucJsonArray = new JSONArray(stringBuilder2.toString());
JSONObject sonucJsonObject = sonucJsonArray.getJSONObject(0);
JSONArray trendsJsonArray = sonucJsonObject.getJSONArray("trends");
JSONObject trendJson;
for(int i=0; i < trendsJsonArray.length() ; i++){
TrendTopic trend = new TrendTopic();
trendJson = trendsJsonArray.getJSONObject(i);
trend.set_id(i+1);
trend.set_trendName(trendJson.getString("name"));
trend.set_trendQuery(trendJson.getString("query"));
trend.set_trendURL(trendJson.getString("url"));
trendTopics.add(i,trend);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
This is the CustomTwitterApiClient Class :
public class CustomTwitterApiClient extends TwitterApiClient {
public CustomTwitterApiClient(TwitterSession session) {
super(session);
}
public CustomService getCustomService() {
return getService(CustomService.class);
}
}
interface CustomService {
#GET("/1.1/trends/place.json")
Call<ResponseBody> show(#Query("id") int id);
}

empty crash file when using ACRA

i am using the code below to generate a crash file, the file is created at parse.com but it is empty.
any idea why?
Another problem is that "ACRA.DEFAULT_REPORT_FIELDS;" has an error, default report fields is not available.
public class LocalSender implements ReportSender {
private final Map<ReportField, String> mMapping = new HashMap<ReportField, String>() ;
private FileOutputStream crashReport = null;
private Context ctx;
public LocalSender(Context ct) {
ctx = ct;
}
public void send(CrashReportData report) throws ReportSenderException {
final Map<String, String> finalReport = remap(report);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
Log.i("hcsh","Report send");
try {
Set set = finalReport.entrySet();
Iterator i = set.iterator();
String tmp;
while (i.hasNext()) {
Map.Entry<String,String> me = (Map.Entry) i.next();
tmp = "[" + me.getKey() + "]=" + me.getValue();
buf.write(tmp.getBytes());
}
ParseFile myFile = new ParseFile("crash.txt", buf.toByteArray());
myFile.save();
ParseObject jobApplication = new ParseObject("AppCrash");
jobApplication.put("MyCrash", "app name");
jobApplication.put("applicantResumeFile", myFile);
try {
jobApplication.save();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}catch (FileNotFoundException e) {
Log.e("TAG", "IO ERROR",e);
}
catch (IOException e) {
Log.e("TAG", "IO ERROR",e);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private Map<String, String> remap(Map<ReportField, String> report) {
ReportField[] fields = ACRA.getConfig().customReportContent();
if (fields.length == 0) {
fields = ACRA.DEFAULT_REPORT_FIELDS;
}
final Map<String, String> finalReport = new HashMap<String, String>(
report.size());
for (ReportField field : fields) {
if (mMapping == null || mMapping.get(field) == null) {
finalReport.put(field.toString(), report.get(field));
} else {
finalReport.put(mMapping.get(field), report.get(field));
}
}
return finalReport;
}
}
There is no such constant as ACRA.DEFAULT_REPORT_FIELDS. You are looking for ACRAConstants.DEFAULT_REPORT_FIELDS
ACRA.DEFAULT_REPORT_FIELDS constant value is in acra-4.3.0 version ...
if you are using acra-4.5.0 version ACRA you will get this error "DEFAULT_REPORT_FIELDS cannot be resolved or is not a field" .
try to use acra-4.5.0 version and then use following code
// Extract the required data out of the crash report.
String reportBody = createCrashReport(report);
/** Extract the required data out of the crash report. */
private String createCrashReport(CrashReportData report) {
// I've extracted only basic information.
// U can add loads more data using the enum ReportField. See below.
StringBuilder body = new StringBuilder();
body.append(
"Device : " + report.getProperty(ReportField.BRAND) + "-"
+ report.getProperty(ReportField.PHONE_MODEL))
.append("\n")
.append("Android Version :"
+ report.getProperty(ReportField.ANDROID_VERSION))
.append("\n")
.append("App Version : "
+ report.getProperty(ReportField.APP_VERSION_CODE))
.append("\n")
.append("STACK TRACE : \n"
+ report.getProperty(ReportField.STACK_TRACE));
return body.toString();
}
Don't use following code
////////////////////////
final String reportBody = buildBody(arg0);
private String buildBody(CrashReportData errorContent) {
ReportField[] fields = ACRA.getConfig().customReportContent();
if (fields.length == 0) {
// fields = ACRA.DEFAULT_MAIL_REPORT_FIELDS;
fields = ACRA.DEFAULT_REPORT_FIELDS;
}
final StringBuilder builder = new StringBuilder();
for (ReportField field : fields) {
builder.append(field.toString()).append("=");
builder.append(errorContent.get(field));
builder.append('\n');
}
return builder.toString();
}
Happy Coding....

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);
}
}

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

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");
}
});
}

Categories

Resources