getting bitmap from uri not working - android

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.
}
}

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.

WifiManeger#scanResults() always returning empty in Android 6.0

Yes, I did take a look at all other similar question but they are not working for me. I'm trying to scan all the access points near me. This exact code works for Android 10, but in Android 6.0, specifically in Galaxy J5, the getScanResult() is always returning empty, the code:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_alunos);
setTitle(TITULO_APPBAR);
listaAlunosView = new ListaAlunosView(this);
configuraFabNovoAluno();
configuraLista();
wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
//Check for permissions
if ((ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED)
|| (ContextCompat.checkSelfPermission(this, Manifest.permission.CHANGE_WIFI_STATE)
!= PackageManager.PERMISSION_GRANTED))
{
Log.i("TAG", "Requesting permissions");
//Request permission
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_WIFI_STATE,
Manifest.permission.CHANGE_WIFI_STATE,
Manifest.permission.ACCESS_NETWORK_STATE},
123);
}
else
Log.i("TAG", "Permissions already granted");
wifiScan();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
Log.i("TAG,", "onRequestPermissionsResult");
switch (requestCode)
{
case 123:
{
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
// permission was granted
Log.i("TAG", "permission granted: " + permissions[0]);
}
else
{
// permission denied, boo! Disable the
// functionality that depends on this permission.
Log.i("TAG", "permission denied: " + permissions[0]);
}
return;
}
// other 'case' lines to check for other
// permissions this app might request.
}
}
private void wifiScan() {
wifiManager.startScan();
BroadcastReceiver wifiScanReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
boolean success = intent.getBooleanExtra(WifiManager.EXTRA_RESULTS_UPDATED, false);
if(success) {
List<ScanResult> scanResults = wifiManager.getScanResults();
Log.i("SCAN RESULT:", "" + scanResults);
} else {
}
}
};
Android Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="br.com.alura.agenda"
tools:ignore="GoogleAppIndexingWarning">
<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_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<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"
tools:ignore="AllowBackup">
<activity android:name=".ui.activity.ListaAlunosActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ui.activity.FormularioAlunoActivity" />
</application>
</manifest>
I also turned my Location Services ON.
Can someone tell me where is the error?

Trying to prompt user to set permissions on app launch in AndroidManifest

Okay, so in my AndroidManifest.xml file, I'm trying to set my permissions such that when the App launches, the user is asked to allow Location + Storage permissions.
I'm working off the BluetoothLeGatt example, and I used the uses-permission-sdk-23 tags to do it.
For reference, here's my code:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.bluetoothlegatt"
android:versionCode="1"
android:versionName="1.0">
<!-- Min/target SDK versions (<uses-sdk>) managed by build.gradle -->
<!-- Declare this required feature if you want to make the app available to BLE-capable
devices only. If you want to make your app available to devices that don't support BLE,
you should omit this in the manifest. Instead, determine BLE capability by using
PackageManager.hasSystemFeature(FEATURE_BLUETOOTH_LE) -->
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission-sdk-23 android:name="android.permission.BLUETOOTH"/>
<uses-permission-sdk-23 android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission-sdk-23 android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission-sdk-23 android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application android:label="#string/app_name"
android:icon="#drawable/ic_launcher"
android:theme="#android:style/Theme.Holo.Light">
<activity android:name=".DeviceScanActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name=".DeviceControlActivity"/>
<service android:name=".BluetoothLeService" android:enabled="true"/>
</application>
</manifest>
try this
step 1 :- add permission that you want in manifiest file like this
android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION,
step 2 : ask runtime permission like this
String permission = android.Manifest.permission.ACCESS_FINE_LOCATION;
if (ActivityCompat.checkSelfPermission(SearchCityClass.this, permission)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.
checkSelfPermission(SearchCityClass.this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(SearchCityClass.this, new String[]
{permission}, PERMISSION_GPS_CODE);
}
step 3: handle permission result like this
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSION_GPS_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, location_permission_granted_msg, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, location_permission_not_granted_msg, Toast.LENGTH_SHORT).show();
}
}
}
uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
In MainActivity add the following
if (Build.VERSION.SDK_INT < 23) {
//We already have permission. Write your function call over hear
} else {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// Here we are asking for permission
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else {
//If the app is running for second time, then we already have
permission. You can write your function here, if we already have
permission.//
}
}
do same for memory storage..

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

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.

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.

Categories

Resources