I'm trying to read the text file in cordova. For this I've created a assets folder (See the cordova folder structure image) and placed my text file in that but i'm getting the error java.io.FileNotFoundException: json.txt.
Note:
When i tried it in the Android native I'm able to read the file...
Code
String yourData = LoadData("json.txt");
public String LoadData(String inFile) {
String tContents = "";
try {
InputStream stream = context.getAssets().open(inFile);
int size = stream.available();
byte[] buffer = new byte[size];
stream.read(buffer);
stream.close();
tContents = new String(buffer);
} catch (IOException e) {
e.printStackTrace();
Log.e("catch", e + "");
}
return tContents;
}
Cordova folder structure
Am i placing assets folder in the wrong position or am i doing any other mistake?
Actual problem was, haven't mentioned assets folder in plugin.xml. After mentioning it everything working fine
plugin.xml entry
<source-file src="json.txt" target-dir="assets"/>
and use same method and structure which is in the question
Well as i got to know Cordova access your file as a relative path. and it will assume you're using the www directory.
so if you want to access your file you can do like this below in Cordova plugin -
window.resolveLocalFileSystemURI("file:///android_asset/www/json.txt", onResolveSuccess, onFail);
your file path will become something like this -
file:///android_asset/www/json.txt"
Related
I have to export files from my application and looking for a solution, where I can save files, to give the user the possibility to open them.
I tried already getFilesDir().getPath() which worked well, until I realized that the folder can't open from a real device (/data/user/0/com.myapplication.example/files) since the /data path is just a storage area for the application.
What are the alternatives?
You should have a look here https://developer.android.com/training/data-storage
I'm not sure what file type you are trying to store however what you have tried stores the file withing the applications directory and not the devices. To combat this I would look under either Media or Documents and other files again in the above link. I would be able to be of further assistance if I knew what file type you are trying to store. Hope this helps you in some way.
This is a function to store a float array to the phone external storage. Pass the file name.extension in the String name. You could modify it to export your file.
public static void save(float[] input_array, String name)
{
final String TAG2 = "->save()";
String string_array = Arrays.toString(input_array);
String fullName = Environment.getExternalStorageDirectory().getPath() + "/SercanFolder/" + name;
String path = Environment.getExternalStorageDirectory().getPath() + "/SercanFolder";
File folder = new File(path);
if(!folder.exists())
{
folder.mkdirs();
}
BufferedWriter buf;
try
{
buf = new BufferedWriter(new FileWriter(fullName));
buf.write(string_array,0,string_array.length());
buf.close();
Log.d(TAG+TAG2, "array saved as document. ");
}
catch (IOException e)
{
Log.e(TAG+TAG2, "problems while saving the file. ");
}
}
The suggestion with getExternalStorage().getPath() (Thanks to blackapps) helped me to save the pdf in a folder, which can be opened in the file manager.
I'm using the openFileOutput() to create a new txt file. I need the file to be visible from other applications (as well as from a PC when the Android device is connected via USB. Ive tried using .setReadable(true); but this does not seem valid. Please advise how I should declare the file is visible / public.
try {
textIncoming.append("saving");
final String STORETEXT = "test.txt";
OutputStreamWriter out = new OutputStreamWriter(openFileOutput(STORETEXT, 0));
out.setReadable(true);
out.write("testing");
out.close();
}
catch (Throwable t) {
textIncoming.append("not saving");
}
Ive changed my program to use getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), but for some reason it returns a path /storage/emulated/0/Documents, and I cant even find this folder on the device. Ive looked at the files on the android device using ES file explorer but cant find the folder or file I'm trying to create (Plus I want these in an documents folder on the SD card, so it seems that its not giving me a pointer to the SD card at all, and not creating the folder, and not creating the file. Following is my updated code, please advise
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).toString();
File myDir = new File(root + "/Saved_Receipts");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "DRcpt-" + n + ".xml";
textIncoming.append(root);
File file = new File(myDir, fname);
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
out.flush();
out.close();
}
catch (Exception e) {
e.printStackTrace();
}
Save it to sdcard if you want anyone to be able to read it.
This android documentation should tell you what you need to do.
https://developer.android.com/guide/topics/data/data-storage.html#filesExternal
openFileOutput() documentation says:
Open a private file
So the file that it creates won't be visible to other apps, unless you copy it to another directory that is visible. In that case, you have to save your data in what's called "external storage" which is shared with other apps. Use the code at this link.
I have saved a file with .docx extension in my app.the file is saved in the sdcard. The file appears as a word file in my sdcard but I am unable to open it (using polaris or any other default software) and message"unsupported file" appears.
When I save the file with .txt extension, I can open it.
public void Savedoc(View v)
{
String filename = "file" + sn + ".docx";
String filepath = "MyFileStorage";
myExternalFile = new File(getExternalFilesDir(filepath), filename);
try {
FileOutputStream fos = new FileOutputStream(myExternalFile);
fos.write(ly.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
thank you alexandru ...but now i get an error message on running the app stating "The Javadoc for this element could neither be found in the attached source nor the attached Javadoc".pls help...
You'll need to use Apache POI in order to correctly create a .docx file.
I've found this answer with a code snippet:
XWPFDocument document = new XWPFDocument();
XWPFParagraph tmpParagraph = document.createParagraph();
XWPFRun tmpRun = tmpParagraph.createRun();
tmpRun.setText("LALALALAALALAAAA");
tmpRun.setFontSize(18);
document.write(new FileOutputStream(new File("yourpathhere")));
You may find more information about how to use XWPF here.
We are trying to create a mobile app using PhoneGap/Cordova. We need to ship this app with a pre-populated SQLite db. We are able to copy the DB using below code. But when we try to access tables from copied DB in our App we get 'No Such Table' error. Can anyone help us in identifying the cause ?
We copied the database using the below code to data/data/package_name/databases folder.
try
{
File dbFile = getDatabasePath("Bee_dict.db");
if(!dbFile.exists()){
this.copy("Bee_dict.db",dbFile.getAbsolutePath());
}
}
catch (Exception e)
{
e.printStackTrace();
}
//And our copy function:
void copy(String file, String folder) throws IOException
{
File CheckDirectory;
CheckDirectory = new File(folder);
String parentPath = CheckDirectory.getParent();
File filedir = new File(parentPath);
if (!filedir.exists()) {
if (!filedir.mkdirs()) {
return;
}
}
InputStream in = this.getApplicationContext().getAssets().open(file);
File newfile = new File(folder);
OutputStream out = new FileOutputStream(newfile);
byte[] buf = new byte[1024];
int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len);
in.close(); out.close();
}
index.html
The below code is used to open and access the DB
function onDeviceReady()
{
db = window.openDatabase("Bee_dict", "1.0", "Bee_dict", 20000);
tx.executeSql('SELECT * FROM data WHERE word_id = ?', [1], querySuccess_definition, errorCB);
}
Cordova version - 2.9
Thanks.
In first place, can trying with the next DB file name:
0000000000000001.db
And for load file:
File dbFile = getDatabasePath(".0000000000000001db");
The DB file needs to be in the next route:
yourProyect/assets/0000000000000001.db
I recommend use "SQLitePlugin":
SQLitePlugin GitHub
In the "onDeviceReady()" function i use:
if(!dbCreated){
db = window.sqlitePlugin.openDatabase("0000000000000001", "1.0", "My Database", -1);
}
I faced the same problem, but the answer above does not help me, so I am writing my experience, it may help.
I typically used a Cordova plugin named: me.rahul.plugins.sqlDB at https://github.com/an-rahulpandey/cordova-plugin-dbcopy
It is a plugin focused to copy files from Cordova www folder to the right folder on Android/iphone.
You have first to install the plugin, using:
$ cordova plugin add https://github.com/an-rahulpandey/cordova-plugin-dbcopy.git
Then on Device Ready event:
function onDeviceReady() {
console.log(">device is ready");
window.plugins.sqlDB.copy("mydb.sqlite", copySuccess, copyError);
}
To access pre-populated database you should first copy the database file in www directory.
Install this plugin DB-Copy plugin and copy the database from www directory into the device, using the copy plugin and then use Sqlite-storage plugin to access the database.
PS. The copy of database from www directory is need it because each OS has different location to store databases...
In J2ME, I've do this like that:
getClass().getResourceAsStream("/raw_resources.dat");
But in android, I always get null on this, why?
For raw files, you should consider creating a raw folder inside res directory and then call getResources().openRawResource(resourceName) from your activity.
InputStream raw = context.getAssets().open("filename.ext");
Reader is = new BufferedReader(new InputStreamReader(raw, "UTF8"));
In some situations we have to get image from drawable or raw folder using image name instead if generated id
// Image View Object
mIv = (ImageView) findViewById(R.id.xidIma);
// create context Object for to Fetch image from resourse
Context mContext=getApplicationContext();
// getResources().getIdentifier("image_name","res_folder_name", package_name);
// find out below example
int i = mContext.getResources().getIdentifier("ic_launcher","raw", mContext.getPackageName());
// now we will get contsant id for that image
mIv.setBackgroundResource(i);
Android access to raw resources
An advance approach is using Kotlin Extension function
fun Context.getRawInput(#RawRes resourceId: Int): InputStream {
return resources.openRawResource(resourceId)
}
One more interesting thing is extension function use that is defined in Closeable scope
For example you can work with input stream in elegant way without handling Exceptions and memory managing
fun Context.readRaw(#RawRes resourceId: Int): String {
return resources.openRawResource(resourceId).bufferedReader(Charsets.UTF_8).use { it.readText() }
}
TextView txtvw = (TextView)findViewById(R.id.TextView01);
txtvw.setText(readTxt());
private String readTxt()
{
InputStream raw = getResources().openRawResource(R.raw.hello);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try
{
i = raw.read();
while (i != -1)
{
byteArrayOutputStream.write(i);
i = raw.read();
}
raw.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return byteArrayOutputStream.toString();
}
TextView01:: txtview in linearlayout
hello:: .txt file in res/raw folder (u can access ny othr folder as wel)
Ist 2 lines are 2 written in onCreate() method
rest is to be written in class extending Activity!!
getClass().getResourcesAsStream() works fine on Android. Just make sure the file you are trying to open is correctly embedded in your APK (open the APK as ZIP).
Normally on Android you put such files in the assets directory. So if you put the raw_resources.dat in the assets subdirectory of your project, it will end up in the assets directory in the APK and you can use:
getClass().getResourcesAsStream("/assets/raw_resources.dat");
It is also possible to customize the build process so that the file doesn't land in the assets directory in the APK.
InputStream in = getResources().openRawResource(resourceName);
This will work correctly. Before that you have to create the xml file / text file in raw resource. Then it will be accessible.
Edit Some times com.andriod.R will be imported if there is any error in layout file or image names. So You have to import package correctly, then only the raw file will be accessible.
This worked for for me: getResources().openRawResource(R.raw.certificate)