I have a service in my app which saves files, either in onStartCommand() or after finishing, in onDestroy(). In the onCreate() I am checking if my app's directory and its subdirectory exist and if they don't, I create the path. However, I found out that the exists() method actually creates the whole path or even part of it, if it doesn't already exist. After doing that, my app actually crashes and after launching it again, it works perfect.
I've also tried surrounding the exists() method with a try-catch block but the app still crashes, without throwing any exception. This problem seems to only appear in my old device with Android 9.0, because the app doesn't have this problem on my other device, which has Android 12(API 31).
So I am wondering why is this happening and what would be a way to prevent that crash.
The code in question is:
#Override
public void onCreate() {
//some other initializations...
File dir = new File(myDirectory); /*myDirectory is the full path to my app's directory, so:
/storage/emulated/0/directory/subdirectory */
if(!dir.exists()) {
try {
if(!dir.mkdirs()) {
//handle failure
}
} catch (Exception e) {
` //handle exception
}
}
}
exits: not create new folder
if(!dir.exists()){
dir.mkdirs();// create your folder
}
//update
Related
I have a GUI application written in JavaFX 14 (not the XML one). I currently have three lists that are connected each to a different custom class, in whom exists an ObservableList which updates the ListViews. I have three. Upon doubleclicking on an element of the first ListView, which also contains URLs, I want to open said URL inside the default browser, no matter the OS (I'm programming on Ubuntu 20.04, and this app will be used on W10 too).
listSquads.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
if(event.getClickCount()==2) {
try {
if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
Desktop.getDesktop().browse(new URI(bot.getSquadHandler().extractURL(listSquads.getSelectionModel().getSelectedItem())));
}
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
});
This is the code. The bot is a custom TwitchBot object, based on pIRCbot libraries. The squadHandler mentioned in the getter method is said custom class. Extract URL is a method that, as the name would suggest, extracts the exact URL given a string as input - this part works, as it's called upon in other parts of the code and works correctly, and I've also tested it.
However, upon double clicking on any given element of the ViewList, the app freezes to then crash a few seconds later. Why could that be? Is there a way to open the browser no matter the OS?
Thanks in advance! :)
I have a Unity Scene built with Cardboard SDK and exported as a library for Android. The library is used to play videos in cardboard mode on the android app. it's not the whole app, but a part in it. The rest of the android app is built with Kotlin and Java.
I have implemented that and all the functions work as expected, but, exiting the scene crashes the android.
We tried various ways to clear player prefs and even clear memory before closing the scene. But on android it always crashes. I have two android phones with android 9 and 10 for testing.
In the android app, I have made it such that as soon as the app crashes, I try to recover. My crash is that some lateinit var variables are destroyed. Their value becomes null and recovering the previous activity crashes it. So right after I exit the unity scene, I load the dereferenced variables back into memory and everything works again.
Note: I have tried using Application.Quit(); in unity, but it just closes the whole app. On the other hand, I only want to close the running scene
In unity [I call a function goBack in android part to close the app]:
public void GoToHome()
{
Pause();
Stop();
Resources.UnloadUnusedAssets();
PlayerPrefs.DeleteAll();
AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
jo.Call("goBack");
}
In App:
public void goBack()
{
UnityPlayer.currentActivity.finish();
finish();
loadDerereferencedVars();
}
This goes perfectly on android 9. On the other phone with android 10, after I close the scene, the app continues to function, but, there comes a message
When I click close app, the app continues to work.
I have checked the logs and there is a null pointer dereference cause for the crash in Unity Main >...
If you'd like to see the Unity Crash Log from LogCat in Android Studio
So, since the app is still running, I thought, it would be better to just hide the crash report and just let the user not know about this crash, but still report it.
I tried enclosing my app in Application and added a method to catch uncaughtException.
here is my application class:
public class MyApp extends Application {
private static final String TAG = "MyAPP";
#Override
public void onCreate() {
super.onCreate();
Thread.setDefaultUncaughtExceptionHandler(
new Thread.UncaughtExceptionHandler() {
#Override
public void uncaughtException (Thread thread, Throwable e) {
handleUncaughtException (thread, e);
}
});
}
/**
* Handles Uncaught Exceptions
*/
private void handleUncaughtException (Thread thread, Throwable e) {
// The following shows what I'd like, though it won't work like this.
Toast.makeText(getApplicationContext(), "Looks like I am having a bad day!", Toast.LENGTH_LONG).show();
Log.e("UncaughtException", "I found an exception!");
// Add some code logic if needed based on your requirement
}
}
Again, this works perfectly in Android 9 and I also got the error reported. However in the phone with android 10, I just get the crash report like the image above and no error is reported.
I want to know why the crash handling is not working and how can I fix it?
I would not finish the Activity you came from, instead just open a new intent (on UnityActivity). When you end this intent the app will come back to the last active Activity.
I will give you my script as an example:
public void sendJobToUnity(String fileName, boolean isNewJob){
//creates a new job. It exists inside the JobSelector Activity
isUnityLoaded = true;
//this is what you are looking for part1
Intent i = new Intent(JobSelector.this, MainUnityActivity.class); //same as (CurrentActivity.this, UnityActivity.this)
//those are how I send some data across the app. just ignore it
//i.putExtra("jobName", fileName);
//i.putExtra("isNewJob",isNewJob);
//i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivityForResult(i, 1); //this is what you are looking for part2
}
For closing it, in the MainUnityActivity Activity I have an override that Unity sends to Android in order to Unload the activity (not quit it completely cause you cannot load it again if you do it) like this:
#Override
protected void receiveJobAndUnloadUnity(String data){
saveCurrentJob(data); //saves the job it receives from Unity
mUnityPlayer.unload(); //this is what you are looking for part3
}
If you want to unload Unity from android you can put "mUnityPlayer.unload();" wherever you want, provided you have started the Activity the way I've shown you.
Note that "mUnityPlayer" is a default Unity variable and cannot be renamed
I'm working on a simple to-do list app, and I'm trying to read/write data from/to internal storage. I'm trying to understand when exactly those read/write methods should be called.
I know that the activity class has an onCreate() method which will be a reasonable location for my read method, but where should I call my write method?
I want to call it when the app closes/ends, so I'd assume onDestory() is a good location, but i heard that onDestroy() may not be a good location for data storage operations and i should use onStop().
Any help or ideas?
It depends on Application Lifecycle.
And see This.
onStop() invokes when user press home button(Hard Key).
And then, if memory insufficient or another reason, Android Memory Manager will kill your app instant and onDestory() will never called.
The best thing you have to is make a button to save datas. Of course, Include onStop() save routine.
Following the table in the Android Developers Guide on the Activity Lifecycle, your app may be killed by the system any time without warning after either onPause() (for Pre-HONEYCOMB devices) or after onStop(). So you probably want to write your data in these methods to make sure nothing gets lost. So for newer devices (API level 11 and up), onStop() should be fine. If your app should run on older devices as well, onPause() would be the best place.
This is Just sample code. But you get the idea. Create a custom method implementing the code below and call it on some events like "onClick" or any other.
File file;
FileOutputStream strem = null;
String line = "Hey this is my name";
try {
file = new File("sdcard/newFile.txt");
strem = new FileOutputStream(file);
byte[] bytes = line.getBytes();
strem.write(bytes);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
strem.close();
} catch (IOException e) {
e.printStackTrace();
}
}
I'm using Android4OpenCV to do some live image processing, and I'd like to use the smallest resolution the camera can offer. The default resolution is the largest the camera can offer.
I'm looking at the 3rd example, which allows the user to change resolutions via a menu. I'd like to modify that example to change the resolution at startup instead of requiring the user go through the menu. To do that, I simply add two lines to the otherwise empty onCameraViewStarted() function:
public void onCameraViewStarted(int width, int height) {
android.hardware.Camera.Size res = mOpenCvCameraView.getResolutionList().get(mOpenCvCameraView.getResolutionList().size()-1);
mOpenCvCameraView.setResolution(res);
}
And the thing is, this works perfectly fine on my Galaxy Nexus, running Android 4.2.2. The app starts up, and the resolution is set correctly.
However, when I run the exact same app on a Nexus 7 tablet, running Android 5.1, the app hangs on the call to setResolution(). Actually it works okay one time, but then hangs the second time you try to run it- even if you completely exit the app, remove it from the running apps, or restart the device. Other users are reporting the same error as well, so it's not just the Nexus 7 device- in fact, my Galaxy Nexus seems to be the only device where this works.
Specifically, the application goes into the setResolution() function, which then calls org.opencv.android.JavaCameraView.disconnectCamera(), which looks like this:
(Note: this code is internal to the OpenCV4Android library, this is not my code)
protected void disconnectCamera() {
/* 1. We need to stop thread which updating the frames
* 2. Stop camera and release it
*/
Log.d(TAG, "Disconnecting from camera");
try {
mStopThread = true;
Log.d(TAG, "Notify thread");
synchronized (this) {
this.notify();
}
Log.d(TAG, "Wating for thread");
if (mThread != null)
mThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
mThread = null;
}
/* Now release camera */
releaseCamera();
}
Looking at the logs, I can see that the thread gets stuck on the synchronized(this) line. The only other thing that synchronizes on that Object is the inner JavaCameraView.CameraWorker class, which is the mThread variable in the above code, started by the JavaCameraView class:
(Note: this code is internal to the OpenCV4Android library, this is not my code)
private class CameraWorker implements Runnable {
public void run() {
do {
synchronized (JavaCameraView.this) {
try {
JavaCameraView.this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (!mStopThread) {
if (!mFrameChain[mChainIdx].empty())
deliverAndDrawFrame(mCameraFrame[mChainIdx]);
mChainIdx = 1 - mChainIdx;
}
} while (!mStopThread);
Log.d(TAG, "Finish processing thread");
}
}
I've tried futzing with that code, changing the notify() to notifyAll(), and maintaining a List of CameraWorker threads and joining each one. But no matter what, the app still hangs at the disconnectCamera() call.
My questions are:
How can I modify the third OpenCV4Android example so that its resolution is set at startup?
What is causing the app to hang?
Why does this work on some devices but not others?
Edit: I haven't received any comments or answers, so I've crossposted to the OpenCV forums here.
Edit 2: As per cyriel's suggestion, I've tried setting the resolution after several frames have gone by:
int frames = 0;
public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
frames++;
if(frames == 6){
android.hardware.Camera.Size res = mOpenCvCameraView.getResolutionList().get(mOpenCvCameraView.getResolutionList().size()-1);
mOpenCvCameraView.setResolution(res);
}
return inputFrame.rgba();
}
However, now this gets stuck in the same exact place, even on my Galaxy Nexus, which works if I set the resolution in the onCameraViewStarted() function. I've tried increasing the frame count to 7 and even 100, but I always get stuck in the same place.
The most important question in your situation is whether it's working if you don't modify the code at all - are you able to change the resolution (via menu) without crashing the app?
If yes than the answer most likely is simple - it's the same bug in OpenCV as in Windows version: before changing camera resolution or fps (and most likely any property) you need to grab at least one (use 3-5 to be sure) frame before changing this property.
If no than most likely there is nothing you can do on your own - fill the bug report and wait for comments. The only alternative is to use other library to grab frames from camera and than convert it to OpenCV object.
My development phone is a Nexus 5, running Android 4.4.2.
In my application, I am attempting to create a folder on external storage that will store debug information for my application. Basically it will contain all the commands executed by the application, so that when a user encounters a problem, I have the option of having them send me the information from the debug folder to analyse.
I started off by trying to write a file to the folder, but found there was an error creating the folder. At first I was using mkdir(), then I moved onto mkdirs() which also didn't work.
I have <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> in my manifest.
Here is the code for creating the folder:
File folder = new File(Environment.getExternalStorageDirectory() + "/DebugData");
String path = folder.getPath();
if(!folder.mkdirs() || !folder.exists()){
Log.e(LOG_TAG, path + " failed");
} else {
Log.d(LOG_TAG, path + " succeeded");
}
Here is what I have also tried:
//Check SD card state
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state) || !Environment.MEDIA_MOUNTED.equals(state)) {
Log.e(LOG_TAG, "Error: external storage is read only or unavailable");
} else {
Log.d(LOG_TAG, "External storage is not read only or unavailable");
}
This returns that the external storage is not read only or unavailable.
I have also tried different paths, such as File folder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Folder1");
This is where it became really confusing.
I tried development on different phones. Firstly, I grabbed a Galaxy S4 GT-i9505 running Android 4.2.2 and it worked. I was able to create the folders and write to them. This showed me that the code was working. Also the path returned by running the code on the S4 and Nexus 5 was the same.
Then I thought it may be android version specific. So I grabbed a Nexus 4 with Android 4.4.2 and the code worked on it as well. Created the folders and allowed me to write to them.
None of the phones are rooted and are all stock standard. There's no special applications or anything I can think of settings wise on the Nexus 5 that would cause permissions problems. The connection is set to Media Device (MTP).
EDIT:
I should add that I have tried the follow which also did not work:
Writing a file to the root directory of the external storage
Creating the file in the external storage root directory and writing to it
Creating a folder in a path outlined and writing a file to it
Creating the file in the path outlined and writing to it
I am confused as to what is causing this, is there anything else I can test or change to fix the issue?
EDIT 2:
Turns out the issue was due to, I think, indexing.
Basically all of the other devices I tested on, allowed me to reconnect the USB connection and view the created files and folders.
For some reason my Nexus 5 doesn't index the folders/files, even though they exist.
I downloaded a different 3rd party file explorer application and noticed all the folders and files were there.
So to view these folders and files via USB debugging, I have to restart the phone in order to re-index them, which seems quite annoying but it is better than it not working at all.
Thanks.
In terms of this being an indexing issue with the Nexus, this worked for me:
MediaScannerConnection.scanFile(this, new String[] { file.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
You should call it straight after creating and saving the file. By using the scanner, I was able to see newly created files and directories simply by replugging the device in.
According to the docs:
MediaScannerConnection provides a way for applications to pass a newly
created or downloaded media file to the media scanner service. The
media scanner service will read metadata from the file and add the
file to the media content provider.
Hope this helps someone else.
Turns out the issue was due to, I think, indexing.
Basically all of the other devices I tested on, allowed me to reconnect the USB connection and view the created files and folders.
For some reason my Nexus 5 doesn't index the folders/files, even though they exist.
I downloaded a different 3rd party file explorer application and noticed all the folders and files were there.
So to view these folders and files via USB debugging, I have to restart the phone in order to re-index them, which seems quite annoying but it is better than it not working at all.
For android sdk version 23 and above you should check if the user has granted permission of external storage.
private void createFolder() {
if (isStoragePermissionGranted()) {
File folder = new File(Environment.getExternalStorageDirectory()+ File.separator + "DebugData");
if(!folder.exists()){
folder.mkdir();
}
}
public boolean isStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
return true;
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
return true;
}
}
The code above worked for me and I hope it will work for you.
Had the same problem. Turned out I was testing on Android 6 and did not check for runtime WRITE_EXTERNAL_STORAGE permission.
First, new File() is just create object for file connect.
you want use this file, file is exists or createNewFile().
If you want use this file to create directory, check file is exists, isDirectory() after then mkDir().
Second, check Environment.getExternalStorageDirectory is variable path.
You can use DDMS or ADB for work.
Additionaly, I think you add permission for read external storage for something error.
If you are running an Android device with api >= 23, you need to request permission from user before you call mkdir() function.
My previous answer with example code can be found
https://stackoverflow.com/a/38694026/5089713
For Android 10+ add following into manifest:
<application
android:requestLegacyExternalStorage="true"
...
as asking for Manifest.permission.WRITE_EXTERNAL_STORAGE is no more enough.
Typically, I do this:
/**
* Return a dedicated directory named "MyApp" at the top of external storage
*/
public static file getDataDir() {
File sdcard = Environment.getExternalStorageDirectory();
if( sdcard == null || !sdcard.isDirectory() ) {
// TODO: warning popup
Log.w(TAG, "Storage card not found " + sdcard);
return null;
}
File dataDir = new File(sdcard, "MyApp");
if( !confirmDir(dataDir) ) {
// TODO: warning popup
Log.e(TAG, "Unable to create " + dataDir);
return null;
}
return dataDir;
}
private static boolean confirmDir(File dir) {
if (dir.isDirectory()) return true; // already exists
if (dir.exists()) return false; // already exists, but is not a directory
return dir.mkdirs(); // create it
}
Also, add this permission to your manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
If you want private storage (typically under /data/) for your app (not on sdcard), then look into getDir(), getFilesDir(), fileList(), openFileInput(), openFileOutput(), etc.
There are also helper functions to get private directories within the sdcard for API 8 and above: getExternalFilesDir(), getExternalCacheDir(), etc.