Trying to get place from place picker but it open and closes - android

I am integrating place picker but I have already enable places api but it opens and close immediately.
I have created api key and puted it on manifest file
still it not working.in my logcat it gives me error
2019-03-08 10:31:41.640 2837-2358/? E/Places: Places API for Android does not seem to be enabled for your app. See https://developers.google.com/places/android/signup for more details.
2019-03-08 10:31:41.651 4713-4713/? E/Places: Place Picker closing due to PLACES_API_ACCESS_NOT_CONFIGURED
2019-03-08 10:31:41.775 2837-2358/? E/Places: Places API for Android does not seem to be enabled for your app. See https://developers.google.com/places/android/signup for more details.
2019-03-08 10:31:41.776 2837-2358/? E/AsyncOperation: serviceID=65, operation=SearchPlaces
OperationException[Status{statusCode=PLACES_API_ACCESS_NOT_CONFIGURED, resolution=null}]
here is my code
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="key" />
#SuppressLint("MissingPermission")
private void showPlacePicker() {
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
try {
startActivityForResult(builder.build(NewOrderActivity.this), PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
Place place = PlacePicker.getPlace(data, NewOrderActivity.this);
edt_pickup_address.setText(place.getAddress());
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List<Address> listAddresses = geocoder.getFromLocation(place.getLatLng().latitude, place.getLatLng().longitude, 1);
if (null != listAddresses && listAddresses.size() > 0) {
/* post_area = listAddresses.get(0).getSubLocality();
post_city = listAddresses.get(0).getSubAdminArea();
post_state = listAddresses.get(0).getAdminArea();*/
}
} catch (IOException e) {
e.printStackTrace();
}
String place_phone_number = "" + place.getPhoneNumber();
if (!TextUtils.isEmpty(place_phone_number)) {
String[] phone_number = place_phone_number.split(" ");
String s = "";
for (int i = 0; i < phone_number.length; i++) {
if (i != 0) {
s = s + phone_number[i];
}
}
// et_contact_no_add_company.setText(s);
} else {
// et_contact_no_add_company.setText("");
}
if (place.getWebsiteUri() != null) {
// et_website_add_company.setText("" + place.getWebsiteUri());
} else {
// et_website_add_company.setText("");
}
}
}
}

As per Google new update the Place Picker Deprecate and it will not longer available in future, here is official statement
Deprecation notice: Place Picker
Notice: The Place Picker (Android, iOS) is deprecated as of January 29, 2019. This feature will be turned off on July 29, 2019,
and will no longer be available after that date. To continue using the
Place Picker with Places SDK for iOS v.2.7.0 through the deprecation
period, do NOT disable the Places SDK for iOS. Read the migration
guides (Android, iOS) to learn more.
So, the other side u can use the Place Autocomplete
But here is some limitation in new Place API you must enable the Billing account to use the Place Autocomplete.
Reminder: To use the Places API, you must get an API key and you must
enable billing. You can enable billing when you get your API key (see
the Quick guide) or as a separate process (see Usage and Billing).
Alternative solution: get the latLong from place name using Geocoder

Deprecation notice: Google Play Services version of the Places SDK for Android
Please refer this link
https://developers.google.com/places/android-sdk/autocomplete

Related

IBM Watson UnAuthorized

I implemented IBM watson Assistant and it works perfectly fine on android debug. Problem comes when I build a signed apk. It always says Unauthorized. I don't think its the key because its working fine on debug mode. I need some help because the project is live.
What I have tried so far is to change the key in IBM cloud and tried other keys but it raises not found exception of which i think is caused by wrong key. Im I supposed to allow something in IBM cloud for signed apk? or is there a certificate from signed apk that I have to upload in IBM cloud?
Im using IBM watson Assistant v2
private Assistant watsonAssistant;
private Response<SessionResponse> watsonAssistantSession;
private void createServices() {
watsonAssistant = new Assistant("2020-04-01", new IamAuthenticator(getString(R.string.assistant_apikey)));
watsonAssistant.setServiceUrl(getString(R.string.assistant_url));
}
private void sendMessage(){
Thread thread = new Thread(() -> {
try {
if (watsonAssistantSession == null) {
ServiceCall<SessionResponse> call = watsonAssistant.createSession(new CreateSessionOptions.Builder().assistantId(getString(R.string.normal_assistant_id)).build());
watsonAssistantSession = call.execute();
}
MessageInput input = new MessageInput.Builder()
.text(userInput)
.build();
MessageOptions options = new MessageOptions.Builder()
.assistantId(getString(R.string.normal_assistant_id))
.input(input)
.sessionId(watsonAssistantSession.getResult().getSessionId())
.build();
Response<MessageResponse> response = watsonAssistant.message(options).execute();
if (response.getResult().getOutput() != null && !response.getResult().getOutput().getGeneric().isEmpty()) {
List<RuntimeResponseGeneric> responses = response.getResult().getOutput().getGeneric();
for (RuntimeResponseGeneric r : responses) {
switch (r.responseType()) {
case "text":
aiResponse = r.text();
aiConversationList.add(new AIConversation(r.text(), "ai", System.currentTimeMillis()));
break;
default:
Log.e("Error", "Unhandled message type");
}
}
runOnUiThread(() -> {
sendConvoToServer(userInput, aiResponse);
txtWelcomeAI.setVisibility(View.VISIBLE);
aiAdapter.notifyItemInserted(aiConversationList.size() - 1);
userInputTxt.setEnabled(true);
pRecyclerView.scrollToPosition(aiConversationList.size() - 1);
aStatus.setText("online");
});
}
} catch (Exception e) {
e.printStackTrace();
Log.e("IBM_EXCEPTION", e.toString());
aiConversationList.add(new AIConversation("Oops! Something went wrong", "ai", System.currentTimeMillis()));
aiAdapter.notifyItemInserted(aiConversationList.size() - 1);
runOnUiThread(() -> {
pRecyclerView.scrollToPosition(aiConversationList.size() - 1);
aStatus.setText("online");
userInputTxt.setEnabled(true);
});
}
});
thread.start();
}
In case anyone else will have a problem between debug and release apks like the one I had, try to check if you have done obfuscation. If so, then obfuscation is probably a problem. At least it was for me. So, either disable obfuscation from your build.gradle on app level or add some rules in proguard-rules

Android PlaceAutocomplete search result mixup

I followed the google play documentation for implementing autocomplete using "Use an intent to launch the autocomplete activity."
But sometimes the results are showing all mixed up and overlapped.
Below is the code that i am using :
try {
// The autocomplete activity requires Google Play Services to be available. The intent
// builder checks this and throws an exception if it is not the case.
AutocompleteFilter typeFilter = new AutocompleteFilter.Builder()
.setTypeFilter(AutocompleteFilter.TYPE_FILTER_CITIES)
.build();
Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN).setFilter(typeFilter)
.build(MainActivity.this);
startActivityForResult(intent, 111);
} catch (GooglePlayServicesRepairableException e) {
// Indicates that Google Play Services is either not installed or not up to date. Prompt
// the user to correct the issue.
GoogleApiAvailability.getInstance().getErrorDialog(MainActivity.this, e.getConnectionStatusCode(),
0 /* requestCode */).show();
} catch (GooglePlayServicesNotAvailableException e) {
// Indicates that Google Play Services is not available and the problem is not easily
// resolvable.
String message = "Google Play Services is not available: " +
GoogleApiAvailability.getInstance().getErrorString(e.errorCode);
Log.e("", message);
Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
}
Is this a Google Play service SDK problem or code problem?

Google Maps Android -- Map suddenly no longer displayed

I'm working on integrating Google Maps into the app I'm working on and I've had a rather unpleasant time doing it thus far. Regardless, I finally got a SupportMapFragment displaying a map and set a location and zoom level.
Here is the functional bits of my code thus far:
#Override
public void onActivityCreated( Bundle savedInstanceState ) {
super.onActivityCreated( savedInstanceState );
Location location = BundleChecker.getExtraOrThrow( KEY_LOCATION, new Bundle[] { savedInstanceState, getArguments() } );
setLocation( location );
if ( checkGooglePlayServicesStatus() == ConnectionResult.SUCCESS ) {
setMapFragment( new SupportMapFragment() );
getActivity().getSupportFragmentManager().beginTransaction().add( R.id.location_detail_mapFrame, getMapFragment() ).commit();
}
populateAddress();
attachButtonListeners();
Runnable initMap = new Runnable() {
#Override
public void run() {
if ( checkGooglePlayServicesStatus() == ConnectionResult.SUCCESS ) {
try {
GoogleMap map = getMapFragment().getMap();
LatLng latLng = getLocation().getAddress().getLatLng( getActivity() );
CameraUpdate update = CameraUpdateFactory.newLatLngZoom( latLng, DEFAULT_MAP_ZOOM );
map.animateCamera( update );
}
catch (IOException e) {
Log.e( TAG, e.getMessage(), e );
Toast.makeText( getActivity(), "Unable to find location", Toast.LENGTH_SHORT ).show();
}
}
}
};
Handler handler = new Handler();
handler.postDelayed( initMap, 200 );
}
Also, I wrote a simple convenience method to get a LatLng from my Address model that you may criticize as well:
/*
* Convenience method to easily check if there is a valid lat & lng in this address
*/
public boolean hasLatLng() {
return getLatitude() != null && getLongitude() != null;
}
/*
* Convenience method for use with Google Maps API
*/
public LatLng getLatLng( Context context ) throws IOException {
LatLng latLng = null;
if ( hasLatLng() ) {
latLng = new LatLng( getLatitude(), getLongitude() );
}
else {
String locationString = getStreet() + ", " + AddressUtil.makeCityStateZipString( this );
Geocoder geoCoder = new Geocoder( context );
try {
List<android.location.Address> matches = geoCoder.getFromLocationName( locationString, 2 );
if ( matches != null && matches.size() > 0 ) {
double lat = matches.get( 0 ).getLatitude();
double lng = matches.get( 0 ).getLongitude();
latLng = new LatLng( lat, lng );
}
}
catch (IOException e) {
throw new IOException( e );
}
}
return latLng;
}
I'm aware that this code is not ideal and needs to be refactored. This is my first time working with Google Maps so please feel free to offer suggestions as to how I might do that as well. I experienced a lot of problems when trying to use the MapFragment as a in my layout XML, so I'm creating it programmatically.
The heart of the matter:
I was getting some bogus address data from the staging server and this resulted in the Address#getLatLng method returning null which caused an exception when calling CameraUpdateFactory.newLatLngZoom. After I got this exception, I was no longer able to get map data from Google. The map fragment is blank now and messages are displayed in logcat:
05-21 18:11:42.903: I/Google Maps Android API(15747): Failed to contact Google servers. Another attempt will be made when connectivity is established.
05-21 18:11:43.093: E/Google Maps Android API(15747): Failed to load map. Error contacting Google servers. This is probably an authentication issue (but could be due to network errors).
I have created a new api key and replaced the current one in my manifest with no change. The only changes I had made to the above code were to account for a null LatLng and I have since undone those changes in a pointless attempt to get my code back to a functional state.
Additionally, to make things a bit stranger, I built the sample maps project that is included with the Google Play Services Extras and it works perfectly (has a separate API key, btw).
What might I have done wrong here? Am I overlooking something obvious?
This problem is usually derived from a problem in referencing google-play-service library.
Take a look at this blog post I wrote on how to integrate Google Maps in your application, especially the first 3 steps:
Google Maps API V2
another cause of this could be that you haven't configured the Google API Console properly, so I suggest you to take a look at this guide as well:
Google Maps API V2 Key
another reason that may cause this is if you have some kind of problem in your permissions in the manifest file. You can look at the first guide for the needed permissions as well.
Use Something like this:
Update the google play services in the SDK.
Manually uninstall the App from device and restart the device.
i have tried it and its going perfectly bro
Also do one thing get the new api key to edited the new sh1 code from https://code.google.com/apis/console/
you can get your sh1 code from window- preference-android-buid
Making Google maps work is a Googlemare. This worked for me:
-Update Google play services with the Android Manager
-Make a fresh apikey with: Sha1 keystore (Window->preferences->Android->Build) and project package name. Do this at: https://code.google.com/apis/console/
Somebody had changed the package name and was foiling the app!!
Try this before you need anger management therapy thanks to google maps.

How do I connect Android apps with Google Sheets spreadsheets?

I'm trying to do an Android app that needs to work with Google spreadsheet API. I'm new in this, so I'm starting with the version 3 of the api: https://developers.google.com/google-apps/spreadsheets/
I followed all the steps, downloaded all the jar files to lib subfolder in my project folder and then I added to the build path in Eclipse as usual. So although there is no Java example to perform Oauth 2.0, I just tried to declare:
SpreadsheetService service = new SpreadsheetService("v1");
but when I emulate this simple line it gives me an error:
java.lang.NoClassDefFoundError: com.google.gdata.client.spreadsheet.SpreadsheetService
I'm using all the jars included in the documentation and I have the import:
import com.google.gdata.client.spreadsheet.SpreadsheetService;
but I am totally lost. I dont know what else to do just to start, connect to Google APIs and work with the spreadsheets.
Sample code for you without OAuth 2.0. But its recommended to perform OAuth as its good for the security purpose. You also have to add below permissions.
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCOUNT_MANAGER"/>
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Sample Code:-
try {
SpreadsheetEntry spreadsheet;
service = new SpreadsheetService("Spreadsheet");
service.setProtocolVersion(SpreadsheetService.Versions.V3);
service.setUserCredentials("username", "password");//permission required to add in Manifest
URL metafeedUrl = new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full");
feed = service.getFeed(metafeedUrl, SpreadsheetFeed.class);
List<SpreadsheetEntry> spreadsheets = feed.getEntries();
if (spreadsheets.size() > 0) {
spreadsheet = spreadsheets.get(i);//Get your Spreadsheet
}
} catch (Exception e) {
e.printStackTrace();
}
Thank you so so much Scorpion! It works!! I've been trying this for too long.
Ok here is my solution:
I started a new project and included these jars:
gdata-client-1.0
gdata-client-meta-1.0
gdata-core-1.0
gdata-spreadsheet-3.0
gdata-spreadsheet-meta-3.0
guava-13.0.1
and my code:
SpreadsheetService spreadsheet= new SpreadsheetService("v1");
spreadsheet.setProtocolVersion(SpreadsheetService.Versions.V3);
try {
spreadsheet.setUserCredentials("username", "password");
URL metafeedUrl = new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full");
SpreadsheetFeed feed = spreadsheet.getFeed(metafeedUrl, SpreadsheetFeed.class);
List<SpreadsheetEntry> spreadsheets = feed.getEntries();
for (SpreadsheetEntry service : spreadsheets) {
System.out.println(service.getTitle().getPlainText());
}
} catch (AuthenticationException e) {
e.printStackTrace();
}
of course this is executed in a different thread not in the main thread. There is no java documentation for OAuth 2.0 but I will try and if I can't do it I'll ask here.
Again, thank you very much and I hope to help you when I work on this time enough. :)
(Feb 2017) The question (and most answers) are now out-of-date as:
GData APIs are the previous generation of Google APIs. While
not all GData APIs have been deprecated, all modern Google
APIs do not use the Google Data protocol
Google released a new Google Sheets API (v4; not GData) in
2016, and
Android Studio is now the preferred IDE over Eclipse. In order
to use Google APIs, you need to get the Google APIs Client Library
for Android (or for more general Java, the Google APIs Client
Library for Java). Now you're set.
To start, the latest Sheets API is much more powerful than all older versions. The latest API provides features not available in older releases, namely giving developers programmatic access to a Sheet as if you were using the user interface (create frozen rows, perform cell formatting, resize rows/columns, add pivot tables, create charts, etc.).
That said, yeah, it's tough when there aren't enough good (working) examples floating around, right? In the official docs, we try to put "quickstart" examples in as many languages as possible to help get you going. In that spirit, here are the Android quickstart code sample as well as the more general Java Quickstart code sample. For convenience, here's the Sheets API JavaDocs reference.
Another answer suggested using OAuth2 for data authorization, which you can do with this auth snippet from the quickstart above, plus the right scope:
// Sheets RO scope
private static final String[] SCOPES = {SheetsScopes.SPREADSHEETS_READONLY};
:
// Initialize credentials and service object
mCredential = GoogleAccountCredential.usingOAuth2(
getApplicationContext(), Arrays.asList(SCOPES))
.setBackOff(new ExponentialBackOff());
If you're not "allergic" to Python, I've made several videos with more "real-world" examples using the Sheets API (non-mobile though):
Migrating SQL data to a Sheet (code deep dive post)
Formatting text using the Sheets API (code deep dive post)
Generating slides from spreadsheet data (code deep dive post)
Finally, note that the Sheets API performs document-oriented functionality as described above. For file-level access, i.e. import, export etc. you'd use the Google Drive API instead; specifically for mobile, use the Google Drive Android API. Hope this helps!
It's a complex process, but it can be done! I wrote a blog post on getting the basics up and running. And I've also published an open-source project that is actually useful, but still quite minimal. It uses OAuth, and therefore can pull the permission directly from Android's permission model (no hardcoded email/password!).
You need something to start the "Choose account intent":
View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
Intent intent = AccountPicker.newChooseAccountIntent(null, null, new String[]{"com.google"},
false, null, null, null, null);
startActivityForResult(intent, 1);
if (AUTO_HIDE) {
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
return false;
}
};
And then when that intent returns, you can try to use the token that was returned (although note, if it's the first time the user may have to explicitly authorize your program; that's the UserRecoverableAuthException):
protected void onActivityResult(final int requestCode, final int resultCode,
final Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
final String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
System.err.println(accountName);
(new AsyncTask<String, String,String>(){
#Override
protected String doInBackground(String... arg0) {
try {
// Turn account name into a token, which must
// be done in a background task, as it contacts
// the network.
String token =
GoogleAuthUtil.getToken(
FullscreenActivity.this,
accountName,
"oauth2:https://spreadsheets.google.com/feeds https://docs.google.com/feeds");
System.err.println("Token: " + token);
// Now that we have the token, can we actually list
// the spreadsheets or anything...
SpreadsheetService s =
new SpreadsheetService("Megabudget");
s.setAuthSubToken(token);
// Define the URL to request. This should never change.
// (Magic URL good for all users.)
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;
try {
feed = s.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.err.println(spreadsheet.getTitle().getPlainText());
}
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (UserRecoverableAuthException e) {
// This is NECESSARY so the user can say, "yeah I want
// this app to have permission to read my spreadsheet."
Intent recoveryIntent = e.getIntent();
startActivityForResult(recoveryIntent, 2);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (GoogleAuthException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}}).execute();
} else if (requestCode == 2 && resultCode == RESULT_OK) {
// After the user YAYs or NAYs our permission request, we are
// taken here, so if we wanted to grab the token now we could.
}
}

getFromLocationName() returns null on android tablet

cmap.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{ System.out.println("Cmap initial:=lat:-"+lat+" lang:-"+lon);
Toast t=Toast.makeText(getBaseContext(),"Location"+lat+"lang:-"+lon,Toast.LENGTH_LONG);
t.show();
tlname=elname.getText().toString();
tladdr=eladdr.getText().toString();
addressInput=tlname+" "+tladdr;
System.out.println("address:-"+addressInput);
Toast t3=Toast.makeText(getBaseContext(),"Address"+addressInput,Toast.LENGTH_LONG);
t3.show();
try
{
Geocoder gc1 = new Geocoder(
getBaseContext(), Locale.getDefault());
foundAdresses = gc1.getFromLocationName(addressInput, 5);
showAdressResults.sendEmptyMessage(0);
Toast t1=Toast.makeText(getBaseContext(),"Location...."+foundAdresses,Toast.LENGTH_LONG);
t1.show();
System.out.println("faddress:-"+foundAdresses);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (foundAdresses.size() == 0)
{ // if no address found,
// display an error
Dialog locationError = new AlertDialog.Builder(
Gotask.this).setIcon(0).setTitle(
"Error").setPositiveButton(R.string.ok, null)
.setMessage(
"Sorry, your address doesn't exist.")
.create();
locationError.show();
} else
{ // else display address on map
for (int i = 0; i < foundAdresses.size(); ++i)
{
Address x = foundAdresses.get(i);
lat = (x.getLatitude() *100);
lon = (float) x.getLongitude();
System.out.println("Cmap:=lat:-"+lat+" lang:-"+lon);
}
navigateToLocation((lat * 1000000), (lon * 1000000),myMap);
}
}
});
I have also faced this kind of issue in reverse Geo coding so i am use Google api for it.
Refer this link for google api to use in reverse geocoding.
I faced the same problem when i was developing an app based on google maps.The problem was with the devcie ,the one which i am using did't support backend service(a kind of service comes with device) which is responsible for working of GeoCoding related APIs.So i decided to use services exposed by google to query for lat & longitude for the required Address.So just give a try.
Refer this link to know more
http://code.google.com/apis/maps/documentation/geocoding/
Please refer following links:
How can you tell when an Android device has a Geocoder backend service?
Android; Geocoder, why do I get "the service is not available"?
Here is a sample request for geocoding request to obtain Latitude and longitude from response after parsing Xml output.
http://maps.googleapis.com/maps/api/geocode/xml?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true_or_false
There is a clear cut example in the link mentioned earlier.

Categories

Resources