Load strings.xml from sd card to application android - android

Is it possible to load strings.xml from sd card instead of application res/values/... Search on the web but didn't find any tutorials. My thought is download the xml to sd card then save the strings element to an array.
public void stringsxml(){
File file = new File(Environment.getExternalStorageDirectory()
+ ".strings.xml");
StringBuilder contents = new StringBuilder();
try {
//use buffering, reading one line at a time
//FileReader always assumes default encoding is OK!
BufferedReader input = new BufferedReader(new FileReader(file));
try {
String line = null; //not declared within while loop
/*
* readLine is a bit quirky :
* it returns the content of a line MINUS the newline.
* it returns null only for the END of the stream.
* it returns an empty String if two newlines appear in a row.
*/
while (( line = input.readLine()) != null){
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
String data= contents.toString();
}

Well, actually it is semi-possible, but you have to create a derivate LayoutInflater which will replace string codes with thus read strings.
I have documented my attempts and failings together with initial implementation here.
Summary: simple strings work, string arrays do not

No, this is not possible. Check Android decoumentation about resources:
The Android SDK tools compile your application's resources into the application binary at build time. To use a resource, you must install it correctly in the source tree (inside your project's res/ directory) and build your application.
Resources are built-in into the application binary and you can't read them from a file.

Related

Android UIAutomator - read textfile on sdcard during runtime

Is it possible to read a textfile on sdcard during runtime of an UIautomator test? As in an android application, using getExternalDirectory() etc. to create a File-object pointing to the actual file. Is it possible to send a command using getRuntime().exec("cmd"), if so, how? Or is there an easier way to simply access the device:s sdcard and read a file into the test?
The goal is to throughout the test send parameters to the test. So the test will perform certain actions, then continously look for a change on a file on the devices sdcard, and if so, read that line, and continue to perform actions. So therefor a way to read a file, and check certain things, is needed.
Or is there perhaps another way to pass information into the test during runtime? I know it can be done at the start of the testrun, but not during testrun.
I use below code inside uiautomator code to read text files.instead of
public void FileRead(String file_location) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(file_location));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
//you can do whatever you want here or return String
} finally {
br.close();
}
}

Can't read lines from file by using StreamReader on Unity3d (Android)

I need to read a text stream by using StreamReader from file on android platform. File is about 100k lines, so even editor is getting stuck if i try to load it all to TextAsset or if i use WWW.
I simply need to read that file line by line without loading it all to a string. Then i'll do a tree generation from the lines that i got from the file. (But probably that part doesn't matter, i just need help on file reading part.)
I'm giving the code that i wrote down below. It works perfectly on editor, but fails on android.
I would be glad if anyone tell me, what am i missing.
(ps. english is not my native and this is my first question on the site. so sorry for the any mistakes that i may have done.)
private bool Load(string fileName)
{
try
{
string line;
string path = Application.streamingAssetsPath +"/";
StreamReader theReader = new StreamReader(path + fileName +".txt", Encoding.UTF8);
using (theReader)
{
{
line = theReader.ReadLine();
linesRead++;
if (line != null)
{
tree.AddWord(line);
}
}
while (line != null);
theReader.Close();
return true;
}
}
catch (IOException e)
{
Debug.Log("{0}\n" + e.Message);
exception = e.Message;
return false;
}
}
You can't use Application.streamingAssetsPath as a path on Android because streaming assets are stored within the JAR file with the application.
From http://docs.unity3d.com/Manual/StreamingAssets.html:
Note that on Android, the files are contained within a compressed .jar
file (which is essentially the same format as standard zip-compressed
files). This means that if you do not use Unity’s WWW class to
retrieve the file then you will need to use additional software to see
inside the .jar archive and obtain the file.
Use WWW like this in a coroutine:
WWW data = new WWW(Application.streamingAssetsPath + "/" + fileName);
yield return data;
if(string.IsNullOrEmpty(data.error))
{
content = data.text;
}
Or, if you really want to keep it simple (and your file is only a few 100k, stick it in a resource folder:
TextAsset txt = (TextAsset)Resources.Load(fileName, typeof(TextAsset));
string content = txt.text;

How to read/write a string encoded with android.util.Base64

I would like to store some strings in a simple .txt file and then read them, but when I want to encode them using Base64 it doesn't work anymore: it writes well but the reading doesn't work. ^^
The write method:
private void write() throws IOException {
String fileName = "/mnt/sdcard/test.txt";
File myFile = new File(fileName);
BufferedWriter bW = new BufferedWriter(new FileWriter(myFile, true));
// Write the string to the file
String test = "http://google.fr";
test = Base64.encodeToString(test.getBytes(), Base64.DEFAULT);
bW.write("here it comes");
bW.write(";");
bW.write(test);
bW.write(";");
bW.write("done");
bW.write("\r\n");
// save and close
bW.flush();
bW.close();
}
The read method :
private void read() throws IOException {
String fileName = "/mnt/sdcard/test.txt";
File myFile = new File(fileName);
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader inBuff = new BufferedReader(new InputStreamReader(fIn));
String line = inBuff.readLine();
int i = 0;
ArrayList<List<String>> matrice_full = new ArrayList<List<String>>();
while (line != null) {
matrice_full.add(new ArrayList<String>());
String[] tokens = line.split(";");
String decode = tokens[1];
decode = new String(Base64.decode(decode, Base64.DEFAULT));
matrice_full.get(i).add(tokens[0]);
matrice_full.get(i).add(tokens[1]);
matrice_full.get(i).add(tokens[2]);
line = inBuff.readLine();
i++;
}
inBuff.close();
}
Any ideas why?
You have a couple of errors in your code.
First a couple of notes on your code:
When posting here, attaching a SSCCE helps others to debug your code. This is not a SSCEE because it doesn't compile. It lacks several defined variables, so one must guess what you really mean. Also you have pasted close-comment token in your code: */ but there is no one start-comment token.
Catching and just suppressing exceptions (like in catch-block in read method) is really bad idea unless you really know what you're doing. What it does most of the time is hide the potential problems from you. At least write the stacktrace of an exception is a catch block.
Why don't you just debug it, check what exactly outputs to the destination file? You should learn how to do that because that will speed up your development process, especially for larger projects with hard-to-catch problems.
Back to the solution:
Run the program. It throws an exception:
02-01 17:18:58.171: E/AndroidRuntime(24417): Caused by: java.lang.ArrayIndexOutOfBoundsException
caused by line here:
matrice_full.get(i).add(tokens[2]);
inspecting the variable tokens reveals that it has 2 elements, not 3.
So lets open the file generated by the write method. Doing that shows this output:
here it comes;aHR0cDovL2dvb2dsZS5mcg==
;done
here it comes;aHR0cDovL2dvb2dsZS5mcg==
;done
here it comes;aHR0cDovL2dvb2dsZS5mcg==
;done
Note line breaking here. This is because the Base64.encodeToString() appends additional newline at the end of the encoded string. To generate a one single line, without extra newlines, add Base64.NO_WRAP as the second parameter like this:
test = Base64.encodeToString(test.getBytes(), Base64.NO_WRAP);
Note here, you must delete file that was created earlier as it has improper line breaking.
Run the code again. It now creates a file with the proper contents:
here it comes;aHR0cDovL2dvb2dsZS5mcg==;done
here it comes;aHR0cDovL2dvb2dsZS5mcg==;done
Printing the output of matrice_full now gives:
[
[here it comes, aHR0cDovL2dvb2dsZS5mcg==, done],
[here it comes, aHR0cDovL2dvb2dsZS5mcg==, done]
]
Note that you're not doing anything with the value in decode variable in your code, hence the second element is the Base64 representation of that value which is read from the file.

Problem finding/reading a file

I'm trying to develop a small application, where I was given a JSON file, and I have to extract data from it. As I understood a JSON object takes a string argument, thus I'm trying to access a file and write the data from it to a string.
I've placed that file in a "JSON file" folder, and when I try to read the file, it throws me a file not found exception.
I've tried several ways to find a path to that file, but every attempt was for vain.
It might be that I'm extracting the path wrong, or might be something else, please help me.
Thanks in advance.
here is the code of finding the path:
try
{
path = Environment.getRootDirectory().getCanonicalPath();
}
catch (IOException e)
{
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
File jFile = new File(path + /"JSON file/gallery.json");
here is the code for reading from a file :
String str ="";
try
{
BufferedReader in = new BufferedReader(new FileReader(jFile));
while ((str += in.readLine()) != null)
{
}
in.close();
}
catch (IOException e)
{
e.getMessage();
}
return str;
Here more specification:
I want to take the data from the file in order to do that : JSONObject(jString).
when I extract the path of json file I create a file with the path and pass it to the function that reads from the file, and there it throws me a file not found exception, when I try to read from it.
The file does exists in the folder (even visually - I've tried to attach an image but the site won't let me, because I'm new user)
I've tried to open the file through the windows address bar by typing the path like that:
C:\Users\Marat\IdeaProjects\MyTask\JSON file\gallery.json and it opens it.
if you store it in the assets folder you can access it by using
InputStream is = context.getResources().getAssets().open("sample.json");
You can then convert it to a String
public static String inputStreamAsString(InputStream stream)
throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
return sb.toString();
}
EDIT
You need to put the file in the device, if it is on your computer, it is not accessible from your device. There are some ways to do that, and one of them is to put it in the res/ dir of your application. Please refer to the documentation to see how to do that.
Debug it. I'm pretty sure it will be very easy to find. To start with, look for the following:
Print the path before you create the file, e.g. Log.d("SomeTag", path + "/JSON file/gallery.json")
Observe the full exception details. Maybe there is another problem.
Explore the folders and see if the file exists (in eclipse: window -> show view -> other -> android -> file explorer.
You will probably observe the problem and be able to fix it. If not, post here a question with more details, including the results of those trials.
BTW, GetgetRootDirectory() returns the root directory of android, that's not what you want (you don't have RW permissions there) you probably want to get the applcation directory, you can see how to get it here, in the question I asked a few month ago. But since you didn't give us those details, it will be hard to help you more then that.

Android: How to read a txt file which contains Chinese characters?

i have a txt file which contains many chinese characters, and the txt file is in the directory res/raw/test.txt. I want to read the file but somehow i can't make the chinese characters display correctly. Here is my code:
try {
InputStream inputstream = getResources().openRawResource(R.raw.test);
BufferedReader bReader = new BufferedReader(
new InputStreamReader(inputstream,Charset.forName("UTF-8")));
String line = null;
while ((line= bReader.readLine())!= null) {
Log.i("lolo", line);
System.out.println("here is some chinese character 这是一些中文字");
}
} catch (IOException e) {
e.printStackTrace();
}
Both Log.i("lolo", line); and System.out.println("here is some chinese character 这是一些中文字") don't show characters correctly, i can not even see the chinese characters in the println() method.
What can i do to fix this problem? Can anybody help me?
In order to correctly handle non-ASCII characters such as UTF-8 multi-byte characters, it's important to understand how these characters are encoded and displayed.
Your console (output screen) may not support the display of non-ASCII characters. If that's the case, your UTF-8 characters will be displayed as garbage. Sometimes, you will be able to change the character encoding on the console. Sometimes not.
Even if the console correctly displayed UTF-8 characters, it's possible that your string does not correctly store the Chinese characters. You may think that it's correct because your editor displays them, but ensure that the character encoding of your editor also supports UTF-8.
I also was trying to figure out that. First you need to open the .txt file with the notepad and then click on File->Save as, there you will see a dropdown menu that says Enconding, so change it to UTF-8. After saving the file you should remove the .txt extension to the file and then add the file to the path res/raw and then you can refer to it from the code as R.raw.txtFileName.
That's all, i will put my code where I used the chinese characters and I could show them in the emulator.
If you have any other question, let me know because i am also developing something related with characters. Here is the code:
public List<String> getWords() {
List<String> contents = new ArrayList<String>();
try {
InputStream inputStream = getResources().openRawResource(R.raw.chardb);
BufferedReader input = new BufferedReader(new InputStreamReader(inputStream,Charset.forName("UTF-8")));
try {
String line = null;
while (( line = input.readLine()) != null){
contents.add(line);
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
return contents;
}

Categories

Resources