I've written an application which should take a picture and then show it on the screen for modifications.
When trying it on the eclipse emulator the camera won't work, so I'm trying it on my Galaxy Nexus Smart Phone.
Nevertheless when running it on my SP the application will crash saying that it unfortunally stopped working.
When executing the app this is what exactly happens:
I click on the camera button and the camera interface gets opened
After taking the picture it gives me the choice to discard it or open it
If I click on discard the application returns to normal usage
If I click on open the application crashes as mentioned above
I googled a little and found out that you need permissions to use hardware devices check here, so I created the file /etc/udev/rules.d/51-android.rules and this is its content:
SUBSYSTEM=="USB", ATTR{IDVENDOR}=="18d1", MODE="0666, "GROUP="plugdev"
SUBSYSTEM=="USB", ATTR{IDVENDOR}=="04e8", MODE="0666, "GROUP="plugdev"
SUBSYSTEM=="USB", ATTR{IDVENDOR}=="0bb4", MODE="0666, "GROUP="plugdev"
But still I won't be able to use camera.
Here are the permissions I declared in my manifest file:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
Here is the code I use to launch the camera intent:
//create new Intent
Intent cameraIntent = new Intent( android.provider.MediaStore.ACTION_IMAGE_CAPTURE );
//get something back from the activity we are starting
startActivityForResult( cameraIntent, CAMERA_PICTURE_REQUEST );
And this is the code for processing the result:
public void onActivityResult( int requestCode, int resultCode, Intent imageReturnedIntent )
{
if( resultCode == RESULT_OK )
{
if( requestCode == GALLERY_PICTURE_REQUEST )
{
selectedImageUri = imageReturnedIntent.getData();
Log.d( TAG, selectedImageUri );
Intent intent = new Intent( DVAHLUI_SuperviseActivity.this, DVAHLUI_SelectImageContentActivity.class );
intent.setData( selectedImageUri );
startActivity( intent );
}
if( requestCode == CAMERA_PICTURE_REQUEST )
{
selectedImageUri = imageReturnedIntent.getData();
Log.d( TAG, selectedImageUri );
Intent intent = new Intent( DVAHLUI_SuperviseActivity.this, DVAHLUI_SelectImageContentActivity.class );
intent.setData( selectedImageUri );
startActivity( intent );
}
}
}
This is the getPath() function causing the Java Null pointer exception:
public String getPath( Uri uri )
{
String[] filePathColumn = { android.provider.MediaStore.Images.Media.DATA };
LINE 343 --> Cursor cursor = getContentResolver().query( uri, filePathColumn, null, null, null );
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndexOrThrow( filePathColumn[0] );
String filePath = cursor.getString( columnIndex );
cursor.close();
return filePath;
}
Can you please tell me what's going wrong?
FOGOT TO POST LOGCAT:
E/AndroidRuntime(27859): FATAL EXCEPTION: main
E/AndroidRuntime(27859): java.lang.RuntimeException: Failure delivering result ResultInfo{who=supervise, request=1, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.DVA_HLUI/com.DVA_HLUI.DVAHLUI_TabModeActivity}: java.lang.NullPointerException
E/AndroidRuntime(27859): at android.app.ActivityThread.deliverResults(ActivityThread.java:3141)
E/AndroidRuntime(27859): at android.app.ActivityThread.handleSendResult(ActivityThread.java:3184)
E/AndroidRuntime(27859): at android.app.ActivityThread.access$1100(ActivityThread.java:130)
E/AndroidRuntime(27859): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1243)
E/AndroidRuntime(27859): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(27859): at android.os.Looper.loop(Looper.java:137) E/AndroidRuntime(27859): at android.app.ActivityThread.main(ActivityThread.java:4745)
E/AndroidRuntime(27859): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(27859): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(27859): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
E/AndroidRuntime(27859): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
E/AndroidRuntime(27859): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(27859): Caused by: java.lang.NullPointerException
E/AndroidRuntime(27859): at android.content.ContentResolver.acquireUnstableProvider(ContentResolver.java:1094)
E/AndroidRuntime(27859): at android.content.ContentResolver.query(ContentResolver.java:354)
E/AndroidRuntime(27859): at android.content.ContentResolver.query(ContentResolver.java:313)
E/AndroidRuntime(27859): at com.DVA_HLUI.DVAHLUI_SuperviseActivity.getPath(DVAHLUI_SuperviseActivity.java:343)
E/AndroidRuntime(27859): at com.DVA_HLUI.DVAHLUI_SuperviseActivity.onActivityResult(DVAHLUI_SuperviseActivity.java:312)
E/AndroidRuntime(27859): at android.app.ActivityGroup.dispatchActivityResult(ActivityGroup.java:122)
E/AndroidRuntime(27859): at android.app.ActivityThread.deliverResults(ActivityThread.java:3137)
E/AndroidRuntime(27859): ... 11 more
It sounds and looks like your not allowing the system to update itself that a new media file has been created. Thats why your method is failing. You can either manully create the image file path so you have the images location on the file tree or you can call for the media service to run an update. I always create my own filepath as older phones take longer to update using the media service and so your method in that case would fail.
Apparently this crash is due to a known Samsung problem: it seems like you need to create a Uri before calling the camera intent, in this way when running the onActivityResult method
the content provider will allready have allocated the place where to save the resource.
For further information check the following:
My Android camera Uri is returning a null value, but the Samsung fix is in place, help?
Android: startActivityForResult always null and force close my app
wordpress link
Android Samsung: Camera app won't return intent.getData()
and many more by googling...
P.S. as soon as possible I'll post the solution that worked for me.
I know it is late to answer it but asap i found the answer i replied for it so please atleast review it .
AndroidCameraUtil could be nice and easy solution for each and every device below is the code snippet you can use with the library
private void setupCameraIntentHelper() {
mCameraIntentHelper = new CameraIntentHelper(this, new CameraIntentHelperCallback() {
#Override
public void onPhotoUriFound(Date dateCameraIntentStarted, Uri photoUri, int rotateXDegrees) {
messageView.setText(getString(R.string.activity_camera_intent_photo_uri_found) + photoUri.toString());
Bitmap photo = BitmapHelper.readBitmap(CameraIntentActivity.this, photoUri);
if (photo != null) {
photo = BitmapHelper.shrinkBitmap(photo, 300, rotateXDegrees);
ImageView imageView = (ImageView) findViewById(de.ecotastic.android.camerautil.sample.R.id.activity_camera_intent_image_view);
imageView.setImageBitmap(photo);
}
}
#Override
public void deletePhotoWithUri(Uri photoUri) {
BitmapHelper.deleteImageWithUriIfExists(photoUri, CameraIntentActivity.this);
}
#Override
public void onSdCardNotMounted() {
Toast.makeText(getApplicationContext(), getString(R.string.error_sd_card_not_mounted), Toast.LENGTH_LONG).show();
}
#Override
public void onCanceled() {
Toast.makeText(getApplicationContext(), getString(R.string.warning_camera_intent_canceled), Toast.LENGTH_LONG).show();
}
#Override
public void onCouldNotTakePhoto() {
Toast.makeText(getApplicationContext(), getString(R.string.error_could_not_take_photo), Toast.LENGTH_LONG).show();
}
#Override
public void onPhotoUriNotFound() {
messageView.setText(getString(R.string.activity_camera_intent_photo_uri_not_found));
}
#Override
public void logException(Exception e) {
Toast.makeText(getApplicationContext(), getString(R.string.error_sth_went_wrong), Toast.LENGTH_LONG).show();
Log.d(getClass().getName(), e.getMessage());
}
});
}
#Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
mCameraIntentHelper.onSaveInstanceState(savedInstanceState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mCameraIntentHelper.onRestoreInstanceState(savedInstanceState);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
mCameraIntentHelper.onActivityResult(requestCode, resultCode, intent);
}
}
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I have an app and I need to take photos and then upload it to firebase. I basically need Uri path of the photo taken.
I read Get file path of image on Android, but I have a problem with NullPointerException.
Main difference between my problem and the problem above is that I'm doing it in a Fragment.
Here is my code:
mTakePhotoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
I get NullPointerException in line with Uri imgUri.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
mImgView.setImageBitmap(photo);
Uri imgUri = getImageUri(getActivity().getApplicationContext(), photo);
mManager.setPhotoUri(imgUri);
}
}
And here is the method I use to get Uri.
private Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
The exact error message is:
java.lang.RuntimeException: Failure delivering result
ResultInfo{who=android:fragment:1, request=22222, result=-1,
data=Intent { act=inline-data (has extras) }} to activity
{.MainActivity}:
java.lang.NullPointerException: uriString
I would appreciate any help.
The entire error log:
09-14 12:06:18.448 16497-16497/com.example.radzik.recipes E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.radzik.recipes, PID: 16497
java.lang.RuntimeException: Failure delivering result ResultInfo{who=android:fragment:1, request=22222, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.example.radzik.recipes/com.example.radzik.recipes.activity.MainActivity}: java.lang.NullPointerException: uriString
at android.app.ActivityThread.deliverResults(ActivityThread.java:3699)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3742)
at android.app.ActivityThread.-wrap16(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1393)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: uriString
at android.net.Uri$StringUri.(Uri.java:475)
at android.net.Uri$StringUri.(Uri.java)
at android.net.Uri.parse(Uri.java:437)
at com.example.radzik.recipes.fragment.ChoosePhotoFragment.getImageUri(ChoosePhotoFragment.java:144)
at com.example.radzik.recipes.fragment.ChoosePhotoFragment.onActivityResult(ChoosePhotoFragment.java:135)
at android.app.Activity.dispatchActivityResult(Activity.java:6452)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3695)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3742)
at android.app.ActivityThread.-wrap16(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1393)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Your problem is with getActivity() becasue you are getting the intent of the current activity you were on which will fail.
So if you move your code to the OnActivityResult this will make it work.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//first call super
super.onActivityResult(requestCode, resultCode, data);
//rest of your code
}
Don't forget to add
<uses-permission android:name="android.permission.CAMERA" />
and/or without depends on your app
<uses-feature android:name="android.hardware.camera" />
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.
So basically I want the app to: after pressing a button opens the gallery, the user selects one image and after that saves the uri in a variable. That's all it needs to do but what I found is that after calling startActivityForResult() subsequent code still runs in the background creating a NullPointerException error, since the variable I wanted has not yet been retrieved from the intent.
public class MainActivity extends AppCompatActivity {
final static int PICK_IMAGE_REQUEST = 1;
private String imageUriStr;
SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prefs = this.getSharedPreferences("MyPreferences",MODE_PRIVATE);
ImageView addImgButton = (ImageView) findViewById(R.id.add_img_button);
addImgButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
if (prefs.contains(imageUriStr)) {
imageUriStr = prefs.getString("imageUriStr", ""); //Get the data from prefs
}
Log.d("Value",imageUriStr); //verify if it is correct
prefs.edit().clear();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
imageUriStr = data.getData().toString(); //convert to string to use it with SharedPreferences
prefs.edit().putString("imageUriStr",imageUriStr).apply();
}
}
}
One solution would be to do everything inside the onActivityresult, but I also want to later user another intent to crop the image based on that uri, but I think an Intent inside an onActivityresult will be too messy or is it acceptable? I guess I'm missing something.
Keeping with my code will generate this
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.prototypeapp, PID: 17826
java.lang.NullPointerException: println needs a message
at android.util.Log.println_native(Native Method)
at android.util.Log.d(Log.java:154)
at com.example.android.prototypeapp.MainActivity$1$override.onClick(MainActivity.java:41)
at com.example.android.prototypeapp.MainActivity$1$override.access$dispatch(MainActivity.java)
at com.example.android.prototypeapp.MainActivity$1.onClick(MainActivity.java:0)
at android.view.View.performClick(View.java:5264)
at android.view.View$PerformClick.run(View.java:21297)
at android.os.Handler.handleCallback(Handler.java:743)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:150)
at android.app.ActivityThread.main(ActivityThread.java:5546)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:794)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:684)
Your private String imageUriStr; is null.Since it is null you are getting null pointer exception. Assign it with the empty string like : private String imageUriStr = "";.
AND
Check in shared preference like :
if(prefs.contains("imageUriStr"))
Your Code is crashing on this line:
Log.d("Value",imageUriStr);
Reason: imageUriStr value is null and a valid message is required to print the log
You can either use Log as :
Log.d("Value","Image URI Value: "+imageUriStr);
or you can put your Log inside if block like:
if (prefs.contains(imageUriStr)) {
imageUriStr = prefs.getString("imageUriStr", "");//Get the data from prefs
Log.d("Value",imageUriStr); //verify if it is correct
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I need an independent QR scanner in my app, so I've added the zxing library to my Android app - I've followed this link - I added the dependencies in build.gradle, and this is how I call the method:
btnScanQR.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new IntentIntegrator(MainScreenActivity.this).initiateScan(); // `this` is the current Activity
}
});
// Get the results:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if(result != null) {
if(result.getContents() == null) {
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
So it's basically exactly like on their github page, so there shouldn't be any problems, right?
However, I get this error when I try to open the scanner through my app, and I can't seem to find any solutions online to this exact problem:
CameraInstance: Configuring camera
W/CameraManager: Failed to set rotation.
W/CameraManager: Camera rejected even safe-mode parameters! No configuration
E/CameraInstance: Failed to configure camera
java.lang.NullPointerException: Attempt to invoke virtual method 'android.hardware.Camera$Parameters android.hardware.Camera.getParameters()' on a null object reference
at com.journeyapps.barcodescanner.camera.CameraManager.setParameters(CameraManager.java:353)
at com.journeyapps.barcodescanner.camera.CameraManager.configure(CameraManager.java:139)
at com.journeyapps.barcodescanner.camera.CameraInstance$4.run(CameraInstance.java:171)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.os.HandlerThread.run(HandlerThread.java:61)
D/CameraPreview: pause()
D/CameraInstance: Closing camera
D/CameraPreview: pause()
What is the cause of this (is it because it fails to rotate?) and how could I fix this? I've tried changing the orientation like it says on zxings github page with this:
<activity
android:name="com.journeyapps.barcodescanner.CaptureActivity"
android:screenOrientation="fullSensor"
tools:replace="screenOrientation" />
IntentIntegrator integrator = new IntentIntegrator(this);
integrator.setOrientationLocked(false);
integrator.initiateScan();
But I keep getting the same error! Please help :(
Following two reasons for this error:
1) You have not initialized camera:
mcamera = mcamera.open();
2) You have not given permissions in androidmanifest.xml file.
<uses-permission android:name="android.permission.CAMERA"/>
I'm performing file viewing operation as follows:
private void openFile(File file, String format) {
try {
if (file.exists()) {
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
String mimeType = "*/*";
if (format.length() > 0) {
mimeType = MimeTypeMap.getSingleton()
.getMimeTypeFromExtension(format);
if (mimeType == null)
mimeType = "*/*";
} else
mimeType = "*/*";
intent.setDataAndType(path, mimeType);
try {
startActivity(intent);
} catch (Exception e) {
Toast.makeText(LoginSuccessActivity.this,
constants.Error_NoCompatibleApp, Toast.LENGTH_SHORT)
.show();
e.printStackTrace();
}
} else {
Toast.makeText(LoginSuccessActivity.this,
constants.Error_DocNotFound, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
This is working fine, as I get app chooser pop-up for the filetypes which has multiple apps related to it(for eg. kingsoft office and polaris office for word file) OR directly file is opened for the filetypes which has only one app related to it(HTMLViewer for html file).
What I don't understand is my main activity is getting destroyed in few moments after calling file viewer activity. I've checked this by placing logs in onPause(), onStop() and onDestroy(). So, after file viewing is done, when I press back key, instead of taking back to app, it navigated to main menu.
I tried with startActivityForResult(intent, 1); instead of startActivity(intent); hoping that it'll preserve my main activity as it'll be waiting for result, but to no avail.
Please note that I've added android:configChanges="orientation|screenSize" in manifest file and
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
in java file.
Am I doing anything wrong?
Any help appreciated.
Sometimes, mind you, "Sometimes", I get follwing messages on log:
file:// Uri exposed through Intent.getData()
java.lang.Throwable: file:// Uri exposed through Intent.getData()
at android.os.StrictMode.onFileUriExposed(StrictMode.java:1597)
at android.net.Uri.checkFileUriExposed(Uri.java:2338)
at android.content.Intent.prepareToLeaveProcess(Intent.java:7194)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1418)
at android.app.Activity.startActivityForResult(Activity.java:3423)
at android.app.Activity.startActivityForResult(Activity.java:3384)
at android.app.Activity.startActivity(Activity.java:3626)
at android.app.Activity.startActivity(Activity.java:3594)
at com.android.internal.app.ResolverActivity.onIntentSelected(ResolverActivity.java:407)
at com.android.internal.app.ResolverActivity.startSelected(ResolverActivity.java:299)
at com.android.internal.app.ResolverActivity.onButtonClick(ResolverActivity.java:289)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3809)
at android.view.View.performClick(View.java:4424)
at android.view.View$PerformClick.run(View.java:18383)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4998)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
at dalvik.system.NativeStart.main(Native Method)
Add these lines to your Intent and try to Start Activity,
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setType(Your_MimeType);
I m using this code in my App
String MimeType = URLConnection.guessContentTypeFromName(myFile.getAbsolutePath());
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setType(MimeType);
Uri uri_path = Uri.fromFile(myFile);
intent.setDataAndType(uri_path, MimeType);
try
{
_context.startActivity(intent);
}
catch(ActivityNotFoundException e)
{
Toast.makeText(_context,"Activity Not Found..", Toast.LENGTH_SHORT).show();
}
Refer this link also for better understanding
Hope it will help you.
Activity can get destroyed any time. If someone has some data to retain one can do as follows:
class MyActivity {
private String mMyString;
public void onSaveInstanceState(Bundle b) {
b.putString("MYDATA", mMyString);
super.onSaveInstanceState(b);
}
public void onCreate(Bundle savedState) {
super.onCreate(savedState)
if(savedState != null) {
mMyString = savedState.getString("MYDATA");
}
}
You can this way create your own subclass private static class State implements Serializable and save it in onSaveInstanceState()