File path for Sparsitiy Sparksee file/database - android

I am using Sparksee database, which requires to provide a path for the database file. Comparing it with sqlite, I simply wrote the filename without any path.
try
{ gdb = sparksee.create("filepath", "alias"); }
catch (FileNotFoundException e) {
{ e.printStackTrace(); }
It gives an FileNotFoundException on running.
java.io.FileNotFoundException: File cannot be created
The documentation/API does not specify any special path requirements, it simply says to provide a path for the file. I tried using the default database path :
/data/data/com.example.sparksee/databases/file
But it does not work as well.
What path should be provided in such a scenario?

I used this code to get a file path :
in Activity :
String path = this.getFileDirs().getPath();
in DatabaseCode :
gdb = sparksee.create(path + "/filepath", "alias");
The file was created in the /data/data/package/file/ folder. The application ran perfectly well without any hiccups.

Related

Kotlin: How to create/append file (and share)

I have a list of arrays of data in my app that I would now like to write to a file (csv) and use a 3rd party app (such as email) to share this csv file. I have had no luck finding any helpful resources for creating, finding the file path for, and appending to a file in Kotlin. Does anyone have experience with this or have examples to point to? Just to get started I'm trying to write the header and close the file so I can see that it is correctly writing.
This is what I have for now:
val HEADER = "ID, time, PSI1, PSI2, PSI3, speed1, speed2, temp1, temp2"
val filename = "export.csv"
var fileOutStream : FileOutputStream = openFileOutput(filename,Context.MODE_PRIVATE)
try {
fileOutStream.write(HEADER.toByteArray())
fileOutStream.close()
}catch(e: Exception){
Log.i("TAG", e.toString())
}
It doesn't throw the exception, but I cannot find the file in the file system. I'm using a physical tablet for testing/debug. I've checked the com.... folder for my app.
I cannot find the file in the file system
Use Android Studio's Device File Explorer and look in /data/data/.../files/, where ... is your application ID.
Also, you can write your code a bit more concisely as:
try {
PrintWriter(openFileOutput(filename,Context.MODE_PRIVATE)).use {
it.println(HEADER)
}
} catch(e: Exception) {
Log.e("TAG", e.toString())
}
use() will automatically close the PrintWriter, and PrintWriter gives you a more natural API for writing out text.
It appears there are many ways to create a file and append to it, depending on the minimum API version you are developing for. I am using minimum Android API 22. The code to create/append a file is below:
val HEADER = "DATE,NAME,AMOUNT_DUE,AMOUNT_PAID"
var filename = "export.csv"
var path = getExternalFilesDir(null) //get file directory for this package
//(Android/data/.../files | ... is your app package)
//create fileOut object
var fileOut = File(path, filename)
//delete any file object with path and filename that already exists
fileOut.delete()
//create a new file
fileOut.createNewFile()
//append the header and a newline
fileOut.appendText(HEADER)
fileOut.appendText("\n")
/*
write other data to file
*/
openFileOutput() creates a private file, likely inside of app storage. These files are not browsable by default. If you want to create a file that can be browsed to, you'll need the WRITE_EXTERNAL_STORAGE permission, and will want to create files into a directory such as is provided by getExternalFilesDir()

Android Studio: context.getFilesDir() returns a path [/data/user/0/com.example.filesexperimenting/files/] that I can not find. What am I missing?

I am trying to use Android's internal helpers to get a path from the system for my file first and then put my files where the system wants. Because tomorrow they might change their minds.
I made a simple program to explore this subject. Here is my code;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String path = letsMakeAfile(this, "myFile.txt");
}
private static String letsMakeAfile(Context context, String nameOfFile) {
String strOfFinalPath ="";
//ask the system what path to use...
String strOfContextPath = context.getFilesDir() + "/";
//line above doesnt work without ' + "/" ' or something on the end
//line above records this path: /data/user/0/com.example.filesexperimenting/files/
//this appears to be an invalid path unless "user" is a hidden directory
Log.d("IDIOT", "strOfContextPath: "+ strOfContextPath);
try
{
File file = new File(strOfContextPath, nameOfFile);
if (file.exists() == false) {
file.mkdirs();
//after this line "makes dirs" is file automatically still made and dropped in?
letsMakeAfile(context, nameOfFile);
//I assume not so Ive made a recursive call
}
else
;
//escape recursion....
strOfFinalPath = file.getAbsolutePath();
//Here I record the path where I hope the file is located
Log.d("IDIOT", "strOfFinalPath: "+ strOfFinalPath);
}
catch (Exception e) {
e.printStackTrace();
Log.d("IDIOT", "CATCH ERROR: "+ e.getLocalizedMessage());
}
//runs without a catch
return strOfFinalPath;
}
}
Logcat:
2019-04-09 09:59:22.901 16819-16819/? D/IDIOT: strOfContextPath: /data/user/0/com.example.filesexperimenting/files/
2019-04-09 09:59:22.901 16819-16819/? D/IDIOT: strOfFinalPath: /data/user/0/com.example.filesexperimenting/files
Ultimately I am getting a path of /data/user/0/com.example.filesexperimenting/files/ from context.getFilesDir() which appears to be an invalid path unless "user" is a hidden directory (then why can I see root?). In Device File Explorer under data the only other directories are app, data and local
What am I missing? I'll assume its something with file.makedirs()
Full disclosure, I am a student and there is not a lot out there on this so your replies, while obvious to you at your experience level, should help others. I have some experience with Java and more with C++ but Android is new to me. Thanks in advance!
So, in talking outside of StackExchange it appears that using java.io like I am trying to in the example can cause some problems because of the preset file directories that may be locked or restricted that Java io might not know about.
Android has it's own method openFileOutput(String name, int mode) that has the ability to create the app resource file and directory it belongs in.
Description copied from class: android.content.Context
Actions:
~Open a private file associated with this Context's application package for writing.
~Creates the file if it doesn't already exist.
~No additional permissions are required for the calling app to read or write the returned file.
Params:
~name – The name of the file to open; can not contain path separators.
~mode – Operating mode.
Returns: The resulting FileOutputStream.
Throws: java.io.FileNotFoundException
If you want to be able to navigate to the location of your saved files through the file explorer (either in Android Studio or the Files app on the phone) you should use Context.getExternalFilesDir().
Context.getFilesDir() returns a directory not accessible by anyone BUT the creating application. So if you would like to see what is in this file you would need to open it with the same application that wrote it. IE: Print the contents to the screen after you save it in your app.
Context.getExternalFilesDir() returns a directory completely accessible by anyone and any application. So files created and saved in this external directory can be seen by Android Studio's file explorer as the OP has screenshot or by any application installed on the phone.
What is nice about both of these methods is that as long as you are only accessing files you have created you never need to ask the user for storage permissions Read or Write. If you would like to write to someone else's external files dir then you do.
Source
Check if sdcard is mounted or not.
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)){
///mounted
}
Get the path of sd card
File dir= new File(android.os.Environment.getExternalStorageDirectory());
walkdir(dir);
ArrayList<String> filepath= new ArrayList<String>();
//list for storing all file paths
public void walkdir(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
// if its a directory need to get the files under that directory
walkdir(listFile[i]);
} else {
// add path of files to your arraylist for later use
//Do what ever u want
filepath.add( listFile[i].getAbsolutePath());
}
}
}
}
Try using this:
context.getFilesDir().getParentFile().getPath()

How to cache audio for offline use in Android Studio

I am developing an Android application in which I need to get the specified audio file from my website when the user plays it, but I don't want to stream it or download it every time, just the first time. So I was thinking of caching it and play offline whenever the user is in need. So please suggest any method to do so. Or if exists any other method rather than caching like downloading the actual file to file storage and play whenever needed.
If you need to cache files, you should use createTempFile(). For example, the following method extracts the file name from a URL and creates a file with that name in your app's internal cache directory:
private File getTempFile(Context context, String url) {
File file;
try {
String fileName = Uri.parse(url).getLastPathSegment();
file = File.createTempFile(fileName, null,
context.getCacheDir());
} catch (IOException e) {
// Error while creating file
}
return file;
}
You can also see here for more about caching files.
https://developer.android.com/training/data-storage/files.html#WriteCacheFileInternal
Hope this will help.

Android and LibGDX : create XML file in local storage

I want to check if in my /assets/game/ directory there is a file level.xml and if it does not exist I want to create it. I use this code:
private static void LoadXML() {
ProgressFileHandle = Gdx.files.local("game/level.xml");
if (!ProgressFileHandle.exists()) {
try {
ProgressFileHandle.file().createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
} else ProgressFileHandle.file().readString();
}
This code does not work, I get the error:
java.io.IOException: No such file or directory
it works if I change
Gdx.files.local("assets/game/level.xml");
to
Gdx.files.local("level.xml"); But I don't understand why. How can I create this file in a subdirectory (assets/game)?
I'm not clear if you're expecting to read from the standard assets folder that is packaged with your game. You should be using Gdx.files.internal() to read from there in that case, though that assets folder is always going to be read-only on Android.
If you want to create another directory called assets/ in the Libgdx "local storage" (which is equivalent to the Android internal storage) you will need to create the directories before you can create a file in the new directory. Just invoke .mkdirs() on the file handle to make sure all the required parent directories are created.
ProgressFileHandle.file().mkdirs();
ProgressFileHandle.file().createNewFile();

Display .mht file on android

How to display .mht(MHTML) file on android webview. I tried to open the .mht file on default android browser but that didn't open but i am able to open same on opera mobile browser. So i tried with MHTUnpack java library. I didn't succeed in that.
Here's a link!
Please if anybody has used this MHTUnpack let me how can i use that in android. And also let me know if there is any other library.
Thanks
Found this unknown google project which appears to be working.
This utility decodes the mhtml file and save it on given path(internal or external). After saving it returns the html file path which could be loaded into webview.
Try it.
After overcoming frustration about WebView.saveWebArchive() format change in Android 4.4, I tried the "unknown google project" Chitranshu Asthana mentioned in his answer, but code provided there is slow (~10s for 1MB *.mht file with a dozen of pictures) and doesn't handle attached file names correctly.
MHT Unpack library combined with Java Mail for Android (not the one provided by Oracle) worked perfectly for me.
EDIT: Fixed the link to MHT Unpack library. Also, here's usage example:
// contentPath - path to input .mht file
public static String unpackMht(String contentPath) throws IOException {
// dstPath - path where file will be unpacked
String dstPath = openTempDir(null) + File.separator;
String indexFileName = dstPath + new File(contentPath).getName();
try {
Collection<Attachment> attachments = MHTUnpack.unpack(new File(contentPath));
for (Attachment attachment : attachments) {
String filename = attachment.getFileName();
String path = filename == null ? indexFileName : dstPath + filename;
File newFile = new File(path);
if (newFile.exists()) {
newFile.delete();
}
attachment.saveFile(path);
}
return indexFileName;
} catch (MessagingException e) {
throw new IOException(e);
}
}

Categories

Resources