Checking if file exists in Kotlin without creating the file - android

Relevant answers checked but they don't exactly address my situation.
At the beginning of my application it is checked if a file exists by the code: someFile.exists(). However I found out that if the user navigates inside the app using menu items and back button the code behaves like someFile is created -although the app fragment to create and write into someFile is not triggered at all. I suppose this is because a File object is created by the system to run the exists() method, and this object causes someFile.exists() to return true in the next call.
How can I solve this?
Is there a bulletproof method to check if a sharedPreferences file exists or not?

Related

Android Studio: check where the file is created in code

I'm working on a complex Android Studio project, which creates many files and directories.
My question is: starting from a file or directory created, is there a command to search where the file is automatically created in the code?
E.g.: I have a textFiles/text.txt in emulator explorer... I want to find, starting from the file, where is the function createText() in the code that created the specifical file.
Press Ctrl + Shift + F and you will be able to search from whole project. In your case try to search createtext() or text.txt.
Make a complete search of mkdir() in whole solution, you will find the method where the directories are actually created. Then look for that methods usage for where its been called for creation of your specific file.(*Try debugging your code)
Hit the shift key 3 times and begin typing the file name.

Efficient implementation of File Explorer - Android

I'm creating a simple file explorer on Android Studio, and I wonder which one of the following implementations is the best:
My solution:
I have an activity called MainActivity that displays my list of files, and each time the user clicks on a directory, it creates a new MainActivity (and the onCreate method gets the new list of files, ...).
Correction:
In a correction from a tutorial, I found that when the user clicks on a directory, instead of starting a new activity, the code keeps the current one and changes everything (clear the list and fill it with new files, change the title...).
Is there a solution that is better than the other ? Is it more efficient to keep always the same activity ?
Thanks for any help.
Keep a single activity no question about it !
When a user clicks an item you build your data-source based on the newly selected path. Make sure to distinct between files and directories. Then simply call notifyDataSetChanged and thats it !
To query the file system there are two ways:
The easy - use Java File.listFiles()
The hard - run shell command Runtime.getRuntime().exec( "ls -la" ) and parse response.
There are many open source projects on github for the subject. Example:
Amaze File Manager

Migrate from getSharedPreferences(custom file) to getDefaultSharedPreferences()

When I originally wrote and published my app, I was using a custom written activity to handle application settings. I used custom file name to store shared preferfences, like this:
getSharedPreferences("custom_settings_file",MODE_PRIVATE);
But now I'm refactoring my app and I would like to implement PreferenceActivity or PreferenceFragment and an xml file with PreferenceScreen section. Every tutorial or example that I've seen is using
getDefaultSharedPreferences(context);
to retrieve shared preferences, because PreferenceActivity assumes default filename to store preferences and there's no way to tell it to use a different one(at least I couldn't find one after an hour of searching and reading documentation).
So now I have a problem. If I just simply use the new default file, existing users of my app will lose their settings when they update the app, because the new application will not know anything about "custom_settings_file". What would be the best way to move the data from an old file to a new one on app update?
Here are the possible options that I could come up with:
Extend Application class and implement a piece of code in onCreate() so that every time my app is launched, it would check for existence of "custom_settings_file" and move it's contents to the new one. But running a block of code on every app launch seems like wasting too much processing resources for an operation that only needs to run once.
Just notify the user that their old settings are gone. But obviously this is not acceptable.
Is there a better solution, than option 1? Perhaps someone has already faced a similar problem?
What is preventing you from doing number 1 only once?
Just add a "migration" boolean to the new sharedpreferences.
If you also load the xml preference file then you can try this:
PreferenceManager.setDefaultValues(context, YOUR_PREFERENCE_NAME, MODE_PRIVATE, R.xml.preference_file, false);
If not (you want to add each preference item dynamically in your code) then you can do like this:
PreferenceManager pm = getPreferenceManager();
pm.setSharedPreferencesMode(MODE_PRIVATE);
pm.setSharedPreferencesName(YOUR_PREFERENCE_NAME);
In case you still want to use the defaultSharedPreference and process the migration then ... I'm writing this and I see Nicklas's answer, so I'm done here.
Could you add value in your new SharedPreferences that records whether you are a new install or an upgrade. If you don't have the setting in your sharedpreferences, check to see if you have an old preferences file in the way you were before. Then convert those preferences to your new method, and set your private setting indicating that it's been upgraded. Then just set the new value indicating the new state and you won't need to check your old preferences any more.

Run application/activity at first time

I need to recognize first launch of my application or activity.
At this time I need to get some information from server create local database and save info to it. What is the best way to do this?
Create any preferences for example FirstLaunch and set true \ false to it.
Check whether my database exists or not.
Something else?
PS. All server calls must be into one transaction. Ormlite supports transactions?
Thanks.
For the "create database at first run"-purpose, you should use an SQLiteOpenHelper, which offers you the onCreate()-method that is called when:
[...] the database is created for the first time.
The Database-file itself will be created for you (you don't have to do this manually). In this method, you can then perform actions like populating your database with standard entry's.
If you want to populate the database with informations you get from your server, there might be a problem when there is no Internet-connection available.
In this case, I would check if there is a connection available:
If there is, get your informations.
If not, show a Toast or some other notification to inform the user.
To determine if your Database has be populated with the standard entry's, you can use the database-version which is also provided by the SQLiteDatabase-class:
When you first create your Database-object, you call
SQLiteOpenHelpers constructor and pass it 0 as the Database
version.
If you successfully populated your database, you use
setVersion()-method to alter it to 1.
Later in the onOpen()-method, which is called when the
database is opened, you can check if the database was populated by
using the getVersion()-method.
If it is populated, call the super-method to open it.
If not, try populating it.
Further more, the getReadableDatabase() / getWritableDatabase()-methods should be called off the main-thread anyways because:
Database upgrade may take a long time, you should not call this method
from the application main thread, including from
ContentProvider.onCreate().
So getting the informations from the Internet can take place in the onCreate() and in the onOpen()-method (if it wasn't successful at the first try). You can (for example) use a Service to do this.
If you want to solve this problem with database:
Create database with MyDatabasaVersion table and store your version in a single row, for example db_version default value is 0. First time when the application starts you check the db_version if 0 you need to start the syncronisation, after it is finishing set the db_version to 1.
The easiest way should be sharedpreferences. you can call it everywhere form the application context and you can put boolean values in it.
Here are all Android storages.
you should try first option Create any preferences for example FirstLaunch and set true \ false to it.

Android - Saving state of dynamically changed layout

I have a layout where users can add buttons and place them where they want.
I want to allow the user to save their layout so that it is loaded the next time they open the app.
Does anyone know if I can save the file on the sdcard? Alternatively I could use some kind of layout.getXml() method and put it in the database my app uses.
Thanks in advance
There is no file to save when you are generating a layout via code. You will have to create your own file format, which could be saved to the SD card or inserted into a database.
You can us savedInstaceState() method with the same type object as parameter .
there load the ui you want at the time of reloading.
In onCreate() method put a condition whethere that savedInstaceState obj is null or not . if not then call the LoadUI().
If I were you, I would create a class holding all the information about this layout and buttons. And write every information of the class to a file with JSONWriter. When the app has opened I just read the file and recreate the arrays using JSONObjects.

Categories

Resources