Android google translate API - android

I have a problem with receiving translations from Google via translate API. Does somebody know what is wrong? Thanks!
Note:
It has worked fine for some time but maybe 5 months ago it stopped to work.
#Override
public void onClick(View v) {
GoogleAPI.setHttpReferrer("http://code.google.com/p/google-api-translate-java/");
GoogleAPI.setKey("xxx");
try {
tv_answer.setText(Translate.DEFAULT.execute(tv_source.getText().toString(), Language.CZECH, Language.ENGLISH));
} catch (GoogleAPIException e) {
e.printStackTrace();
}
}
Received error:
com.google.api.GoogleAPIException: java.lang.Exception: [google-api-translate-java] Error retrieving translation.

This problem only appears on android when using this api client. I believe this is because this api client is old and/or poorly written.
You can attempt to get the source code from here and fix the problem yourself, or just use the api directly from Java using GET with HttpURLConnection and them parse the JSON.

Google Translate API is a paid service.
Note:
(https://developers.google.com/translate/v2/getting_started)

Related

Why can't I get pushToken by using Huawei Push Kit?

I am using following code snippet, however I still can't get the pushToken.
private void obtainToken() {
// get token
new Thread() {
#Override
public void run() {
try {
String appId = AGConnectServicesConfig.fromContext(MainActivity.this).getString("client/app_id");
pushtoken = HmsInstanceId.getInstance(MainActivity.this).getToken(appId, "HCM");
if(!TextUtils.isEmpty(pushtoken)) {
Log.i(TAG, "get token:" + pushtoken);
}
} catch (Exception e) {
Log.i(TAG,"getToken failed, " + e);
}
}
}.start();
}
Having a log would be perfect but if everything fine in the logs, no exception and result code from HCM is success, then verify the EMUI version of your device.
If your device's EMUI version is earlier than 10.0, the code you have used will return empty push token. In such case, it is necessary to implement a custom service extending HmsMessageService.
In your AndroidManifest.xml add;
<service
android:name=".CustomPushService"
android:exported="false">
<intent-filter>
<action android:name="com.huawei.push.action.MESSAGING_EVENT" />
</intent-filter>
</service>
Then create following class;
public class CustomPushService extends HmsMessageService {
private static final String TAG = "PushTokenLog";
#Override
public void onNewToken(String token) {
super.onNewToken(token);
Log.i(TAG, "receive token:" + token);
}
}
Last but not least, make sure your device is Huawei :) Most of the features of HMS Core relies on EMUI. Without EMUI, functionality of the functions is not guaranteed for now.
Below is a nice reference to see HMS Core - EMUI relation.
https://developer.huawei.com/consumer/en/doc/development/HMS-Guides/emui_version_dependent_features
Update as per the comment of question owner
The return code 907135000 means that your SDK configurations are not correct. Take your time to check following points;
Check whether the app_id and package_name parameters in the agconnect-services.json file are correct. The app_id and package name should match the app created on AGC. Also, consider re-downloading corresponding agconnect-service.json
Check whether the certificate signature is configured in the build.gradle file.
The fault may be caused by the cache of HMS Core (APK). Uninstall and then reinstall HMS Core (APK), disconnect and reconnect the phone with the Internet, and start the app again.
You can get a pushToken on the premise that the preparation work has been done, especially enabling the push service and setting up the fingerprint. For details, refer to the following link: App development
You can view the logcat with filter "hmssdk" after checking. If there is an exception, you can see the error code, and then you can refer to the document for how to solve the problem. Here is the link:
Show the log if possible so that we can solve the problem together.
For more details, you can refer to the document about how to get pushToken.
If the EMUI version is 10.0 or later on a Huawei device, a token will be returned through the getToken method. If the getToken method fails to be called, HUAWEI Push Kit automatically caches the token request and calls the method again. A token will then be returned through the onNewToken method.
If the EMUI version on a Huawei device is earlier than 10.0 and no token is returned using the getToken method, a token will be returned using the onNewToken method.
Similar issue, getting an error:
GET token failed, com.huawei.hms.common.ApiException: 907122036: no right
Solution:
AppGallery Connect
Project
Push Kit
Enable
Done
I got the same error. I fixed the problem. If you work in more than one medium, check the flavor files. Make sure it's correct.
Multiple Flavors Document :
https://developer.huawei.com/consumer/en/doc/development/AppGallery-connect-Guides/agc-config-flavor
Maybe a little bit late, but still.
getToken fails because AGConnectServicesConfig.getString("client/app_id"); returns null, which you pass into getToken method.
In the recent Huawei Services version, to get appId you should ask for /client/app_id, not client/app_id string like this:
String appId = AGConnectServicesConfig.fromContext(MainActivity.this).getString("/client/app_id");
Everything else stays the same. But I would recommend writing if statement to check if appId is null and track that. That will save you time if Huawei decides to change that value again.

Google Appengine Multiple Versions Android App

I'm trying to test out an updated appengine version without ruining my live version. The current code is:
themeendpoint.Builder endpointBuilder = new themeendpoint.Builder(
AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(),
new HttpRequestInitializer() {
#Override
public void initialize(HttpRequest httpRequest) throws IOException {
}
}
);
themeendpoint endpoint = CloudEndpointUtils.updateBuilder(
endpointBuilder).build();
Which works fine for the default version. I'm trying to access the "dev" version that I uploaded. I understand that normally you are supposed to add the version at the beginning like "dev.project.appspot" but I'm struggling to get this into the Android App. I tried adding the following:
endpointBuilder.setRootUrl("https://dev.project.appspot.com/_ah/api/");
Just before creating the endpoint. When running the app I get the following error:
java.io.IOException: Hostname 'dev.project.appspot.com' was not verified
I'm at a loss as to how to access my non-default version.
Turns out I almost had it right. Per this link I need to use "-dot-" notation for HTTPS. Plus, I was missing a small piece of the URL. Full line of code is:
endpointBuilder.setRootUrl("https://dev-dot-project.appspot.com/_ah/api/");

Unexpected response code 403 for https://www.googleapis.com/games/v1/players/1123xxxxxx11712506520 and other play-services errors

I'm trying to make games API work, with reference to https://github.com/playgameservices/android-samples/blob/master/BaseGameUtils/src/com/google/example/games/basegameutils/BaseGameActivity.java as sample code.
Mine is quite similar, basically I'm trying to connect a game client and receive a negative answer. When trying to manage it with startResolutionForResult() this is what I got:
E/Volley(15638): [1492] il.a: Unexpected response code 403 for https://www.googleapis.com/games/v1/players/112370814111712506xxx
E/Volley(15638): [1492] il.a: Unexpected response code 403 for https://www.googleapis.com/games/v1/players/112370814111712506xxx
E/SignInIntentService(15638): Access Not Configured
[...]
E/LoadSelfFragment(15748): Unable to sign in - application does not have a registered client ID
The last message, "application does not have a registered client ID" made me think to this question...But I don't think my issue is related to app id / client ID as I got it working with same API keys on another machine. I'm pretty sure of SHA1 correctness, too, derived from current machine's debug.keystore.
The issue seems to be related to test address I'm using, the strange thing is that I don't receive always the same reply: using same keys and settings, I sometimes got:
E/SignInIntentService(15638): Access Not Configured
or even:
E/SignInIntentService(15638): Unable to load player
I'm using startResolutionForResult() inside OnConnectionFailedListener, it's showing the log-in screen briefly, but then it crashes with reported errors.
Another strange thing is that onActivityResult() is called, and result code is 10004
A last thing I can't understand is why, after an unsuccessful sign-in, the method onConnectionFailed() is called over and over, looping my app. Relevant code is:
public void initClient() {
GamesClient.Builder gcBuilder = new GamesClient.Builder(this, cb, cf);
gcBuilder.setGravityForPopups(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
//gcBuilder.setScopes(mScopes);
mGamelient = gcBuilder.create();
mSchiacciameleView.setGameClient(gcBuilder.create());
}
OnConnectionFailedListener cf = new OnConnectionFailedListener() {
public void onConnectionFailed(ConnectionResult arg0) {
Log.e("Verme", "CONN FAIL:" + arg0.getErrorCode());
if (arg0.hasResolution()){
PendingIntent pendingIntent = arg0.getResolution();
//startResolutionForResult(SchiacciaMeleGame.this, 66);
try {
arg0.startResolutionForResult(me, ConnectionResult.SIGN_IN_REQUIRED) ;
} catch (SendIntentException e) {
Log.e("Verme", "Err in resolution", e);
}
}else{
Log.e("Verme", "NO RESOLUTION");
}
}
};
I've been messing with these libraries for two days. Frankly, I don't like the way Google is managing this; documentation is still incomplete and run-time behaviour seems a bit inconsistent (the exact same code is working on another machine, SHA1 is correct on both). Maybe it's my fault?
Thank you for replies
In Step 3. Generate an OAuth 2.0 client ID it specifically gives a warning as follows:
Warning: Do not open the Google APIs Console directly and manually
add your Client IDs on that page. Doing so might cause errors when
you send requests to the game services.
So my experience was that you need to follow the guide religiously: Setting Up Google Play Game Services with the Google Play Developer Console

App engine connected Android app

Problem with the new App engine connected android application projects for the google eclipse plugin? This is the "Big Daddy" sample shown at goolge i/o 2011. My sample project compiles and the android app appears to work fine and registers with the server. However when I send a message from the server I get the following: Having issue with sample project. Android appears to work fine and registers with the server and the c2dm server, however I cannot send a message.
Also of note on the server is a c2dmconfig datastore object. It has fields for authToken and c2dmUrl. The authToken has a token, however the c2dmUrl is NULL. I suspect this is where my problem lies, but not sure how to fix it.
Thanks Patrick
I found this question by wondering the same thing, if the c2dmUrl being null is a problem. It would seem that this is not an issue though. If you look at the C2DMConfig (the entity that you are referencing), there is a function called "getC2DMUrl". Here it is:
public String getC2DMUrl() {
if (c2dmUrl == null) {
return DATAMESSAGING_SEND_ENDPOINT;
} else {
return c2dmUrl;
}
So null is a supported value for this. If a specific URL isn't specified, it simply returns it to the default.

Why is Android Geocoder throwing a "Service not Available" exception?

The app uses the Geocoder object. It works fine on my stock Froyo Nexus One. But then I run the exact same app on a different device (an Advent Vega 10" tablet also running Froyo) and I get this exception: Service not Available. The method I'm using is getFromLocationName(), I'm building against the Android 1.6 Google API.
I'm aware of an issue where this exception is thrown on the emulator, but I suspect this is different. Why would it be thrown on one device running Froyo but not another?
The app is a location app, and as the tablet has no GPS or mobile network, in a scenario where the Wi-Fi connection doesn't provide a location, the user must manually specify it, so not being able to use the Geocoder object is bad news.
I could add a way for the user to select the location on a map, but it's not ideal. Possibly I could use the Google Maps API directly, but I'm keen to understand the nature of the issue first as would be nice to have an easier solution.
Hopefully in a future release Android will include an OS-level "default location" for non-Geocoder devices, so location-aware apps work out of the box on devices like Google TV.
I asked Google's Reto Meier to confirm my theory was correct and he said "Correct. The Geocoder is part of the Google API add-on that isn't part of the AOSP."
So any device that doesn't come with the Play Store, GMail apps etc… will also be missing the Geocoder back-end.
There seems to be another possible workaround for this problem, which is unfortunately marked as a duplicate question, and therefore might be missed. Essentially, a reboot of the device clears up the problem. Note I called it a "workaround" and not a "solution". :(
For those who searching alternative, Hopefully, my answer in another post is useful.
You can use Google Geocoding API when caught error in geocoding.
For more code => Get current location using json
Some devices do not have suport for Geocoder, so what you need to do is create your own geocoder.
Basicaly you need create a async task to request google for the address and treat the json response.
Using aquery, i do something like this:
public void asyncJson(String address){
address = address.replace(" ", "+");
String url = "http://maps.googleapis.com/maps/api/geocode/json?address="+ address +"&sensor=true";
aq.ajax(url, JSONObject.class, new AjaxCallback<JSONObject>() {
#Override
public void callback(String url, JSONObject json, AjaxStatus status) {
if(json != null){
//here you work with the response json
JSONArray results = json.getJSONArray("results");
Toast.makeText(context, results.getJSONObject(1).getString("formatted_address"));
}else{
//ajax error, show error code
Toast.makeText(aq.getContext(), "Error:" + status.getCode(), Toast.LENGTH_LONG).show();
}
}
});
}
After wasting several hours, I got a simplest solution.
I Just restarted my device, and it started working.
It seems, the problem is due to some OS level caching problem. Hope it will also work for your..
I had the same issue. I used the following function.
Note:
Use context of your Activity and don't use getApplicationContext() to the following function
public static Address getLocalityFrmGeoCoder(Context context, Location mLocation) {
try {
if(mLocation!=null){
Geocoder gCoder = new Geocoder(context, Locale.getDefault());
List<Address> address = gCoder.getFromLocation(mLocation.getLatitude(), mLocation.getLongitude(), 1);
if (address.size() > 0) {
return address.get(0);
}
}
} catch (Exception e) {
Log.d("GEOCODER", "GEOCODER EXCEPTION");
e.printStackTrace();
}
return null;
}

Categories

Resources