Android | Google PlacePicker API. OnActivityResult code not executed [Really weird behaviour] - android

I've a Fragment (support.v4) in a ViewPager with the which calls PlacePicker UI and then updated on a TextView. My code is as follows,
public void openPlacePicker() {
try {
PlacePicker.IntentBuilder intentBuilder = new PlacePicker.IntentBuilder();
Intent intent = intentBuilder.build(getContext());
// Start the Intent by requesting a result, identified by a request code.
startActivityForResult(intent, PLACE_PICKER);
} catch (GooglePlayServicesRepairableException e) {
GooglePlayServicesUtil
.getErrorDialog(e.getConnectionStatusCode(), getActivity(), 0);
} catch (GooglePlayServicesNotAvailableException e) {
Toast.makeText(getContext(), "Google Play Services is not available.",
Toast.LENGTH_LONG)
.show();
}
}
And the OnActivityResult is,
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.i(TAG, "Request Code:" + requestCode);//This is printed
if(requestCode == PLACE_PICKER){
Log.d(TAG,"Reached in if()"); //Never printed
}
switch (requestCode) { //Never reached
case PLACE_PICKER:
if (resultCode == Activity.RESULT_OK) {
final Place place = PlacePicker.getPlace(data, getContext());
final CharSequence name = place.getName();
//EventBus.getDefault().post(new NotifyEvent(NotifyEvent.NotifyType.PLACE_PICKED, (String) name));
}
}
}
So the problem is that, the conditional statements never gets executed. The Log before if() is printed. But the Log inside the if() is not printed.
Weird thing is the android-place-picker sample from GitHub is working fine.
I have tried the following:
Clean Project
Clear Data and re-install on device
IDE clear cache and restart
Any ideas?
--EDIT--
Manifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.apps.maps">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="com.apps.maps.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<permission android:name="com.apps.maps.permission.MAPS_RECEIVE" android:protectionLevel="signature" />
<application android:name=".MyApplication" android:allowBackup="true" android:icon="#mipmap/ic_launcher" android:label="#string/app_name" android:supportsRtl="true" android:theme="#style/AppTheme">
<meta-data android:name="com.google.android.geo.API_KEY" android:value="#string/google_maps_key" />
<activity android:name=".activity.MainActivity" android:label="#string/title_activity_maps">
</activity>
</application>
</manifest>

I know this is an older thread but it has helped me to resolve a similar issue to the original problem. Raman Bhavsar's 10/10/15 comment was the right question to ask. I had forgotten to enable the Places API in the Google Developer Console, and once I did I was able to hit my breakpoint in the onActivityResult method.

Related

checkSelfPermission is not working properly

I'm trying to do a quick test app that allow me to turn on a off Bluetooth and I code the listeners for clicks in the buttons. This is the one that turn Bluetooth on:
mOnBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!mBlueAdapter.isEnabled()) {
showToast("Turning On Bluetooth...");
//intent to on BT
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//Android Studio force me to do this check.
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
showToast("I'm stuck here");
return;
}
startActivityForResult(intent, REQUEST_ENABLE_BT);
} else {
showToast("Bluetooth is already on");
}
}
});
The thing is that Android Studio force me to add the:
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
showToast("I'm stuck here");
return;
}
check error but even I have all the permissions they asked me in AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.Bluetooth">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
the program always fails the check error and ended up in the "You're stuck message", what is happening here?
Turning bluetooth on and requesting `BLUETOOTH_CONNECT permission is a different thing.
Request permission like BLUETOOTH_CONNECT, see https://developer.android.com/training/permissions/requesting.
Turning bluetooth on
if (bluetoothAdapter?.isEnabled == false) {
val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT)
}
If enabling Bluetooth succeeds, your activity receives the RESULT_OK result code in the onActivityResult() callback. If Bluetooth was not enabled due to an error (or the user responded "Deny") then the result code is RESULT_CANCELED.
See Set up Bluetooth for details.

WifiManger.getScanResults() returns empty list on android

Yes, I did take a look at all other similar question but they are not working for me.
I am trying to get a list of wifi connections available near me.
This is how I am doing it:
public class WifiFunction {
private final String tag = WifiFunction.class.getSimpleName();
private WifiManager wifiManager;
public List<WifiDetail> getListofWifi(Context context) {
List<WifiDetail> wifiDetails = new ArrayList<>();
List<ScanResult> results = wifiManager.getScanResults();
Log.d(tag,"Wifi Details " + wifiManager.getScanResults().size());
for (ScanResult result : results) {
wifiDetails.add(new WifiDetail(result.BSSID, result.SSID));
Log.d(tag, result.BSSID + result.SSID);
}
return wifiDetails;
}
public void startScan(Context context)
{
wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
wifiManager.startScan();
IntentFilter filter = new IntentFilter();
filter.addAction(SCAN_RESULTS_AVAILABLE_ACTION);
context.registerReceiver(new resultReciever(this),filter);
}
}
Receiver class :
public class resultReciever extends BroadcastReceiver {
private WifiFunction wifiFunction;
resultReciever(WifiFunction wifiFunction)
{
this.wifiFunction = wifiFunction;
}
#Override
public void onReceive(Context context, Intent intent) {
Log.d("Receiver","started");
wifiFunction.getListofWifi(context);
}
}
From Main Activity I am just calling:
(new WifiFunction()).startScan(this);
that is after checking for permissions.
Yes, I did declare receiver in the manifest.
I am asking for access and change of wifi state and access coarse location.
Still, Log prints the size of the returned list to be 0. What am I doing wrong? How to solve it?
Edit: Manifest
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permisiion.ACCESS_COARSE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".resultReciever"/>
</application>
EDIT 2:
Runtime Permission:
private boolean checkPermission() {
List<String> permissionsList = new ArrayList<String>();
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_WIFI_STATE) != PackageManager.PERMISSION_GRANTED) {
permissionsList.add(Manifest.permission.ACCESS_WIFI_STATE);
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CHANGE_WIFI_STATE) != PackageManager.PERMISSION_GRANTED) {
permissionsList.add(Manifest.permission.CHANGE_WIFI_STATE);
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
permissionsList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
}
if (permissionsList.size() > 0) {
ActivityCompat.requestPermissions(this, permissionsList.toArray(new String[permissionsList.size()]),
1);
return false;
}
return true;
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
switch (requestCode) {
case 1:
(new WifiFunction()).startScan(this);
break;
}
}
This worked. I just had to give Access_Fine_Location permission.
Adding the following line to your manifest is not necessarily enough to fix the problem!
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
If your targetSdkVersion is 23 or greater, then (because this is one of the dangerous permissions) you must also do something like this
ActivityCompat.requestPermissions(Main.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION }, 1);
Doing this fixed the problem for both me and the OP. I double-checked the assertion by reversing the changes to recreate the problem.
NB: There are 2 highly remarkable elements here:
(1) Nowhere is it documented that WifiManager.startScan() requires this permission.
(2) My app is based on a working (pre-API 23) app that does NOT have Manifest.permission.ACCESS_FINE_LOCATION
You were missing permission to access Access_Fine_Location, but starting from Android 6 granting all the permissions won't yield the expected output. You have to enable location services in order to get desired results. Granting permissions is just the half work done.
You can also fire an intent to redirect user to this setting:
Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
Location services are necessary because when you access the scan results, you can access the information like BSSID (address of the access point). This information can also be used to detect the location of device. By requiring location services, OS ensures that user understands their location information is being accessed when they use your app.
Set permission in your AndroidManifest.xml
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Now go to settings > Apps > your app > Permissions. Make sure Location is switched on.
Now go to Settings > Location make sure its switched on.
You should be able to get results in WifiManger.getScanResults()
A successful call to WifiManager.getScanResults() requires any one of the following permissions:
ACCESS_FINE_LOCATION
ACCESS_COARSE_LOCATION
CHANGE_WIFI_STATE
If the calling app does not have any of these permissions, the call fails with a SecurityException.
So Android 8 able to retrive all wifi APs by just enabling the CHANGE_WIFI_STATE

getting bitmap from uri not working

whenever i try to get uri from Intent which just select an image from image picker its not working here is my code. Please answer ASAP
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.share) {
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
i.setType("image/*");
startActivityForResult(i, 1);
} else if (id == R.id.logOut) {
ParseUser.logOut();
Intent i = new Intent(this, MainActivity.class);
startActivity(i);
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == Activity.RESULT_OK && data!=null) {
try {
Uri selectedImage = data.getData();
// this is the line which is causing error
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
Toast.makeText(getApplication().getBaseContext(),"test",Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
and this is logs:
I/Error: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media/27 from pid=5506, uid=10043 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
permission already given are:
uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"
Note:can't use proper tags for uses-permisson here because stackover flow giving error
Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="Share Pics"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="com.parse.APPLICATION_ID"
android:value="X6I00RcSXvAnvvV8iaR6ftEsHo2o7sHXmzkZlb03" />
<meta-data
android:name="com.parse.CLIENT_KEY"
android:value="MyKnxnrPXRan1z56fpSmkxPx7hgcM44NfvzdC4q5" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".UserList" />
<activity
android:name=".UsersFeed"
android:label="#string/title_activity_users_feed"
android:parentActivityName=".UserList"
android:theme="#style/AppTheme.NoActionBar">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.anshuman.myinstagram.UserList"/>``
</activity>
</application>
Add this to your manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.pc.myapplication" >
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
...
if you are using an emulator check this link: https://developer.android.com/training/permissions/requesting.html
and check this code:
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Manifest.permission.READ_CONTACTS)) {
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.READ_CONTACTS},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}

onResultActivity is called immediately after startActivyForResult

In my main activity i have this code:
noConnectionButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivityForResult(new Intent(Settings.ACTION_WIRELESS_SETTINGS), SET_CONNECTION);
}
});
in the onCreate method. Then:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == SET_CONNECTION){
checkConnection();
}
}
So what I want to do is to start the settings activity in a way that the user can switch on wireless or data connection.
My problem is that the onActivityResult is called prematurely!!! so I want it to be called only after the user backs to my activity.
any suggestion??
here the manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="it.polimi.metalnews"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="13"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="it.polimi.metalnews.MainActivity"
android:label="#string/app_name"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="it.polimi.metalnews.HomeActivity"
android:label="#string/title_activity_home" >
</activity>
<activity
android:name="it.polimi.metalnews.NewsActivity"
android:label="#string/title_activity_news" >
</activity>
<activity
android:name="it.polimi.metalnews.AlbumActivity"
android:label="#string/title_activity_album" >
</activity>
<activity
android:name="it.polimi.metalnews.ContestActivity"
android:label="#string/title_activity_contest" >
</activity>
</application>
follow this process:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
// Check which request we're responding to
if (requestCode == PICK_CONTACT_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// The user picked a contact.
// The Intent's data Uri identifies which contact was selected.
// Do something with the contact here (bigger example below)
}
}
}
use below link for further detail:
http://developer.android.com/training/basics/intents/result.html
In onActivity result first check if the result is came from the action is OK or not by comparing your result code to RESULT_OK like:
if (resultCode == RESULT_OK) {
// You successfully got back then do what ever you want.
//Then you can check you particular data according to your request.
}
Because there is no reason for going deep if the result is not ok. Every system service will result in RESULT_OK or RESULT_CANCEL if canceled by user.
I don't think there is anything wrong with intent declaration but i read this kind of article link it explains your problem in a better manner
It is due to the Activity is SingleTask and whenever it is called it reports the result.

ACCESS_FINE_LOCATION AndroidManifest Permissions Not Being Granted

I am trying to utilize GPS in Android (2.2 and 2.3) but am getting the following error when I try to use the LocationManager object:
WARN/System.err(522): java.lang.SecurityException: Provider network requires ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION permission
I have researched the issue in other posts and they are typically due to issues with AndroidManifest.xml. However, mine appears to be fine:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.thedigitalsean.examples"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".GetLocation"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permisssion.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permisssion.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permisssion.INTERNET"></uses-permission>
</manifest>
Here is the offending line of code in my onCreate method in the GetLocation Activity, encased in a try/catch block:
LocationManager locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
final LocationListener locListener = new MyLocListener();
try{
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locListener);
}
catch (SecurityException se){
((TextView)findViewById(R.id.infobox)).setText(se.toString());
se.printStackTrace();
}
This is the first app I have written where I need to request android permissions and have so far been unsuccessful in being granted any permissions whatsoever. Is there something I am missing in my manifest or perhaps in my eclipse configuration?
You misspelled permission
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
I was having the same problem and could not figure out what I was doing wrong. Turns out, the auto-complete for Android Studio was changing the text to either all caps or all lower case (depending on whether I typed in upper case or lower cast words before the auto-complete). The OS was not registering the name due to this issue and I would get the error regarding a missing permission. As stated above, ensure your permissions are labeled correctly:
Correct:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Incorrect:
<uses-permission android:name="ANDROID.PERMISSION.ACCESS_FINE_LOCATION" />
Incorrect:
<uses-permission android:name="android.permission.access_fine_location" />
Though this may seem trivial, its easy to overlook.
If there is some setting to make permissions non-case-sensitive, please add a comment with the instructions. Thank you!
Compatible with all SDK versions (android.permission.ACCESS_FINE_LOCATION became dangerous permission in Android M and requires user to manually grant it).
In Android versions below Android M ContextCompat.checkSelfPermission(...) always returns true if you add these permission(s) in AndroidManifest.xml)
public void onSomeButtonClick() {
...
if (!permissionsGranted()) {
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, 123);
} else doLocationAccessRelatedJob();
...
}
private Boolean permissionsGranted() {
return ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED);
}
#Override
public void onRequestPermissionsResult(final int requestCode, #NonNull final String[] permissions, #NonNull final int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 123) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission granted.
doLocationAccessRelatedJob();
} else {
// User refused to grant permission. You can add AlertDialog here
Toast.makeText(this, "You didn't give permission to access device location", Toast.LENGTH_LONG).show();
startInstalledAppDetailsActivity();
}
}
}
private void startInstalledAppDetailsActivity() {
Intent i = new Intent();
i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
i.addCategory(Intent.CATEGORY_DEFAULT);
i.setData(Uri.parse("package:" + getPackageName()));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
in AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
I Had an strange issue and realized that the text of manifest permission has a a space character at the end. removed it and it is working just fine.
Before
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION "/>
After
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
just remove s from the permission you are using sss you have to use ss

Categories

Resources