Take Photo with Camera Samsung galaxy s5 destroy activity - java

I am working on app which uses an ImageView to display a photo. But after a photo is taken, it is not being shown in the ImageView. Furthermore, the app gets force closed after taking the picture. I try this with my Nexus 5 (Marshmallow), Samsung Galaxy S4(Lollipop & CustomRom), Xiaomi Mi4, Asus Zenfone 1, and Lenovo tablet which all run smoothly. Here are some scenarios that I tried with the Samsung Galaxy S5 :
Take a photo, wait a couple of seconds before clicking "Ok", then I press back to my apps. (Result : sometimes this works, sometimes image does not show in the ImageView)
Take a photo and immediately click "Ok". (Result : force closed. Logcat says TextView in abstract class is null )
Take a photo, immediately click "Ok" while debuging in function OnActivityResult (Result : it works)
Here's the code :
AndroidManifest.xml
<application
android:name=".coreclass.CoreApp"
android:allowBackup="true"
android:hardwareAccelerated="true"
android:icon="#mipmap/unik_fintech"
android:label="#string/appname"
android:largeHeap="true"
android:launchMode="singleInstance"
android:noHistory="true"
android:theme="#style/Theme.MyTheme"
tools:replace="android:label">
<activity
android:name=".activities.MainPage"
android:configChanges="screenSize|keyboardHidden|orientation"
android:exported="true"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateAlwaysHidden">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".activities.KantinActivity"
android:configChanges="screenSize|keyboardHidden|orientation"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateAlwaysHidden|adjustPan"
/>
KantinActivity.java
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Timber.d("isi request code:" + String.valueOf(requestCode));
Timber.d("isi result Code:"+ String.valueOf(resultCode));
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case RESULT_GALERY:
if(resultCode == RESULT_OK){
Fragment currentFrag = getSupportFragmentManager().findFragmentById(R.id.kantinActivityContent);
if(currentFrag instanceof StockBarangAction){
Bitmap photo = null;
Uri _urinya = data.getData();
if(data.getData() == null) {
photo = (Bitmap)data.getExtras().get("data");
} else {
try {
photo = MediaStore.Images.Media.getBitmap(getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
GeneralizeImage mGI = new GeneralizeImage(this,photo,_urinya);
StockBarangAction mFrag = (StockBarangAction) currentFrag;
mFrag.setFileImageCatalog(false, mGI.Convert(), _urinya.toString());
}
}
break;
case RESULT_CAMERA:
if(resultCode == RESULT_OK && mCapturedImageURI!=null){
Fragment currentFrag = getSupportFragmentManager().findFragmentById(R.id.kantinActivityContent);
if(currentFrag instanceof StockBarangAction){
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(mCapturedImageURI, projection, null, null, null);
String filePath;
if (cursor != null) {
cursor.moveToFirst();
int column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
filePath = cursor.getString(column_index_data);
}
else
filePath = data.getData().getPath();
GeneralizeImage mGI = new GeneralizeImage(this,filePath);
StockBarangAction mFrag = (StockBarangAction) currentFrag;
mFrag.setFileImageCatalog(true, mGI.Convert(), filePath);
if (cursor != null) {
cursor.close();
}
}
}
else{
Toast.makeText(this, "Try Again", Toast.LENGTH_LONG).show();
}
break;
default:
break;
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mCapturedImageURI != null) {
outState.putString("cameraImageUri", String.valueOf(mCapturedImageURI));
}
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState.containsKey("cameraImageUri")) {
mCapturedImageURI = Uri.parse(savedInstanceState.getString("cameraImageUri"));
}
}
public void setmCapturedImageURI(Uri _uri) {
mCapturedImageURI = _uri;
}
StockBarangAction.java
private void chooseCamera() {
if (reqPermissionClass.checkPermission(Manifest.permission.CAMERA, ReqPermissionClass.PERMISSIONS_REQ_CAMERA)) {
runCamera();
}
}
public void runCamera(){
String fileName = "temp.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
mCapturedImageURI = getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
KantinActivity parent = (KantinActivity) getActivity();
parent.setmCapturedImageURI(mCapturedImageURI);
Intent takePictureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
getActivity().startActivityForResult(takePictureIntent, KantinActivity.RESULT_CAMERA);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (reqPermissionClass.checkOnPermissionResult(requestCode,grantResults,
ReqPermissionClass.PERMISSIONS_REQ_WRITEEXTERNALSTORAGE)||
reqPermissionClass.checkOnPermissionResult(requestCode,grantResults,
ReqPermissionClass.PERMISSIONS_REQ_CAMERA)) {
chooseCamera();
}
else {
Toast.makeText(getActivity(), getString(R.string.cancel_permission_read_contacts), Toast.LENGTH_SHORT).show();
}
}
public void setFileImageCatalog(boolean isCamera, File mFile, String imageContent) {
mFileImageCatalog = mFile;
Picasso mPic;
if(MyApiClient.PROD_FLAG_ADDRESS)
mPic = MyPicasso.getImageLoader(getActivity());
else
mPic= Picasso.with(getActivity());
if(mFileImageCatalog != null){
if(isCamera) {
mPic.load(new File(imageContent))
.error(R.drawable.icon_no_photo)
.placeholder(R.drawable.progress_animation)
.fit()
.centerInside()
.into(img_catalog);
}else
mPic.load(imageContent)
.error(R.drawable.icon_no_photo)
.fit()
.centerInside()
.placeholder(R.drawable.progress_animation)
.into(img_catalog);
}
}
StockBarangAction.java is a fragment that call intent camera, the result catch by KantinActivity(Extend BaseActivity) where the image get resize using "GeneralizeImage" function, then sent back to fragment with "setFileImageCatalog" function.
What I want to know is :
does the camera app on the Samsung Galaxy S5 really have problem ?
Why my apps get killed and some components become null (like TextView). I try to "findViewId" again, but its still not working. Do i need to
save the textview instance?
Thank you and sorry for my English.

Most likely, your process is being terminated while your app is in the background. This is perfectly normal. You will get a fresh process when needed, and the user may be returned to whatever activity they had been on previously.
Your app needs to handle this case, because it is not only going to happen when you take a picture — it can happen for other reasons as well:
User is in your app
User presses HOME
Five minutes later, Android terminates your process to free up system RAM for other processes
Two minutes after that, the user goes back to your app (home screen launcher icon, overview/recent-tasks screen, etc.)
does camera app samsung galaxy s5 really have problem ?
No.
Do i need to save the textview instance ?
That is not possible.

Related

Edited bitmap only saving drawn changes without original picture in shared storage and empty bitmap in internal storage

I was adding a new feature to my drawing app project where users could open any picture from the phone gallery and draw on it. But I am having issues saving the new bitmap. Here are the details below :
My app has 3 activities :
Main Activity as a menu,
RecyclerView activity that acts as a gallery,
Drawing activity where users draw
Up until recently whenever a user saved an image, it would create two copies of it. One private that would be stored in application's personal storage that is not available to phone's gallery to use but is displayed in applications own gallery activity, and one public picture in media which will be displayed in the phones gallery. My gallery class checks the internal folder of the application and lists all files in it to display, that is why I also save in private app directory too. Save image method has two sections that handles the scoped storage issues with api 28+ and <28 respectively.
Recently I added a feature where users can pick any picture from phone's gallery and edit it (both images that app created and those that it did not).It uses intent picker function.
Expected results are :
Open a picture from the gallery in the drawing activity and draw on top of it
Save edited version as a new image both privately in app's storage and a public shared copy in phones main gallery
Current issues :
Image opens and is drawn upon without problems (both images made by the app and foreign pictures)
Saving images causes the app to save an empty bitmap in phones private gallery and changes (edits drawn) in shared storage on the phone without actual image that was meant to be edited.
Here is the code :
From MainActivty, code that opens the images from phone's gallery in order to edit them.
// checks permissions for reading external and scoped storage before opening image picker
private void pickAnImage() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "SDK >= Q , requesting permission");
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1000);
} else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q && checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "SDK < Q , requesting permission");
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1000);
} else {
Log.d(TAG, "Permission exists, starting pick intent");
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(gallery, IMAGE);
}
}
// handles results from permissions and begins intent picker
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1000) {
Log.d(TAG, "result code good");
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "Permission is granted, starting pick");
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(gallery, IMAGE);
} else {
Log.d(TAG, "While result code is good, permission was denied");
Toast.makeText(MainActivity.this, "Permission Denied !", Toast.LENGTH_SHORT).show();
}
}
}
// handles results from intent picker and feeds the image path to the drawing activity for image editing
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == IMAGE && data != null) {
Log.d(TAG, "Data from picked image is not null, creating uri and path");
Uri selectedImageUri = data.getData();
String picturePath = getPath(getApplicationContext(), selectedImageUri);
// Log.d("Picture Path", picturePath);
if (picturePath != null) {
Log.d(TAG, "Path creating success, calling art activity");
Intent intent = new Intent(getApplicationContext(), ArtActivity.class);
intent.putExtra("image", picturePath);
startActivity(intent);
} else {
Log.d(TAG, "Path was null");
finish();
}
}else{
Log.d(TAG, "Data seems to be null, aborting");
}
}
// obtains the path from the picked image
private static String getPath(Context context, Uri uri) {
String result = null;
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = context.getContentResolver().query(uri, proj, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(proj[0]);
result = cursor.getString(column_index);
Toast.makeText(context, "" + result, Toast.LENGTH_SHORT).show();
}
cursor.close();
}
else {
Toast.makeText(context.getApplicationContext(), "Failed to get image path , result is null or permission problem ?", Toast.LENGTH_SHORT).show();
result = "Not found";
Toast.makeText(context, "" + result, Toast.LENGTH_SHORT).show();
}
return result;
}
Below are methods that handle bitmap editing process :
// Inside initialization method that sets up paint and bitmap objects before drawing
if (bitmap != null) {
// if bitmap object is not null it means that we are feeding existing bitmap to be edited, therefore we just scale it to screen size before giving it to canvas
loadedBitmap = scale(bitmap, width, height);
} else {
// bitmap fed to this method is null therefore it means we are not editing existing picture so we create a new object to draw on
this.bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888, true);
}
Inside onDraw method that handles drawing as it happens :
if (loadedBitmap != null) {
// loadedBitmap not being null means we are editing existing image from above, we previously scaled it so now we feed it to the canvas for editing
canvas.drawBitmap(loadedBitmap, 0, 0, paintLine);
canvas.clipRect(0, 0, loadedBitmap.getWidth(), loadedBitmap.getHeight());
} else {
// we are not editing an image so we draw new empty bitmap to use
canvas.drawBitmap(bitmap, 0, 0, tPaintline);
}
And finally, here is the infamous save image method that is the root of current problems :
#SuppressLint("WrongThread") // not sure what to do otherwise about this lint
public void saveImage() throws IOException {
//create a filename and canvas
String filename = "appName" + System.currentTimeMillis();
Canvas canvas;
// loadedBitmap is the edited one, bitmap is a new one if we did not edit anything
if(loadedBitmap != null){
canvas = new Canvas(loadedBitmap);
} else{
canvas = new Canvas(bitmap);
}
// save image handle for newer api that has scoped storage and updated code
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
// feed all the data to content values
OutputStream fos;
ContentResolver resolver = context.getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, filename + ".jpg");
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpg");
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);
Uri imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
fos = resolver.openOutputStream(Objects.requireNonNull(imageUri));
draw(canvas);
// compress correct bitmap, loaded is edited, bitmap is new art
if(loadedBitmap != null){
loadedBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
}else{
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
}
Objects.requireNonNull(fos).close();
imageSaved = true;
} else {
// for api older then 28 before scoped storage
// create app directory and a new image file
ContextWrapper cw = new ContextWrapper(getContext());
File directory = cw.getDir("files", Context.MODE_PRIVATE);
pathString = cw.getDir("files", Context.MODE_PRIVATE).toString();
File myPath = new File(directory, filename + ".jpg");
FileOutputStream fileOutputStream = new FileOutputStream(myPath);
// check permissions
try {
if(ContextCompat.checkSelfPermission(
context, Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
PackageManager.PERMISSION_GRANTED){
draw(canvas);
// save edited or new bitmap to private internal storage
if(loadedBitmap != null){
MediaStore.Images.Media.insertImage(context.getContentResolver(), loadedBitmap, filename, "made with appName");
}else{
MediaStore.Images.Media.insertImage(context.getContentResolver(), bitmap, filename, "made with appName");
}
// now also add a copy to shared storage so it will show up in phone's gallery
addImageToGallery(myPath.getPath(), context);
imageSaved = true;
}else{
// request permissions if not available
requestPermissions((Activity) context,
new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
100);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fileOutputStream.flush();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Save image to gallery method used above :
// for old api <28, it adds the image to shared storage and phone's gallery
public static void addImageToGallery(final String filePath, final Context context) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.MediaColumns.DATA, filePath);
context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}
That is all, if anyone knows bitmap, canvas and permissions (old and new) feel free to help. I am sure tha changes I need are small. Check the current issues above in order to know what to look for.

Unable to display result of camera activity in ImageView

Basically what I'm trying to do is create a simple app that uses the default camera app to take a picture, then I want to display that image in a new activity within an ImageView, but everything I've tried has resulted in
java.io.FileNotFoundException: /storage/emulated/0/imageToProcess.jpg: open failed: ENOENT (No such file or directory)
I've included the correct permissions (maybe even too many) in the manifest:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
and I'm also manually requesting permissions if need be in the main activity:
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if(checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA}, 1);
}
if(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
if(checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}
}
so I don't think the issue is with read/write permissions.
In my main activity's xml file, I've created a button with an onClick listener that calls the following method:
public void openCamera(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(Environment.getExternalStorageDirectory() + File.separator + "imageToProcess.jpg");
imgUri = Uri.fromFile(f);
intent.putExtra("imgUri", imgUri.toString());
startActivityForResult(intent, TAKE_PICTURE);
}
Here's the onActivityResult() method I defined to create a new intent and pass the uri to the new activity:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if(requestCode == TAKE_PICTURE && resultCode == Activity.RESULT_OK) {
Intent camResult = new Intent(this, ShowCameraResult.class);
camResult.putExtra("imgUri", imgUri.toString());
startActivity(camResult);
}
}
NOTE: imgUri and TAKE_PICTURE are defined at the top of the class as protected static final int TAKE_PICTURE = 1; and private Uri imgUri;
Lastly, here is my ShowCameraResult activity
public class ShowCameraResult extends AppCompatActivity {
private Bitmap mImageBitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_camera_result);
ImageView imageView = (ImageView)findViewById(R.id.imageView);
String filePath = getIntent().getStringExtra("imgUri");
Log.d("ShowCameraResult", "directory: " + filePath);
try {
mImageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(filePath));
imageView.setImageBitmap(mImageBitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
The Log.d method call above returns
ShowCameraResult: directory: file:///storage/emulated/0/imageToProcess.jpg
This leads me to believe that the image result from the camera isn't actually being saved into my imageToProcess.jpg file, but I could be very wrong as this is the first real android project I've worked on.
So my question is: Where did I go wrong?
Any help is greatly appreciated, thank you!
ITs returning a file, not a content resolver uri. Just decode the file with BitmapFactory.

READ_EXTERNAL_STORAGE permission, app crash despite I have this in manifest

I have problem with permissions. What should I do to stop my app from crashing?
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == RESULT_OK && data != null){
Uri selectedImage = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
ImageView imageView = (ImageView)findViewById(R.id.imageView);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
AndroidManifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
I just added this in my OnCreate method
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 225);
And it seems to work, is there any better solution?
If putting in your onCreate() works I would check whether you put it in the manifest in the correct place because that has caused me issues in the past.
Make sure <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> is after the first manifest closing tag and before the first <Application ...
For example:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.mypackagename">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application...
try this :
//check permission is granted or no
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
{
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, RESULT_LOAD_IMG);
}
else
{
//your code
}
If your target build version is API 23 or higher, just check that the permission is granted or not.
Go to Settings -> Apps and then tap on your app. In Permissions option enable the Storage permission. But it is not the permanent solution.
Well i do something like u want. I give u simply code how to do this :)
Here i checking permission(i call this method in fragment, make this in activity)
#TargetApi(23)
public void checkStoragePermission() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
if (settingsDrawerFragment != null) {
settingsDrawerFragment.onPermissionGranted();
}
return;
}
if (this.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager
.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_CODE_EXTERNAL_STORAGE);
return;
}
if (settingsDrawerFragment != null) {
settingsDrawerFragment.onPermissionGranted();
}
}
This check permission with auto message
Also i make onRequestPermissions
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[]
grantResults) {
switch (requestCode) {
case REQUEST_CODE_AUDIO_RECORD:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startBrowseActivity();
} else {
Utils.showToast(this, getString(R.string.audio_permission_denied));
}
break;
case REQUEST_CODE_EXTERNAL_STORAGE:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (settingsDrawerFragment != null) {
settingsDrawerFragment.onPermissionGranted();
}
} else {
if (settingsDrawerFragment != null) {
closeSettingsDrawer();
}
Utils.showToast(this, getString(R.string.storage_permission_denied));
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
break;
}
}
Remember to make methods in activity. On fragment check it.
Finally i make something like this to check permissions in fragment
public void setHomeStreamSource(int position) {
if (position == STORAGE_CLOUD_CACHE) {
preferenceHelper.putInt(getString(R.string.preferences_usb_prefs), getString(R.string
.preferences_video_source), MainActivity.SOURCE_CLOUD);
closeDrawer();
Utils.showToast(activity, getString(R.string.source_selected));
} else if (position == STORAGE_USB) {
((MainActivity) activity).checkStoragePermission();
}
}
Hope this sample code help u well

Android NFC mimeType ignored, app is always starting while in contact with a tag or beam device

I have a problem with my app. It is using nfc tags for some actions (opening/locking door).
The app has a intent-filter at the default activity:
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="application/de.juwei.myapplication" />
</intent-filter>
But it seems it is ignoring the mimeType setting complety because it is starting even if i attach an empty tag to the phone and also if i try to beam data from another phone.
The code simply doing this:
public class MainActivity extends ActionBarActivity {
private NfcAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = NfcAdapter.getDefaultAdapter(this);
Intent intent = getIntent();
// see if app was started from a tag
if (mAdapter != null && intent.getType() != null && intent.getType().equals("application/de.juwei.myapplication")) {
}
}
#Override
protected void onResume() {
super.onResume();
if (mAdapter != null) {
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, this.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
mAdapter.enableForegroundDispatch(this, pendingIntent, null, null);
}
}
#Override
protected void onPause() {
super.onPause();
if (mAdapter != null) {
mAdapter.disableForegroundDispatch(this);
}
}
#Override
public void onNewIntent(Intent intent) {
if (mAdapter != null && intent.getType() != null && intent.getType().equals("application/de.juwei.myapplication")) {
// ... reading tag
}
}
}
getIntent() is null if the tag doesn't has my mimetype. So the app is just starting if for example holding to smartphones together trying to beam some data. The activity is also starting if i hold my sony smartwatch 3 to my phone...
The very strange thing is - if i try to reproduce this on a new app with just that simple code, the app is not starting on every nfc command.
But in my main app, there are no more nfc specific methods.
I am completly lost.
Does anyone know how to track/debug why the app is opening by every piece of nfc data?
Best regards,
Juergen
In enableForegroundDispatch method you have to add filters and techLists
For instance:
IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
try {
ndef.addDataType("*/*"); /* Handles all MIME based dispatches.
You should specify only the ones that you need. */
}
catch (MalformedMimeTypeException e) {
throw new RuntimeException("fail", e);
}
mFilters = new IntentFilter[] {
ndef,
};
mTechLists = new String[][] { new String[] { NfcF.class.getName() } };
NfcAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters,
mTechLists);
Looks like the problem was the enableForegroundDispatch.
I commented out both calls at onResume and onPause and changed Manifest to android:launchMode="singleTask" and it seems to work.
Must be some nfc bug, i don't know.
However, within my first tests it seems to work now, the app isn't starting every time i hold a nfc tag on back of the device.

Building a Camera App - Receive

I am new to Android programming and I'm writing an application in Java that opens the camera take a photo and save it. I made it via Intents but I can't see onActivityResult running.
I have tested it into my phone (Samsung Galaxy S) and when I take the photo I receive a preview of that photo having two buttons one Save and the other Cancel. I haven't added something to my code to do this so I think it's something that camera does. I want after capturing the image to run onActivityResult (after I press the Save button on the preview).
But how I'm going to return a result to start onActivityResult after pressing the Button Save on the preview?
I FORGOT to tell that after i press save my entire app is terminated.
Here is my Code
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TakePicButton = (Button) findViewById(R.id.TakePicture);
TakePicButton.setOnClickListener((android.view.View.OnClickListener) this);
}
#Override
public void onDestroy(){
super.onDestroy();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Image captured and saved to fileUri specified in the Intent
Toast.makeText(this, "Image saved to:\n" + data.getData(), Toast.LENGTH_LONG).show();
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT);
} else {
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT);
}
}
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId() == R.id.TakePicture){
// create Intent to take a picture and return control to the calling application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
}
try the below code, you will have to modify it a bit, it will help you get From Library and From Camera both, the SELECT_PICTURE is used for getting image from library
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case SELECT_PICTURE:
Uri selectedImageUri = data.getData();
filemanagerstring = selectedImageUri.getPath();
selectedImagePath = getPath(selectedImageUri);
if (selectedImagePath != null)
myFile = new File(selectedImagePath);
else if (filemanagerstring != null)
myFile = new File(filemanagerstring);
if (myFile != null) {
Bitmap bmp_fromGallery = decodeImageFile(selectedImagePath);
break;
case CAMERA_REQUEST:
Bitmap bmp_Camera = (Bitmap) data.getExtras().get("data");
break;
default:
break;
}
}

Categories

Resources