Google App Engine Java and Android Getting Started - java

I've been struggling to get the example running from below:
https://developers.google.com/eclipse/docs/getting_started
The first problem I had was didn't have installed 'Google Cloud Messaging for Android Library' in the Android SDK (obvious I know).
But now I have an issue with the auto-generated code in two files in the Android project:
GCMIntentService.java and RegisterActivity.java
The errors are:
The method getDeviceInfo(String) is undefined for the type Deviceinfoendpoint GCMIntentService.java
The method listMessages() is undefined for the type MessageEndpoint RegisterActivity.java
The method insertDeviceInfo(DeviceInfo) is undefined for the type Deviceinfoendpoint GCMIntentService.java
The method removeDeviceInfo(String) is undefined for the type Deviceinfoendpoint GCMIntentService.java
I'm using Java SDK v1.7.0_15 on Ubuntu but I also tried on Windows 7 with Java SDK v1.6 and had the same issue. Latest Android Platform 4.2.2 and Google App Engine 1.7.7. Eclipse is Juno Service Release 2.
The problem looks like they are doing some casting wrong, because there is a method getDeviceInfo for inner class DeviceInfoEndpoint inside Deviceinfoendpoint (different capatilisations).
I could try and fix it, but just wondering if I have something wrong in my setup for this to be happening?
Any help would be appreciated.

In your GCMIntentService.java class, add .deviceInfoEndpoint() after the endpoint object in the lines with errors as shown below:
DeviceInfo existingInfo = endpoint.getDeviceInfo(registration)
DeviceInfo existingInfo = endpoint.deviceInfoEndpoint().getDeviceInfo(registration)
In RegisterActivity.java change the line
messageEndpoint.listMessages().setLimit(5).execute();
to
messageEndpoint.messageEndpoint().listMessages().setLimit(5).execute();

I would make sure you are using the same version of GCM APIs as you have JARs for. There have been quite a few revisions.
I am using the following code with gcm-server.jar, listed at 19718 bytes.
The code I successfully use to send GCM messages to a device is:
public void sendMessage() {
String notificationToken = mobileDevice.getPushNotificationCode();
String deviceType = mobileDevice.getDeviceType();
Sender sender = new Sender(BROWSER_API_KEY);
Message message = new Message.Builder().addData("message", "blah blah").build();
String device = "<the key for the device you are sending to goes here>";
try {
System.out.println("Sending message...");
Result result = sender.send(message, device, 5);
System.out.println("Done sending message");
if (result.getMessageId() != null) {
System.out.println("Got message ID: " + result.getMessageId());
System.out.println("Got error code name: " + result.getErrorCodeName());
System.out.println("result: " + result);
String canonicalRegId = result.getCanonicalRegistrationId();
if (canonicalRegId != null) {
// Database has more than one record for this device.
// Replace all of this device's records with this new id
System.out.println("Got new canonical reg id: " + canonicalRegId);
}
} else {
String error = result.getErrorCodeName();
if (error.equals(com.google.android.gcm.server.Constants.ERROR_NOT_REGISTERED)) {
// application has been removed from device - unregister from database
System.out.println("Got error: " + error);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}

Related

error: cannot find symbol method setHttpProxy(ProxyInfo) problem when try to make toyVpn sample project in androidStudio

i downloaded a sample project from https://developer.android.com/guide/topics/connectivity/vpn under the title ToyVpn and i imported into android studio as a project and got this error:
cannot find symbol method setHttpProxy(ProxyInfo) and Cannot resolve method 'setHttpProxy(android.net.ProxyInfo)
// Create a new interface using the builder and save the parameters.
final ParcelFileDescriptor vpnInterface;
for (String packageName : mPackages) {
try {
if (mAllow) {
builder.addAllowedApplication(packageName);
} else {
builder.addDisallowedApplication(packageName);
}
} catch (PackageManager.NameNotFoundException e){
Log.w(getTag(), "Package not available: " + packageName, e);
}
}
builder.setSession(mServerName).setConfigureIntent(mConfigureIntent);
if (!TextUtils.isEmpty(mProxyHostName)) {
builder.setHttpProxy(ProxyInfo.buildDirectProxy(mProxyHostName, mProxyHostPort));
}
synchronized (mService) {
vpnInterface = builder.establish();
if (mOnEstablishListener != null) {
mOnEstablishListener.onEstablish(vpnInterface);
}
}
Log.i(getTag(), "New interface: " + vpnInterface + " (" + parameters + ")");
return vpnInterface;
}
If you check the javadocs for the VpnService.Builder class, you will see that the setHttpProxy method is added in API level 29.
The compilation error that you are getting implies that you are compiling the ToyVPN sample against an older Android API level.
You need to get hold of the SDK for Android 10 or later.

How to use Google Translate API v2 with Android

I'm trying to make an Android translator application using Google Translation Api ("google-api-services-translate-v2-rev48.1.22.0.jar).
I managed to get a valid key and I've tested it from a simple Java Project and everything works perfect.
But, when I try to use the same code in an Android Application, nothing works.
This is the code from android:
Translate translator = new Translate.Builder (new NetHttpTransport(), GsonFactory.getDefaultInstance(), null)
.setApplicationName("MyAppName")
.build();
try {
TranslationsListResponse response = getListOfParameters(fromLanguage, toLanguage, textToTranslate).execute();
StringBuffer sb = new StringBuffer();
for (TranslationsResource tr : response.getTranslations()) {
sb.append (tr.getTranslatedText() + " ");
}
return sb.toString();
}
catch (IOException e) {
Log.e("ERROR", "Got error while trying to translate");
}
private Translate.Translations.List getListOfParameters (String fromLanguage, String toLanguage, String textToTranslate) throws IOException {
Translate.Translations.List list = translator.new Translations().list (Arrays.asList(textToTranslate), toLanguage.toUpperCase());
list.setKey (TranslatorManager.TRANSLATION_GOOGLE_API_KEY);
list.setSource (fromLanguage.toUpperCase());
return list;
}
I don't know for sure where the problem is. The only thing I get when trying to translate is:
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
I/System.out: KnoxVpnUidStorageknoxVpnSupported API value returned is false
In android, I've tried withcom.google.api.client.http.javanet.NetHttpTransport() and AndroidHttp.newCompatibleTransport().
In my initial java project, I've used GoogleNetHttpTransport.newTrustedTransport(), but when using it in Android, got me some exceptions:
java.security.KeyStoreException: java.security.NoSuchAlgorithmException: KeyStore JKS implementation not found
The solution requires changing the HTTP Transport used, as Nick writes. The two solutions proposed in the linked thread “[stackoverflow.com/a/39285052/322738 – Rafael Steil][1]” are to some extent equivalent and would work similarly under certain conditions.
The first reply recommends the usage of HTTP_TRANSPORT = AndroidHttp.newCompatibleTransport();
whereas the second one: HTTP_TRANSPORT = new com.google.api.client.http.javanet.NetHttpTransport();
The [documentation][2] for Class AndroidHttp, in the last paragraph “Method Detail” states that from Android version Gingerbread on, calling “new com.google.api.client.http.javanet.NetHttpTransport();” is recommended.
Method newCompatibleTransport() of the AndroidHttp class returns a new thread-safe HTTP transport instance that is compatible with Android SDKs prior to Gingerbread.

Error in using usb4java

followed the instruction as stated here . Added the properties file in my root project and libraries on the project class path. When i run the project, it returns.
Exception in thread "main" javax.usb.UsbPlatformException: Class org.usb4java.javax.Services does not have the needed constructor
at javax.usb.UsbHostManager.initialize(UsbHostManager.java:46)
at javax.usb.UsbHostManager.getUsbServices(UsbHostManager.java:24)
at usbfinderdemo.UsbFinderDemo.main(UsbFinderDemo.java:30)
Don't know what might be wrong. Thinking i might not be using the right .jar file of usb4java, but i'm not certain yet as the code does not show any error at all.
Code Snippet
UsbServices services = UsbHostManager.getUsbServices();//the line that throws the error.
UsbHub rootHub = services.getRootUsbHub();
List<UsbDevice> devices = rootHub.getAttachedUsbDevices();
if (devices.size() > 0) {
System.out.println("USB devices found.");
} else {
System.out.println("No USB devices found.");
}
for (UsbDevice device : devices) {
System.out.println("\tProduct String " + device.getProductString());
System.out.println("\tManufacturer String " + device.getManufacturerString());
System.out.println("\tSerial Number " + device.getSerialNumberString());
}

Google places autocomplete don't work in my emulator or VMware

I have exactly the same problem as
Autocomplete textview google places api
But the fixes suggested to him don't fix the problem with my case.
I uses the exact same code. But it does not work.
tanks for the api tip
i debuged the problem and saw i am getting a respond of zero_results
Any suggestion?
String input = "";
try {
input = "input=" + URLEncoder.encode(place[0], "utf-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
// place type to be searched
String types = "types=geocode";
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = input + "&" + types + "&" + sensor + "&" + key;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/place/autocomplete/json?input="
+ output + "?" + parameters;
You problem is you API key configuration. Make sure you are creating an API key in "Public API access" section.
You can find how to get the finger print in this post:
How to obtain Signing certificate fingerprint (SHA1) for OAuth 2.0 on Android?
Then in google console register you API key. Remember add to the final you name package declared in your Android Manifest.
finger print example:
F7:DB:FF:EB:6E:AD:C1:D6:84:05:1D:BA:F7:94:0D:E4:1F:2E:3C:8C;cl.hcarrasco.tm
Enable Google Places API:
Remember too do this:
I hope this can help you.

Java - Create domain in Amazon SimpleDB

I'm working with Amazon SimpleDB and attempting the creation of a DB using the following tutorial . Basically it throws an error i.e. Error occured: java.lang.String cannot be cast to org.apache.http.HttpHost. The full stacktrace is as below:
Error occured: java.lang.String cannot be cast to org.apache.http.HttpHost
java.lang.ClassCastException: java.lang.String cannot be cast to org.apache.http.HttpHost
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:416)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:805)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:784)
at com.xerox.amazonws.common.AWSQueryConnection.makeRequest(AWSQueryConnection.java:474)
at com.xerox.amazonws.sdb.SimpleDB.makeRequestInt(SimpleDB.java:231)
at com.xerox.amazonws.sdb.SimpleDB.createDomain(SimpleDB.java:155)
at com.amazonsimpledb.SDBexample1.main(SDBexample1.java:19)
My code is as below (note i have substituted the AWS access id and secret key with the actual values):
public static void main(String[] args) {
String awsAccessId = "My aws access id";
String awsSecretKey = "my aws secret key";
SimpleDB sdb = new SimpleDB(awsAccessId, awsSecretKey, true);
try {
Domain domain = sdb.createDomain("cars");
System.out.println(domain);
} catch (com.xerox.amazonws.sdb.SDBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Any ideas as to why the above mentioned error is occurs.
I appreciate any assistance.
It seems you are using the Typica client library, which is pretty much unmaintained since mid 2011, see e.g. the rare commmits and the steady growing unresolved issues, where the latest one appears to be exactly yours in fact, see ClassCastException using Apache HttpClient 4.2:
According to the reporter, things appear to be functional once we downgrade back to Apache HttpClient 4.1, so that might be a temporary workaround eventually.
Either way I highly recommend to switch to the official AWS SDK for Java (or one of the other language SDKs), which isn't only supported and maintained on a regular fashion, but also closely tracks all AWS API changes (admittedly this isn't that critical for Amazon SimpleDB, which is basically frozen technology wise, but you'll have a much easier time using the plethora of AWS Products & Services later on).
In addition you could benefit from the AWS Toolkit for Eclipse in case you are using that IDE.
The SDK includes a couple of samples (also available via the Eclipse Toolkit wizard), amongst those one for SimpleDB - here's a condensed code excerpt regarding your example:
BasicAWSCredentials basicAWSCredentials = new BasicAWSCredentials(
awsAccessId, awsSecretKey);
AmazonSimpleDB sdb = new AmazonSimpleDBClient(basicAWSCredentials);
Region usWest2 = Region.getRegion(Regions.US_WEST_2);
sdb.setRegion(usWest2);
try {
// Create a domain
String myDomain = "MyStore";
System.out.println("Creating domain called " + myDomain + ".\n");
sdb.createDomain(new CreateDomainRequest(myDomain));
// ...
// Delete a domain
System.out.println("Deleting " + myDomain + " domain.\n");
sdb.deleteDomain(new DeleteDomainRequest(myDomain));
} catch (AmazonServiceException ase) {
// ...
} catch (AmazonClientException ace) {
// ...
}
Please try to create instance of SimpleDB with server and port and let me know if it works.
public SimpleDB objSimpleDB = null;
private String awsAccessKeyId = "access key";
private String awsSecretAccessKey = "secret key";
private boolean isSecure= true;
private String server = "sdb.amazonaws.com";
private int port=443;
try{
SimpleDB objSimpleDB = new SimpleDB(awsAccessKeyId, awsSecretAccessKey, isSecure, server, port);
Domain domain = objSimpleDB .createDomain("cars");
} catch (com.xerox.amazonws.sdb.SDBException e) {
//handle error
}

Categories

Resources