How do I get certain values from a txt file? - android

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/

Related

Reading a large text file with over 130000 line of text

How can i read a large text file into my Application?
This is my code but it does not work. My code must read a file called list.txt. The code worked only with a file with only 10.000 lines.
can someone helps me?
Thanks!
My code:(Worked with small files, but not with large files)
private void largefile(){
String strLine2="";
wwwdf2 = new StringBuffer();
InputStream fis2 = this.getResources().openRawResource(R.raw.list);
BufferedReader br2 = new BufferedReader(new InputStreamReader(fis2));
if(fis2 != null) {
try {
LineNumberReader lnr = new LineNumberReader(br2);
String linenumber = String.valueOf(lnr);
while ((strLine2 = br2.readLine()) != null) {
wwwdf2.append(strLine2 + "\n");
}
// Toast.makeText(getApplicationContext(), linenumber, Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), wwwdf2, Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Since you are processing a large file, you should process the data in chunks . Here your file reading is fine but then you keep adding all rows in string buffer and finally passing to Toast.makeText(). It creates a big foot-print in memory. Instead you can read 100-100 lines and call Toast.makeText() to process in chunks. One more thing, use string builder instead of string buffer go avoid unwanted overhead of synchronization. You initializing wwwdf2 variable inside the method but looks it is a instance variable which I think is not required. Declare it inside method to make it's scope shorter.

Android - Save and Read from file

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);
}

I keep getting ArrayIndexOutOfBoundsException

Keep getting ArrayIndexOutOfBoundsException when trying to display a specific item form array list data displays fine in logcat but then after displaying throws exception at top please help is the code kind of new to android
public void loadData(){
InputStream file = ourContext.getResources().openRawResource(R.raw.cashpot);
BufferedReader reader = new BufferedReader(new InputStreamReader(file));
String line ="";
ArrayList<String> values = new ArrayList<String>();
try {
while((line = reader.readLine()) != null) {
values.add(line);
// String[] strings = line.split(",");
/*for(String s : strings) {
values.add(s);
}*/
}
reader.close();
//for(String s : values) Log.d("CSV Test", s);
for(int i = 0; i < values.size();i++){
String[] data = values.get(i).split(",");
Log.d("Test String",data[2] );
}
} catch (IOException e) {
e.printStackTrace();
}
}
Your some lines do not have comma(,)(or 1 comma) and you are trying to split them by comma and storing it in to data array. and you are accessing data[2] location. which might not been created that's why you are getting this exception.
There might not be a 3rd element in your array ,that is created after the split on ",".
You can print value of data before accessing data[2](that might not exist).
Or you can Debug your program and proceed step by step and monitoring the value of each variable.

how to import a contact name and number from csv file to android phone by programmatically

I am new to android i am in need to read a contact details as contact name and phone number form csv file and store it into android phone by pro grammatically please help any one .
thanks in advance
It's just a read and parse CSV file program that you need .
So you can do something like :
//--- If your input stream is `inpStrm` of the csv file :
BufferedReader reader = new BufferedReader(new InputStreamReader(inpStrm));
try {
String line;
while ((line = reader.readLine()) != null) {
String[] RowData = line.split(",");
date = RowData[0];
value = RowData[1];
// Now use "data" and "value" as you need to
}
}
catch (IOException ex) {
// ex.printStackTrace();
}
finally {
try {
inpStrm.close();
}
catch (IOException e) {
// e.printStackTrace();
}
}
Now contact name and phone number will be present in data and value. That's it i suppose .

Android - Comparing String Input On A Textfile Content

May I ask you to guide me how I can accomplish this problem?
I need to compare an inputWord to a string inside a .txt file and if found, return the whole line but if not, show "word not found".
Example:
inputWord: abacus
Text file content:
abaca - n. large herbaceous Asian plant of the banana family.
aback - adv. archaic towards or situated to the rear.
abacus - n. a frame with rows of wires or grooves along which beads are slid, used for calculating.
...
so on
Returns: abacus with its definition
What i am trying to do is compare my inputWord to the words before the " - " (hyphen as delimiter), if they dont match, move to the next line. If they match, copy the whole line.
I hope it doesnt seem like im asking you to "do my homework" but I tried tutorials around different forums and sites. I also read java docs but i really cannot put them together to accomplish this.
Thank you in advance!
UPDATE:
Here's my current code:
if(enhancedStem.startsWith("a"))
{
InputStream inputStream = getResources().openRawResource(R.raw.definitiona);
try {
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
String s = in.readLine();
String delimiter = " - ";
String del[];
while(s != null)
{
s = in.readLine();
del = s.split(delimiter);
if (enhancedStem.equals(del[0]))
{
in.close();
databaseOutput.setText(s);
break;
}
}
in.close();
}
catch (FileNotFoundException e) {
databaseOutput.setText("" + e);
}
catch (IOException e1) {
databaseOutput.setText("" + e1);
}
}
Thanks a lot! Here's what I came up, and it returns the definition of inputs properly but the problem is, when i enter a word not found in the textfile, the app crashes. The catch phrase doesn't seem to work. Have any idea how I can trap it? Logcat says NullPointerExcepetion at line 4342 which is
s = in.readLine();
Assuming that the format of each line in the text file is uniform. This could be done in the following manner :
1) Read the file line by line.
2) Split each line based on the delimiter and collect the split String tokens in a temp String array.
3) The first entry in the temp token array will be the word before the "-" sign.
4) Compare the first entry in the temp array with the search string and return the entire line if there is a match.
Following code could be put up in a function to accomplish this :
String delimiter = "-";
String[] temp;
String searchString = "abacus";
BufferedReader in = new BufferedReader(new FileReader(file));
while (in.readLine() != null) {
String s = in.readLine();
temp = s.split(delimiter);
if(searchString.equals(temp[0])) {
in.close();
return s;
}
}
in.close();
return ("Word not found");
Hope this helps.
you may try like:
myreader = new BufferedReader(new FileReader(file));
String text = "MyInput Word";
while(!((text.equals(reader.readLine())).equals("0")));

Categories

Resources