Android - Save and Read from file - android

I have a listview lv_operationListand I'm trying to save it to a file and read it after. I can save and read files but I dont know if what I'm saving and reading is correct.
Basically I want to save the list rows and when I load a program I want to fill the same listview with the saved data.
Saving:
for (int i = 0; i < lv_operationList.getAdapter().getCount() - 1; i++) {
fileOutputStream.write(lv_operationList.getAdapter().toString().getBytes());
}
fileOutputStream.close();
Load?? Maybe something like this?
`fileInputStream = getContext().openFileInput(programName);
Scanner scanner = new Scanner(new DataInputStream(fileInputStream));
while(scanner.hasNext()) {
//Read??
}
//and display on lv_operationList. How?

i think you need to append the contents to the same file so you need to use append_mode like this.
OutputStreamWriter out = new OutputStreamWriter(openFileOutput("save.txt", Context.MODE_APPEND));
out.write("text");
out.write('\n');
in order to read them you can use this method.
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
Log.i("reading line by line",""+text);
}

Related

How do I get certain values from a txt file?

I'm kind of noob in Android and I need help with something. I have a .txt file like this:
#nombre iron will#
#fuerza 6#
#const 6#
#habilidad 6#
#intelig 6#
#vitalidad 42#
#aguante 72#
What I want to do is to get every item in the .txt file and store it in a variable. For example, in this case I want a String variable called "nombre" with the value "Will", an int variable "fuerza" with the value "6", etc.
How can I get this? Thanks in advance, and sorry about my bad english.
My code so far:
File tarjeta = Environment.getExternalStorageDirectory();
File carpeta = new File(tarjeta.getAbsolutePath() + "/Rol/PJs/");
File archivo = new File(carpeta.getAbsolutePath(), archivoabierto); //String archivoabierto = "name.txt"
StringBuilder text = new StringBuilder();
try{
//This is where I get lost, I don't know how to proceed
BufferedReader br = new BufferedReader(new FileReader(archivo));
String line;
while ((line = br.readLine()) != null){
text.append(line);
text.append('\n');
}
br.close();
} catch (IOException e){
Toast.makeText(Personajes.this, "No se pudo cargar "+archivo.getPath(), Toast.LENGTH_SHORT).show();
}
EDIT:
I'm using json format now and it works. Thanks all!
you could also use
String[] parts = text.split(" ");
String key = parts[0];
String value = parts[1];
but i recommand to use json-format.
Please use SharedPreferences to store key-values, It is much easier.
http://androidopentutorials.com/android-sharedpreferences-tutorial-and-example/

Read large List in Android for AutoCompleteTextView

I have a file with 72000 lines and 2,6M size. In this File are all String items for a AutoCompleteTextView.
Currently i read them like this:
List<IcdObject> codes = new ArrayList<IcdObject>();
try {
InputStream input = getAssets().open("icd.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(input));
String line;
while ((line = br.readLine()) != null) {
String[] icd = line.split("|");
codes.add(new IcdObject(icd[0], icd[1]));
}
input.close();
} catch (IOException e) {
// TODO
e.printStackTrace();
}
ArrayAdapter<IcdObject> adapter = new ArrayAdapter<IcdObject>(this,
android.R.layout.select_dialog_item, codes);
AutoCompleteTextView at = (AutoCompleteTextView) findViewById(R.id.AutoComplete);
at.setThreshold(3);
at.setAdapter(adapter);
The Garbage Collector goes crazy when i start the activity. But in the end all items get loaded, after waiting around 1min.
Is there a method to load the file on demand or make it faster?
You can use Loaders API to perform these large data set reading.
The LoaderManager.LoaderCallbacks class is used to get callback from LoaderManager

own csv reader to string array out of memory

because i am only reading a very simple csv, where only strings are comma separated and should be converted to a String[].
I thought this was so easy a external jar would be a bit to much and i could handle this very easy. But what happens is that the first item get added until the memory is full and crash!
public List readWinkels(Activity a){
List winkelList = new ArrayList();
try{
InputStream winkelcsv = a.getResources().getAssets().open("winkels.csv");
BufferedReader br = new BufferedReader(new InputStreamReader(winkelcsv, "UTF-8"));
String s = br.readLine();
while (s != null){
winkelList.add(s);
System.out.println(s.toString());
}
br.close();
for(int i =0;i<winkelList.size();i++) {
System.out.println(winkelList.get(i));
}
}catch(IOException ioe){
ioe.printStackTrace();
}
return winkelList;
here is my code.... i dont get why it doesnt work, can anyone help? A readline reads the line and then the reading points jumps to the next line (i think) so why is the first line added a zillion times?
Here's the standard idiom for using a while loop to iterate over lines of a file, applied to your code:
String s;
while ((s = br.readLine()) != null){
winkelList.add(s);
System.out.println(s.toString());
}
You need to call readLine() at every iteration through the loop. The original code is nothing but an infinite loop, since s is only read once. Assuming s is not null, the loop condition is never false, so the list grows without bound until all available memory is used.

FileNotFoundException when trying to read xls in android

I'm trying to read excel contents in android, but always get file not found exception
The project is in:
C:\AndroidWorkSpace\AntenaProject
And the code is:
public void TestClick(View view)
{
File inputWorkbook = new File("shidur.xls");
Workbook w;
StringBuilder sb = new StringBuilder("starting");
try {
w = Workbook.getWorkbook(inputWorkbook);
// Get the first sheet
Sheet sheet = w.getSheet(0);
// Loop over first 10 column and lines
for (int j = 0; j < sheet.getColumns(); j++) {
for (int i = 0; i < sheet.getRows(); i++) {
Cell cell = sheet.getCell(j, i);
//CellType type = cell.getType();
sb.append(cell.getContents());
}
}
} catch (Exception e) {
e.printStackTrace();
}
TextView tv = (TextView)findViewById(R.id.testText);
tv.setText(sb.toString());
}
i tried to put shidur.xls in the following folders:
C:\AndroidWorkSpace\AntenaProject\res\raw
C:\AndroidWorkSpace\AntenaProject\res
but still getting this exception.
i'm using jxl.jar from http://jexcelapi.sourceforge.net/
thanks for the help
The path that you provide to the File constructor needs to be the absolute path of the file, or you need to use the overload that takes another File object as the first parameter which represents the directory the file lives in.
That being said, constructing a file in this way is for files that are either in local storage (ie. phone's main memory) or external storage (ie. SD card).
To open a file from the res/raw directory, get an InputStream in the following way
InputStream in = getResources().openRawResource(R.raw.file_name);
Then, you will need code that reads the contents of your input stream. I use a static helper method that looks like this, but this could run you into problems if the file is huge. Hasn't happened to me yet, but in principle that's always a risk when loading the entire content of a file into memory
public static String readStream(InputStream in)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
}
catch(Exception ex) { }
finally
{
// NOTE: you don't have my IOUtils class,
// but all these methods do is check for null and catch the exceptions that Closeable.close() can throw
IOUtils.safeClose(in);
IOUtils.safeClose(reader);
}
return sb.toString();
}
You should use the following code to open file in the /res/raw
getResources().openRawResource(R.raw.shidur.xls)

Android Runtime.getRuntime().exec() to nav through directories

So I want to be able to write an app that can turn on and display logcat messages, dmesg, and also be able to run commands like 'ls' 'cat' 'echo' 'cd.'
If I do the following:
nativeProc = Runtime.getRuntime().exec("ls\n");
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(nativeProc.getOutputStream()));
BufferedReader in = new BufferedReader(new InputStreamReader(nativeProc.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
full = full + "\n" + line;
}
I can put the text "full" to a Text View and see the root directory.
However, that's about all I can do. Let's say I want to find a directory, and change to it, I'm having trouble.
So if I do this:
nativeProc = Runtime.getRuntime().exec("ls\n");
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(nativeProc.getOutputStream()));
BufferedReader in = new BufferedReader(new InputStreamReader(nativeProc.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
full = full + "\n" + line;
}
/* Code here to confirm the existing of a directory*/
nativeProc = Runtime.getRuntime().exec("cd tmp\n");
BufferedReader in2 = new BufferedReader(new InputStreamReader(nativeProc.getInputStream()));
line = null;
String test = "\nStart1:\n";
while ((line = in2.readLine()) != null) {
test = test + "\n" + line;
}
I get nothing for both "full" and "text"
Any ideas?
You can execute ls with provided path for which folders should be listed
Runtime.getRuntime().exec(new String[] { "ls", "\\tmp"});
The current working directory is associated with the current process. When you exec("cd tmp") you are creating a process, changing its directory to "tmp", and then the process exits. The parent process' working directory doesn't change.
See this for a more general discussion of changing the current working directory in Java.
How about writing a shell file which checks for existence of the file and all other implementaion in this file and added it to sdcard and trigger the shell file from java using getRuntimr.exec().you can also pass parameters to it.

Categories

Resources