How to send image in REST API android - android

Hi i am pretty new in android and i am building an App which take picture from camera and send this image to REST API.
I have created REST API but i get stuck how to pass image to REST API.I am using POST method in REST API but i don't know which media type i will pass in #Consumes annotation.
Is there any media type for image like there are other media types like (application/json, application/xml, etc).
Here is Code for REST API.
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.sun.jersey.core.header.FormDataContentDisposition;
import com.sun.jersey.multipart.FormDataParam;
#Path("/files")
public class JerseyFileUpload {
private static final String SERVER_UPLOAD_LOCATION_FOLDER = "/home/hassan/Downloads/";
/**
* Upload a File
*/
#POST
#Path("/upload")
#Consumes()
#Produces(MediaType.APPLICATION_JSON)
public ImageUrl responseMsg(
#FormDataParam("file") InputStream fileInputStream,
#FormDataParam("file") FormDataContentDisposition contentDispositionHeader) {
String filePath = SERVER_UPLOAD_LOCATION_FOLDER + contentDispositionHeader.getFileName();
// save the file to the server
saveFile(fileInputStream, filePath);
String output =filePath;
CompareImage cmp = new CompareImage();
String id=cmp.get_image_comparison(output);
// String [] arr = id.split(",");
// String f_id = arr[0];
ImageUrl img = new ImageUrl(output,id);
return img;
//return Response.status(200).entity(output).build();
}
// save uploaded file to a defined location on the server
private void saveFile(InputStream uploadedInputStream,
String serverLocation) {
try {
OutputStream outpuStream = new FileOutputStream(new File(serverLocation));
int read = 0;
byte[] bytes = new byte[1024];
outpuStream = new FileOutputStream(new File(serverLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
outpuStream.write(bytes, 0, read);
}
outpuStream.flush();
outpuStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Which media type should i use in #Consumes() for image.
Thanks in advance.

you can use RetroLet1.5
In your build.gradle
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
In your application's build.gradle
dependencies {
implementation 'com.github.Collabalist:RetroLet:1.5'
}

Related

Dictionary app using Oxford Dictionary API

I am trying to make a dictionary application using Oxford Dictionary api. There is something wrong with my code JSON. Can anyone tell me how do I extract only the definition of the searched word, rather getting the whole JSON file
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class MainActivity extends AppCompatActivity {
private static final String APP_ID= "59028fc6";
private static final String API_KEY = "ad3e310307d7b2f8bf474c45e1efd01f";
private static final String TAG = MainActivity.class.getSimpleName();
private OkHttpClient okHttpClient;
private EditText textInput;
private Button submitButton;
private TextView definitionView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initialize ok http
okHttpClient = new OkHttpClient();
textInput = findViewById(R.id.textInput);
submitButton = findViewById(R.id.submitButton);
definitionView = findViewById(R.id.textMeaning);
submitButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
findMeaningOfEnteredWord();
}
});
}
private void findMeaningOfEnteredWord() {
String word = textInput.getText().toString();
if (word.isEmpty()) {
Toast.makeText(this, "Nothing entered", Toast.LENGTH_SHORT).show();
return;
}
// create url from the word
String lowerCaseWord = word.toLowerCase();
String httpRequestUrl = "https://od-api.oxforddictionaries.com:443/api/v1/entries/en/" + lowerCaseWord;
// make request with REST url
new RequestAsyncTask().execute(httpRequestUrl);
}
private class RequestAsyncTask extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
String requestUrl = params[0];
Request request = new Request.Builder()
.url(requestUrl)
.addHeader("Accept", "application/json")
.addHeader("app_id", APP_ID)
.addHeader("app_key", API_KEY)
.build();
Response response = null;
try {
response = okHttpClient.newCall(request).execute();
return response.body().string();
} catch (IOException ex) {
Log.e(TAG, "caught error: " + ex.getMessage());
}
return "";
}
#Override
protected void onPostExecute(String result) {
try {
JSONObject responseAsJson = new JSONObject(result);
JSONArray results = responseAsJson.getJSONArray("results");
if (results.length() > 0) { // valid definitions were found
String lexicalEntries = results.getJSONObject(0).getString("lexicalEntries");
definitionView.setText(lexicalEntries);
}
Log.d(TAG, " " + responseAsJson.toString());
} catch (Exception ex) {
Log.d(TAG, "exception during json parsing: " + ex.getMessage());
}
}
}
}
JSON:
{"id":"aeroplane",
"language":"en",
"lexicalEntries": [
{
"entries": [{"etymologies":["late 19th century: from French aéroplane, from aéro- ‘air’ + Greek -planos ‘wandering’"],
"grammaticalFeatures":[{"text":"Singular","type":"Number"}],
"homographNumber":"000",
"senses":[{"crossReferenceMarkers":["North American term airplane"],
"crossReferences":[{"id":"airplane","text":"airplane","type":"see also"}],
"definitions":["a powered flying vehicle with fixed wings and a weight greater than that of the air it displaces."],
"domains":["Aviation"],
"id":"m_en_gbus0013220.005",
"regions":["British"],
"short_definitions":["powered flying vehicle with fixed wings"],
"thesaurusLinks":[{"entry_id":"plane","sense_id":"t_en_gb0011151.001"}]}]}],"language":"en","lexicalCategory":"Noun","pronunciations":[{"audioFile":"http:\/\/audio.oxforddictionaries.com\/en\/mp3\/aeroplane_gb_2.mp3","dialects":["British English"],"phoneticNotation":"IPA","phoneticSpelling":"ˈɛːrəpleɪn"}],"text":"aeroplane"}],
"type":"headword","word":"aeroplane"
}
Modify these lines :
String lexicalEntries = results.getJSONObject(0).getString("lexicalEntries");
definitionView.setText(lexicalEntries);
to :
String definition = results.getJSONObject(0).getString("lexicalEntries")
.getJSONArray("entries").getJSONObject(0).getJSONArray("senses")
.getJSONObject(0).getJSONArray("definitions").getString(0);
definitionView.setText(definition);
Of course you may need to modify your UI based on the number of definitions a word has.
Also, you should probably consider using POJOs instead of directly dealing with the JSON response.
I'd recommend Jackson or GSON for doing this.
String definitions=results.getJSONArray("lexicalEntries")
.getJSONObject(0)
.getJSONArray("entries")
.getJSONObject(0)
.getJSONArray("senses")
.getJSONArray("definitions")
.get(0)
So , The thing is , There are a lot of gaps in the JSON for different words .
Which means a word may have an array of "synonyms" but others don't , So in your code you are trying to reach something that doesn't actually exist (a NULL value) which is likely to throw an exception every time you search for a word that the JSON returned doesn't match the JSON you are expecting , Because there are missing (NULL) values .
The app I made using oxford dictionary required a lot of work just to make sure there is no thrown exception .
I used retrofit with moshi converter factory , And then Do the following :
1-In your custom classes , Make sure you annotate every data member with
#Json and provide the name of the keys in the JSON of oxford
2-make sure that every declared type is nullable , including both List and the type inside of it
You'll then be able to get the result , And Now comes the part where you handle evey call that may be null
I know this is a bit old question , But It happened that I struggled with this api once , So I hope this may help someone :)

Problems building Google Drive API File Upload

I am trying to build an android app that'll allow me to upload files to Google Drive upon requirement of the user. But, I can't find a single working example anywhere. There are half baked snippets scattered here and there. Some of them are able to connect through OAuth, others are able to create an empty file or folder, but nowhere I can find an app that saves the tokens, and uploads the files seamlessly. I am just clueless as to how to implement the functionality as no books or videos are available, google's own samples don't work for me. I'm struggling to make the code work. Please help someone. Thanks.
I always use the class below to create a Google drive service.
First you need to have these dependencies on your pom file :
<dependency>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client</artifactId>
<version>1.23.0</version>
</dependency>
<dependency>
<groupId>com.google.oauth-client</groupId>
<artifactId>google-oauth-client-jetty</artifactId>
<version>1.23.0</version>
</dependency>
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-drive</artifactId>
<version>v2-rev282-1.23.0</version>
</dependency>
Then use this class to create instance of the drive api client :
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.List;
/**
*
* #author jalal-sordo
*/
public class GoogleDriveServiceFactory {
private String applicationName;
private JsonFactory jsonFactory;
private HttpTransport googleDriveHttpTransport;
private List<String> googleDriveApiScopes;
private String googleDriveClientSecretFilePath;
private FileDataStoreFactory credentialsStoreFolder;
public GoogleDriveServiceFactory(ApplicationParameters params) {
try {
this.googleDriveClientSecretFilePath = params.getGoogleDriveClientSecretFilePath();
// = new FileInputStream(googleDriveClientSecretFilePath);
applicationName = "someApplicationName";
jsonFactory = JacksonFactory.getDefaultInstance();
googleDriveApiScopes = Arrays.asList(DriveScopes.DRIVE);
googleDriveHttpTransport = GoogleNetHttpTransport.newTrustedTransport();
java.io.File googleDriveCredentialsStore = new java.io.File(params.getGoogleDriveCredentialsFolderPath());
credentialsStoreFolder = new FileDataStoreFactory(googleDriveCredentialsStore);
} catch (IOException | GeneralSecurityException t) {
System.err.println(t.getMessage());
System.exit(1);
}
}
public Credential authorize() throws IOException {
InputStreamReader streamReader = new FileReader(new java.io.File(googleDriveClientSecretFilePath));
GoogleClientSecrets clientSecrets
= GoogleClientSecrets.load(jsonFactory, streamReader);
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow
= new GoogleAuthorizationCodeFlow.Builder(
googleDriveHttpTransport, jsonFactory, clientSecrets, googleDriveApiScopes)
.setDataStoreFactory(credentialsStoreFolder)
.setAccessType("offline")
.build();
Credential credential = new AuthorizationCodeInstalledApp(
flow, new LocalServerReceiver()).authorize("user");
return credential;
}
public Drive getDriveService() throws IOException {
Credential credential = authorize();
return new Drive.Builder(
googleDriveHttpTransport, jsonFactory, credential)
.setApplicationName(applicationName)
.build();
}
}
You will also need this class to provide parameters to the class above :
/**
*
* #author jalal-sordo
*/
public class ApplicationParameters {
private String googleDriveCredentialsFolderPath;
private String googleDriveClientSecretFilePath;
public String getGoogleDriveCredentialsFolderPath() {
return googleDriveCredentialsFolderPath;
}
public void setGoogleDriveCredentialsFolderPath(String googleDriveCredentialsFolderPath) {
this.googleDriveCredentialsFolderPath = googleDriveCredentialsFolderPath;
}
public String getGoogleDriveClientSecretFilePath() {
return googleDriveClientSecretFilePath;
}
public void setGoogleDriveClientSecretFilePath(String googleDriveClientSecretFilePath) {
this.googleDriveClientSecretFilePath = googleDriveClientSecretFilePath;
}
#Override
public String toString() {
return "ApplicationParameters{"
+ "\ngoogleDriveCredentialsFolderPath = " + googleDriveCredentialsFolderPath
+ "\ngoogleDriveClientSecretFilePath = " + googleDriveClientSecretFilePath
+ "\n}";
}
}
And this is how you can create an instance of the GoogleDriveServiceFactory and perform a file upload :
ApplicationParameters params = new ApplicationParameters();
//this is where you specify where you want the credentials to be stored
//after a successful autherization is made from the browser (this code will
//open the authorization consent page on your default browser).
params.setGoogleDriveCredentialsFolderPath("/path/to/credentials/folder");
//this is the path to your client_id that you downloaded from google cloud
//console credentials page.
params.setGoogleDriveClientSecretFilePath("/path/to/client_id.json");
GoogleDriveServiceFactory driveFactory = new GoogleDriveServiceFactory (params);
File fileMetadata = new File();
fileMetadata.setName("photo.jpg");
java.io.File filePath = new java.io.File("files/photo.jpg");
FileContent mediaContent = new FileContent("image/jpeg", filePath);
File file = driveFactory.getDriveService.files().create(fileMetadata, mediaContent)
.setFields("id")
.execute();
System.out.println("File ID: " + file.getId());

Android: Add Digital Signature in xml Document Using DigitalSigner

I am trying to use below Class to append digital signature in xml request while posting the xml on http server. But As Android doesn't allow me to use the javax.xml.crypto.dsig. package I am unable to use it.
PN DigitalSigner is the 3rd party Class that they want us to use to sign the xml So my question is Is there any other way to sign the Xml Request without using javax.xml.crypto.dsig. if yes then how..?
thanks in advance
Here is the Class:
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.security.KeyStore;
import java.security.Security;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.xml.crypto.dsig.CanonicalizationMethod;
import javax.xml.crypto.dsig.DigestMethod;
import javax.xml.crypto.dsig.Reference;
import javax.xml.crypto.dsig.SignatureMethod;
import javax.xml.crypto.dsig.SignedInfo;
import javax.xml.crypto.dsig.Transform;
import javax.xml.crypto.dsig.XMLSignature;
import javax.xml.crypto.dsig.XMLSignatureFactory;
import javax.xml.crypto.dsig.dom.DOMSignContext;
import javax.xml.crypto.dsig.keyinfo.KeyInfo;
import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory;
import javax.xml.crypto.dsig.keyinfo.X509Data;
import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;
import javax.xml.crypto.dsig.spec.TransformParameterSpec;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
public class DigitalSigner {
private static final String MEC_TYPE = "DOM";
private static final String WHOLE_DOC_URI = "";
private static final String KEY_STORE_TYPE = "PKCS12";
private KeyStore.PrivateKeyEntry keyEntry;
/**
* Constructor
* #param keyStoreFile - Location of .p12 file
* #param keyStorePassword - Password of .p12 file
* #param alias - Alias of the certificate in .p12 file
*/
public DigitalSigner(InputStream keyStoreFile, char[] keyStorePassword, String alias) {
this.keyEntry = getKeyFromKeyStore(keyStoreFile, keyStorePassword, alias);
if (keyEntry == null) {
throw new RuntimeException("Key could not be read for digital signature. Please check value of signature "
+ "alias and signature password, ");
}
}
/**
* Method to digitally sign an XML document.
* #param xmlDocument - Input XML Document.
* #return Signed XML document
*/
public String signXML(String xmlDocument, boolean includeKeyInfo) {
Security.addProvider(new BouncyCastleProvider());
try {
// Parse the input XML
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
Document inputDocument = dbf.newDocumentBuilder().parse(new InputSource(new StringReader(xmlDocument)));
// Sign the input XML's DOM document
Document signedDocument = sign(inputDocument, includeKeyInfo);
// Convert the signedDocument to XML String
StringWriter stringWriter = new StringWriter();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer trans = tf.newTransformer();
trans.transform(new DOMSource(signedDocument), new StreamResult(stringWriter));
return stringWriter.getBuffer().toString();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Error while digitally signing the XML document", e);
}
}
private Document sign(Document xmlDoc, boolean includeKeyInfo) throws Exception {
if (System.getenv("SKIP_DIGITAL_SIGNATURE") != null) {
return xmlDoc;
}
// Creating the XMLSignature factory.
XMLSignatureFactory fac = XMLSignatureFactory.getInstance(MEC_TYPE);
// Creating the reference object, reading the whole document for
// signing.
Reference ref = fac.newReference(WHOLE_DOC_URI, fac.newDigestMethod(DigestMethod.SHA1, null),
Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null,
null);
// Create the SignedInfo.
SignedInfo sInfo = fac.newSignedInfo(
fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null),
fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(ref));
if (keyEntry == null) {
throw new RuntimeException(
"Key could not be read for digital signature.");
}
X509Certificate x509Cert = (X509Certificate) keyEntry.getCertificate();
KeyInfo kInfo = getKeyInfo(x509Cert, fac);
DOMSignContext dsc = new DOMSignContext(this.keyEntry.getPrivateKey(), xmlDoc.getDocumentElement());
XMLSignature signature = fac.newXMLSignature(sInfo, includeKeyInfo ? kInfo : null);
signature.sign(dsc);
Node node = dsc.getParent();
return node.getOwnerDocument();
}
private KeyInfo getKeyInfo(X509Certificate cert, XMLSignatureFactory fac) {
// Create the KeyInfo containing the X509Data.
KeyInfoFactory kif = fac.getKeyInfoFactory();
List x509Content = new ArrayList();
x509Content.add(cert.getSubjectX500Principal().getName());
x509Content.add(cert);
X509Data xd = kif.newX509Data(x509Content);
return kif.newKeyInfo(Collections.singletonList(xd));
}
private KeyStore.PrivateKeyEntry getKeyFromKeyStore(InputStream keyStoreFile, char[] keyStorePassword, String alias) {
// Load the KeyStore and get the signing key and certificate.
InputStream keyFileStream = null;
try {
KeyStore ks = KeyStore.getInstance(KEY_STORE_TYPE);
keyFileStream = keyStoreFile;
ks.load(keyFileStream, keyStorePassword);
KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) ks.getEntry(alias,
new KeyStore.PasswordProtection(keyStorePassword));
return entry;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (keyFileStream != null) {
try {
keyFileStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Try Apache Santuario:
Apache XML Security for Java: This library includes the standard JSR-105 (Java XML Digital Signature) API, a mature DOM-based implementation of both XML Signature and XML Encryption, as well as a more recent StAX-based (streaming) XML Signature and XML Encryption implementation.
So it should be compatible with the Java SE implementation of digital signature, both have been derived from JSR-105. The standalone development implementation has been removed from the Oracle site, unfortunately.

Cannot instantiate the type JsonFactory

I am trying to verify a JWT that I am receiving from Google using GoogleAuthUtil. I am trying to use the code at the bottom of this page. Here is my exact source code:
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.List;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
public class Checker {
private final List mClientIDs;
private final String mAudience;
private final GoogleIdTokenVerifier mVerifier;
private final JsonFactory mJFactory;
private String mProblem = "Verification failed. (Time-out?)";
public Checker(String[] clientIDs, String audience) {
mClientIDs = Arrays.asList(clientIDs);
mAudience = audience;
NetHttpTransport transport = new NetHttpTransport();
mJFactory = new JsonFactory();
mVerifier = new GoogleIdTokenVerifier(transport, mJFactory);
}
public GoogleIdToken.Payload check(String tokenString) {
GoogleIdToken.Payload payload = null;
try {
GoogleIdToken token = GoogleIdToken.parse(mJFactory, tokenString);
if (mVerifier.verify(token)) {
GoogleIdToken.Payload tempPayload = token.getPayload();
if (!tempPayload.getAudience().equals(mAudience))
mProblem = "Audience mismatch";
else if (!mClientIDs.contains(tempPayload.getIssuee()))
mProblem = "Client ID mismatch";
else
payload = tempPayload;
}
} catch (GeneralSecurityException e) {
mProblem = "Security issue: " + e.getLocalizedMessage();
} catch (IOException e) {
mProblem = "Network problem: " + e.getLocalizedMessage();
}
return payload;
}
public String problem() {
return mProblem;
}
}
The issue that I'm having is in this line: mJFactory = new JsonFactory();, where I am getting the error Cannot instantiate the type JsonFactory. I'm pretty sure I'm calling the constructor properly and I have all of the libraries imported properly so I don't know why I'm getting this error. If anyone can help me out, that would be great! Let me know if theres any additional info that would be helpful.
EDIT:
Here's the link to the Javadoc
Okay the issue was that I made a small mistake copying the code. JsonFactory is an abstract class, so you need to use the subclass GsonFactory to provide an implementation.

How to read data from a Google spreadsheet for an Android app

I have a public google spreadsheet with some data in tables.
I'm developing an Android app which I want it to read these tables and then make a listview with the fields on the spreadsheet.
Which will be the best way to do that?
You can use the code of James Moore: http://blog.restphone.com/2011/05/very-simple-google-spreadsheet-code.html.
package com.banshee;
import java.io.IOException;
import java.net.URL;
import com.google.gdata.client.spreadsheet.SpreadsheetService;
import com.google.gdata.data.spreadsheet.CustomElementCollection;
import com.google.gdata.data.spreadsheet.ListEntry;
import com.google.gdata.data.spreadsheet.ListFeed;
import com.google.gdata.util.ServiceException;
public class SpreadsheetSucker {
public static void main(String[] args) {
SpreadsheetService service = new SpreadsheetService("com.banshee");
try {
// Notice that the url ends
// with default/public/values.
// That wasn't obvious (at least to me)
// from the documentation.
String urlString = "https://spreadsheets.google.com/feeds/list/0AsaDhyyXNaFSdDJ2VUxtVGVWN1Yza1loU1RPVVU3OFE/default/public/values";
// turn the string into a URL
URL url = new URL(urlString);
// You could substitute a cell feed here in place of
// the list feed
ListFeed feed = service.getFeed(url, ListFeed.class);
for (ListEntry entry : feed.getEntries()) {
CustomElementCollection elements = entry.getCustomElements();
String name = elements.getValue("name");
System.out.println(name);
String number = elements.getValue("Number");
System.out.println(number);
}
} catch (IOException e) {
e.printStackTrace();
} catch (ServiceException e) {
e.printStackTrace();
}
}
}
I have developed a client Lib for SpreadSheet which works on Android. Please try-
http://code.google.com/p/google-spreadsheet-lib-android/
hope it helps.
Cheers,
Prasanta

Categories

Resources