how can i display progress bar for dailymotion cloud uploading - java

I am using Dailymotion cloud in my android app to upload videos to server.
i want to display progress bar while uploading but i don't know how can i get byte by byte value to update progress bar.
This is dailymotion cloud api link Dailymotion cloud api link
While searching on internet i found this progress bar in java but i don't know how can i implement into this method of dailymotion api.
I am using async task to display progress bar
Here is android code for uploading
try
{
CloudKey cloud = new CloudKey(user_id, api_key);
File f = new File(selectedVideoPath);
String media_id = cloud.mediaCreate(f);
System.out.println(media_id);
Log.d("Testing", "media_id is"+media_id);
}
And here is Dailymotion API's Cloud.class mediacreate() in which i want to display progress bar .. any idea
public String mediaCreate(File f) throws Exception
{
return this.mediaCreate(f, null, null);
}
public String mediaCreate(File f, DCArray assets_names, DCObject meta) throws Exception
{
String upload_url = this.fileUpload();
PostMethod filePost = null;
int status;
try
{
filePost = new PostMethod(upload_url);
Part[] parts = {
new FilePart("file", f)
};
filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
HttpClient client = new HttpClient();
client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
status = client.executeMethod(filePost);
if (status == HttpStatus.SC_OK)
{
ObjectMapper mapper = new ObjectMapper();
DCObject json_response = DCObject.create(mapper.readValue(filePost.getResponseBodyAsString(), Map.class));
return this.mediaCreate(json_response.pull("url"), assets_names, meta);
}
else
{
throw new DCException("Upload failed.");
}
}
catch (Exception e)
{
throw new DCException("Upload failed: " + e.getMessage());
}
finally
{
if (filePost != null)
{
filePost.releaseConnection();
}
}
}

I'm not able to find any api support for doing this with the DailyMotion class that you mentioned.
If you can edit the source of that library, then you could try extending MultipartRequestEntity and add support for callbacks for progress, and then just plug in that new class in the DailyMotion code in the mediaCreate method:
filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
.. replace MultipartRequestEntity by the new one, eg. ExtendedMultipartRequestEntity.
See the answer by Tuler and others at File Upload with Java (with progress bar) to see how to do it.
Once you are getting updates via the callback, then you can hook up progress bar.

Related

Android HTTP Requests Working In Simulator But Not On Wear Device

I am making a simple Android Wear app to control my thermostats, and I'm sending POST requests with Volley to control them. Everything works great in the Android Wear simulator (the request works), but, while the app does load on my Moto 360, the volley request gets called but invariably times out.
Why could my volley request be failing on my watch but working on the simulator? Other apps' requests succeed on my watch (for example, the built-in weather app can load up weather data in about 3 seconds). And, the weirdest part: I had the app working (successfully making volley requests) on my watch, and, about a day after I installed it to my watch from Android Studio, it suddenly stopped loading data for no apparent reason.
What I've tried so far:
I have requested the Internet permission in my manifest.xml.
I have increased the timeout to 30 seconds (see my code below), which didn't change anything.
I have tried tethering my computer and the simulator to my phone's connection via Bluetooth (to replicate the Bluetooth connection my physical watch has to my phone), and the simulator made the request successfully still (albeit with a two-second delay), ruling out the possibility of Bluetooth being too slow.
I made sure the API level is low enough for my Marshmallow-running watch (my watch and the app are both API level 23).
I tried doing a quick test request to Google before the request to the company's servers with my thermostat data, and while the Google request returns the site's HTML code in the simulator, it times out on my watch (thirty seconds after the request is initiated).
I tried putting some dummy data into the recycler view data should be loaded into, and the dummy data indeed showed up, ruling out that the recycler view is broken.
I deleted the app from my watch and reinstalled it, and deleted the companion from my phone, reinstalled it, and deleted it again, all to no avail.
A lengthy chat with Google Support did not produce anything meaningful.
Here's my code (from my main view's adapter):
public void refreshThermostatsRecyclerView(RequestQueue queue) {
String url = "https://mobile.skyport.io:9090/login"; // login call to the thermostats server Skyport
Log.w("myApp", "Starting /login call to Skyport"); // this gets called on simulator and watch
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the response string.
Log.w("myApp", "Response is: " + response); // this gets called on the simulator but not the watch
try {
// there's some code to parse the data.
} catch (JSONException e) {
Log.w("myApp", "catching an error parsing the json."); // never gets called.
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.w("myApp", "Skyport request didn't work! " + error); // this always gets called on the watch, with the error being a timeout error (com.Android.Volley.timeouterror) but never gets called in the simulator
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> m = new HashMap<>();
m.put("Referer", "app:/VenstarCloud.swf");
// here I put some more headers
return m;
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> m = new HashMap<>();
m.put("version", "3.0.5");
m.put("email", userEmail);
m.put("password", userToken);
return m;
}
};
// Add the request to the RequestQueue.
int socketTimeout1 = 30000; // times out 30 seconds after the request starts on the watch
RetryPolicy policy1 = new DefaultRetryPolicy(socketTimeout1, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy1);
queue.add(stringRequest);
}
Which is called from the onCreate() method in my Main Activity with this code:
RequestQueue queue = Volley.newRequestQueue(this);
refreshThermostatsRecyclerView(queue);
If you'd like to view the logs created by running this in the simulator and on the watch, they're on Google Drive here.
Edit 1: A reboot of my watch fixes the issue temporarily and allows the watch to make HTTP Requests again, but it breaks again once the watch disconnects from Bluetooth, connects to WiFi, disconnects from WiFi, and reconnects to Bluetooth (so it breaks every time I go across my apartment without my phone and then return).
Edit 2: I switched the volley requests all over to HTTPURLConnection Requests in an Async thread, and the same issues occur as with volley.
tl;dr: My app's Volley requests are working in the simulator but not on my Android Wear watch anymore (though Play Store-downloaded apps' similar requests work), how can I get a volley request to work again on my app on the watch?
As per these two conversations below, it seems that WiFi connectivity only allows Android Wear to connect to a phone over WiFi and not directly to the Internet. However, Android Wear 2.0 lets you use regular network APIs.
Direct internet connection on Android Wear?
Does Android Wear support direct access to the Internet?
So, for Android Wear 2.0+ Volley requests from wearable app should work.
If you want to use Android Wear <2.0, then:
On Wearable, in onCreate() add a key that indicates whether the phone should start collecting data.
PutDataMapRequest putDataMapReq = PutDataMapRequest.create("/shouldStart");
putDataMapReq.getDataMap().putBoolean(SHOULD_START_KEY, true);
PutDataRequest putDataReq = putDataMapReq.asPutDataRequest();
PendingResult pendingResult = Wearable.DataApi.putDataItem(mGoogleApiClient, putDataReq);
On phone, in onDataChanged, check if wearable wants to start collecting data. If yes, start Volley request.
for (DataEvent event : dataEvents) {
if (event.getType() == DataEvent.TYPE_CHANGED) {
// DataItem changed
DataItem item = event.getDataItem();
if (item.getUri().getPath().compareTo("/shouldStart") == 0) {
DataMap dataMap = DataMapItem.fromDataItem(item).getDataMap();
boolean shouldStart = dataMap.getBoolean(SHOULD_START_KEY));
if(shouldStart) {
Volley.newRequestQueue(this).add(request);
}
}
} else if (event.getType() == DataEvent.TYPE_DELETED) {
// DataItem deleted
}
}
Then, your Volley request's onResponse should pass data back to Wearable.
public void onResponse(String response) {
PutDataMapRequest putDataMapReq = PutDataMapRequest.create("/data");
putDataMapReq.getDataMap().putString(DATA_KEY, true);
PutDataRequest putDataReq = putDataMapReq.asPutDataRequest();
PendingResult pendingResult = Wearable.DataApi.putDataItem(mGoogleApiClient, putDataReq);
}
Finally, you can access data in your Wearable using onDataChanged and store it in your model for passing it onto adapter:
for (DataEvent event : dataEvents) {
if (event.getType() == DataEvent.TYPE_CHANGED) {
// DataItem changed
DataItem item = event.getDataItem();
if (item.getUri().getPath().compareTo("/data") == 0) {
DataMap dataMap = DataMapItem.fromDataItem(item).getDataMap();
parseAndpassToAdapter(dataMap.getString(DATA_KEY));
}
} else if (event.getType() == DataEvent.TYPE_DELETED) {
// DataItem deleted
}
}
You'll need Wearable.API to implement this and your class should implement DataApi.DataListener. For more information getting started, refer to Accessing the Wearable Data Layer and Syncing Data Items
Hope this helps.
I am also using volley on an Android wear app I built and I am running it on a Moto 360, I have run into the same problem a couple o times. Try restarting the device. Go to Settings > Restart. It sounds silly but it has worked for me.
You could try an alternative to volley if you can rule out the connection as the problem:
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:support-v4:23.1.0'
compile 'com.android.support:design:23.1.0'
compile 'com.google.code.gson:gson:2.2.4'
compile 'com.google.api-client:google-api-client:1.20.0'
The versions are important.
Then to your request:
Map<String, String> contentParams = new HashMap<>();
InputStream is = null;
NetHttpTransport transport = null;
HttpRequest request = null;
HttpResponse resp = null;
HttpHeaders headers = new HttpHeaders();
JSONObject json = null;
try {
transport = new NetHttpTransport();
HttpRequestFactory factory = transport.createRequestFactory();
request = factory.buildPostRequest(new GenericUrl(url), null);
contentParams = getContentParameters();
headers.putAll(getHeaderParameters());
request.setHeaders(headers);
request.getUrl().putAll(contentParams);
resp = request.execute();
is = resp.getContent();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
string = getJSONFromInputStream(is);
json = new JSONObject(string);
}
} catch (Exception e) {
e.printStackTrace();
}
}
transport.shutdown();
protected Map<String, String> getContentParameters() {
Map<String, String> m = new HashMap<>();
m.put("version", "3.0.5");
m.put("email", userEmail);
m.put("password", userToken);
return m;
}
protected Map<String, String> getHeaderParameters() {
Map<String, String> m = new HashMap<>();
m.put("Referer", "app:/VenstarCloud.swf");
return m;
}
protected String getJSONFromInputStream(InputStream is) {
if (is == null)
throw new NullPointerException();
//instantiates a reader with max size
BufferedReader reader = new BufferedReader(new InputStreamReader(is), 8 * 1024);
StringBuilder sb = new StringBuilder();
try {
//reads the response line by line (and separates by a line-break)
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
//closes the inputStream
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Then just execute your code from a thread/asynctask/have it delay your frontend slightly
Edit:
Just in case there is a problem with appending a map:
for (Entry<String, String> entry : getHeaderParameters()) {
headers.put(entry.getKey(), entry.getValue());
}
for (Entry<String, String> entry : getContentParameters()) {
request.getUrl().put(entry.getKey(), entry.getValue());
}
Also as another note, make sure to change the return type from void on both those methods to Map
Is this not just the case of when the watch is connected to the phone via bluetooth the internet will not work, as wifi is turned off. If the watch is using wifi to connect to the phone then it will work.
I'm working on wear 2.0 app and just turn blueooth off on my phone for my watch to get internet connection.

How to get direct link of remote video from embedded url within a url in Android using JSoup?

I had asked the question previously about how to retrieve the embedded url for a video file and have successfully done so. Now I have a different issue. The json response for a WUnderground API webcam response gives the following url:
https://www.wunderground.com/webcams/cadot1/902/show.html
Using JSoup and per the answer to my initial issue I was able to get this embedded link:
https://www.wunderground.com/webcams/cadot1/902/video.html?month=11&year=2016&filename=current.mp4
While trying to "stream" the video from that url to a VideoView, I kept getting the error "cannot play video". Upon looking at the source for that link I noticed that the video file that needs to be played is not referenced in html but rather javascript. How can I get the direct link for the video file that needs to be played? Using JSoup or other process?
The source for the url https://www.wunderground.com/webcams/cadot1/902/video.html?month=11&year=2016&filename=current.mp4 shows the following for the needed video file within a <script> bracket:
url: "//icons.wunderground.com/webcamcurrent/c/a/cadot1/902/current.mp4?e=1480377508"
I am using JSoup to get the embedded url for the video from the response url like so:
private class VideoLink extends AsyncTask<Void, Void, Void> {
String title;
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.setTitle("JSOUP Test");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
// for avoiding javax.net.ssl.SSLProtocolException: handshake alert: unrecognized_name
System.setProperty("jsse.enableSNIExtension", "false");
// WARNING: do it only if security isn't important, otherwise you have
// to follow this advices: http://stackoverflow.com/a/7745706/1363265
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager(){
public X509Certificate[] getAcceptedIssuers(){return null;}
public void checkClientTrusted(X509Certificate[] certs, String authType){}
public void checkServerTrusted(X509Certificate[] certs, String authType){}
}};
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
;
}
// Connect to the web site
Document doc = Jsoup.connect(TEST_URL).get();
Elements elements = doc.getElementsByClass("videoText");
// Get the html document title
for (Element link : elements) {
String linkHref = link.attr("href");
// linkHref contains something like video.html?month=11&year=2016&filename=current.mp4
// TODO check if linkHref ends with current.mp4
title = linkHref;
}
} catch (IOException e) {
e.printStackTrace();
mProgressDialog.dismiss();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// Set title into TextView
resultTxt.setText(title);
String resVid = TEST_URL;
Log.d(TAG, "URL: " + resVid);
Uri resUri = Uri.parse(resVid);
try {
// Start the MediaController
MediaController mediacontroller = new MediaController(
MainActivity.this);
mediacontroller.setAnchorView(resultVidVw);
// Get the URL from String VideoURL
Uri video = Uri.parse(resVid);
resultVidVw.setMediaController(mediacontroller);
resultVidVw.setVideoURI(video);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
resultVidVw.requestFocus();
resultVidVw.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
// Close the progress bar and play the video
public void onPrepared(MediaPlayer mp) {
mProgressDialog.dismiss();
resultVidVw.start();
}
});
}
}
Please note that I need to do this on every JSONObject in the response array.
This is how you can GET the file:
(Notice: the Extraction part only works with current html of the site and if that changes, it may not work correctly!)
String url = "https://www.wunderground.com/webcams/cadot1/902/video.html";
int timeout = 100 * 1000;
// Extract video URL
Document doc = Jsoup.connect(url).timeout(timeout).get();
Element script = doc.getElementById("inner-content")
.getElementsByTag("script").last();
String content = script.data();
int indexOfUrl = content.indexOf("url");
int indexOfComma = content.indexOf(',', indexOfUrl);
String videoUrl = "https:" + content.substring(indexOfUrl + 6, indexOfComma - 1);
System.out.println(videoUrl);
[Output: https://icons.wunderground.com/webcamcurrent/c/a/cadot1/902/current.mp4?e=1481246112]
Now you can get the file by specifying .ignoreContentType(true) in order to avoid org.jsoup.UnsupportedMimeTypeException and .maxBodySize(0) to remove the limit on file size.
// Get video file
byte[] video = Jsoup.connect(videoUrl)
.ignoreContentType(true).timeout(timeout).maxBodySize(0)
.execute().bodyAsBytes();
I don't know if you can play it in Android or not but I think you can save it using org.apache.commons.io.FileUtils (I tested it in Java SE but not Android development environment.)
// Save video file
org.apache.commons.io.FileUtils.writeByteArrayToFile(new File("test.mp4"), video);

how to send a Photo with caption in telegram using ex3ndr?

I am using ex3ndr for creating a telegram client. now i want to send a message witch has a photo and a caption or description. I send photo using this code snippet:
private static void sendMedia(PeerState peerState, String fileName) {
TLAbsInputPeer inputPeer = peerState.isUser() ? new TLInputPeerContact(peerState.getId()) : new TLInputPeerChat(peerState.getId());
int task = api.getUploader().requestTask(fileName, null);
api.getUploader().waitForTask(task);
int resultState = api.getUploader().getTaskState(task);
Uploader.UploadResult result = api.getUploader().getUploadResult(task);
TLAbsInputFile inputFile;
if (result.isUsedBigFile()) {
inputFile = new TLInputFileBig(result.getFileId(), result.getPartsCount(), "file.jpg");
} else {
inputFile = new TLInputFile(result.getFileId(), result.getPartsCount(), "file.jpg", result.getHash());
}
try {
TLAbsStatedMessage res = api.doRpcCall(new TLRequestMessagesSendMedia(inputPeer, new TLInputMediaUploadedPhoto(inputFile), rnd.nextInt()), 30000);
res.toString();
} catch (IOException e) {
e.printStackTrace();
}
}
but I donot know how can add caption to this photo?(this code snippet is a sample from this url: ex3ndr sample
)
ex3ndr library only support layer 12 of Telegram API where sendMedia method doesn't support captions in photos. That's means this library is not able to send captions with photos, the layer should be updated before being able of doing so (and the repository seems to be abandoned).

Fetch JSON Data from URL and Repeatedly Update SQLite Database

In my app, I create a SQLite database. Then I populate it with JSON data fetched from a URL using an instance of the HttpAsyncTask class in my main activity. That works fine, but I also want to update the database. New data (one row in the database) is added to the URL page once per day, and I want to implement a "synchronize" button in the app that updates the database with only the new information. Could I get some advice on how to do this? My HttpAsyncTask is below, if that helps - I'm thinking I might need an if/else clause in the onPostExecute() method that adds all the rows only if the database is getting created for the first time. I thought about trying to put an HttpAsyncTask class in my DatabaseHelper, but that doesn't really make sense.
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String...urls) {
return GET(urls[0]);
}
#Override
protected void onPostExecute(String result) {
try {
JSONObject main = new JSONObject(result);
JSONObject body = main.getJSONObject("body");
JSONArray measuregrps = body.getJSONArray("measuregrps");
// get measurements for date, unit, and value (weight)
for (int i = 0; i < measuregrps.length(); i++) {
JSONObject row = measuregrps.getJSONObject(i);
// a lot of getting & parsing data happens
db.addEntry(new Entry(date, weight, null, null));
//adds all the lines every time this is run, but I only want to add all
//the lines once and then add new rows one by one from there
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public static String GET(String url) {
InputStream is = null;
String result = "";
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse httpResponse = client.execute(get);
is = httpResponse.getEntity().getContent();
if (is != null)
result = convertInputStream(is);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("input stream", e.getLocalizedMessage());
}
return result;
}
private static String convertInputStream(InputStream is) throws IOException {
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = "";
while((line = reader.readLine()) != null)
builder.append(line);
is.close();
return builder.toString();
}
Your implementation totally depends on the project requirements.
If there are continuously changes over the server, the right way to implement the synchronization process is:
1.
Implement the sync process, which works totally in background. This sync will be customized to call specific API calls/Service classes which will be required to sync.
2.
Server will prompt the mobile client for the data change.
3.
To get server updates, A continuously running service/Sync at some predefined intervals will be run and checks for the updates or implements the GCM.
Sync Adapter would be the best for the sync services.
Ohh, also don't forget to apply the content provider, as database calls would be concurrent from UI and background both.
Hope it may help to decide.
You have to check there is similar data available in the table if yes update the table and if no insert new data to table

Programmatically edit a Google Spreadsheet

I have a written a program that takes in user input, but now I want to be able to save that input by editing a Google spreadsheet every time a user submits the form. So basically, the Google spreadsheet is constantly being updated.
Can anyone provide a tutorial on how I might be able to achieve this? I'm writing in Java using Eclipse, so which plug-ins would I need?
I have already tried using some of the sample code provided in the Google Spreadsheets API (adding a list row section), but I can't seem to get it to work.
import com.google.gdata.client.spreadsheet.*;
import com.google.gdata.data.spreadsheet.*;
import com.google.gdata.util.*;
import java.io.IOException;
import java.net.*;
import java.util.*;
public class MySpreadsheetIntegration {
public static void main(String[] args)
throws AuthenticationException, MalformedURLException, IOException, ServiceException {
SpreadsheetService service =
new SpreadsheetService("MySpreadsheetIntegration-v1");
// TODO: Authorize the service object for a specific user (see other sections)
// Define the URL to request. This should never change.
URL SPREADSHEET_FEED_URL = new URL(
"https://docs.google.com/spreadsheets/d/1OcDp1IZ4iuvyhndtrZ3OOMHZNSEt7XTaaTrhEkNPnN4/edit#gid=0");
// Make a request to the API and get all spreadsheets.
SpreadsheetFeed feed = service.getFeed(SPREADSHEET_FEED_URL,
SpreadsheetFeed.class);
List<SpreadsheetEntry> spreadsheets = feed.getEntries();
if (spreadsheets.size() == 0) {
// TODO: There were no spreadsheets, act accordingly.
}
// TODO: Choose a spreadsheet more intelligently based on your
// app's needs.
SpreadsheetEntry spreadsheet = spreadsheets.get(0);
System.out.println(spreadsheet.getTitle().getPlainText());
// Get the first worksheet of the first spreadsheet.
// TODO: Choose a worksheet more intelligently based on your
// app's needs.
WorksheetFeed worksheetFeed = service.getFeed(
spreadsheet.getWorksheetFeedUrl(), WorksheetFeed.class);
List<WorksheetEntry> worksheets = worksheetFeed.getEntries();
WorksheetEntry worksheet = worksheets.get(0);
// Fetch the list feed of the worksheet.
URL listFeedUrl = worksheet.getListFeedUrl();
ListFeed listFeed = service.getFeed(listFeedUrl, ListFeed.class);
// Create a local representation of the new row.
ListEntry row = new ListEntry();
row.getCustomElements().setValueLocal("firstname", "Joe");
row.getCustomElements().setValueLocal("lastname", "Smith");
row.getCustomElements().setValueLocal("age", "26");
row.getCustomElements().setValueLocal("height", "176");
// Send the new row to the API for insertion.
row = service.insert(listFeedUrl, row);
}
}
seem to be very late but surely this is going to help others! The problem is in your SPREADSHEET_FEED_URL and authentication of SpreadSheetService instance because the official SpreadSheets Api has not shared detailed explaination regarding that.You need to get an authentication token and set it on SpreadSheetService Instance like below to get it work:
private void getAuthenticationToken(Activity activity, String accountName){
//Scopes used to get access to google docs and spreadsheets present in the drive
String SCOPE1 = "https://spreadsheets.google.com/feeds";
String SCOPE2 = "https://docs.google.com/feeds";
String scope = "oauth2:" + SCOPE1 + " " + SCOPE2;
String authenticationToken = null;
try {
accessToken= GoogleAuthUtil.getToken(activity, accountName, scope);
}
catch (UserRecoverableAuthException exception){
//For first time, user has to give this permission explicitly
Intent recoveryIntent = exception.getIntent();
startActivityForResult(recoveryIntent, RECOVERY_REQUEST_CODE);
}catch (IOException e) {
e.printStackTrace();
} catch (GoogleAuthException e) {
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_REQUEST_CODE){
if(resultCode == RESULT_OK){
if(data != null){
String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
if (accountName != null && !accountName.equals("")){
//To be called only for the first time after the permission is given
getAuthenticationToken(activity, accountName);
}
}else {
Utility.showSnackBar(linearLayout, Constants.INTENT_DATA_NULL);
}
}
}
}
And finally below code to get all spreadsheets in an email account:
public class MySpreadsheetIntegration {
public void getSpreadSheetEntries()
throws AuthenticationException, MalformedURLException, IOException, ServiceException {
SpreadsheetService service =
new SpreadsheetService("MySpreadsheetIntegration-v1");
service = new SpreadsheetService(applicationName);
service .setProtocolVersion(SpreadsheetService.Versions.V3);
service .setAuthSubToken(accessToken);
// Define the URL to request. This should never change.
URL SPREADSHEET_FEED_URL = new URL(
"https://spreadsheets.google.com/feeds/spreadsheets/private/full");
// Make a request to the API and get all spreadsheets.
SpreadsheetFeed feed = service.getFeed(SPREADSHEET_FEED_URL, SpreadsheetFeed.class);
List<SpreadsheetEntry> spreadsheets = feed.getEntries();
// Iterate through all of the spreadsheets returned
for (SpreadsheetEntry spreadsheet : spreadsheets) {
// Print the title of this spreadsheet to the screen
System.out.println(spreadsheet.getTitle().getPlainText());
}
}
}

Categories