Line Break in index of ArrayList - java

I am reading a text line with FileInputStream at one of its index in ArrayList which contains a Line Break and using it to display in TextView. But problem is that \n is being displayed instead of making a line break.
I also checked Whether an Arraylist can contain "\n" and it worked exactly how I wanted
but only when am declaring it within my class like -data.add(1,"xyz\nxyz"). but the same is not working when I read line from text file.
public class MainActivity extends AppCompatActivity {
public static ArrayList<String> data;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
data=new ArrayList<>();
tv1=findViewById(R.id.text1);
tv2=findViewById(R.id.text2);
Reading text file
File fi = new File(Environment.getExternalStorageDirectory(), "Path /test.txt");
if (fi.exists()){
try {
FileInputStream inputStream = new FileInputStream(fi.getPath());
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line = bufferedReader.readLine();
while (line != null) {
data.add(0,line);
line = bufferedReader.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Displaying elements of ArrayList in TextView
tv1.setText(data.get(0)); // TextView display "\n" instead of line break.
data.add(1,"\n\nhello here is a\nline break"); // This works fine as expected, text is displayed in new line
tv2.setText(data.get(1));

Related

Reading from a text file and storing specific values

Basically the code I have below does currently read from a text file, but what I want it to do is store a value so that I can use it later for a another function. So from the text file I would like to store the height (175) and weight (80) value. How would that be done?
Text File:
Name: ..........
Height: 175
Weight 80
MainActivity:
package com.example.readfromfiletest;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
Button b_read;
TextView tv_text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b_read = (Button) findViewById(R.id.b_read);
tv_text = (TextView) findViewById(R.id.tv_text);
b_read.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String text = "";
try {
InputStream is = getAssets().open("test.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
text = new String(buffer);
} catch (IOException ex) {
ex.printStackTrace();
}
tv_text.setText(text);
}
});
}
}
Judging from your comments, it sounds like you're asking how to properly read in the values into different variables rather than reading them into one String. I think the first thing you should do to achieve this is read the file in line by line with a BufferedReader. Then for each line you read in you can determine which variable to assign the value to. For instance, you could do this:
Button b_read;
TextView tv_text;
String name = "";
int height = 0;
int weight = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b_read = (Button) findViewById(R.id.b_read);
tv_text = (TextView) findViewById(R.id.tv_text);
b_read.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String text = "";
try {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(getAssets().open("test.txt")));
String line;
while((line = bufferedReader.readLine()) != null){
text = text.concat(line + "\n");
String[] lineVals = line.split(":");
if(lineVals[0].equalsIgnoreCase("name")){
name = lineVals[1].trim();
} else if(lineVals[0].equalsIgnoreCase("height")){
height = Integer.parseInt(lineVals[1].trim());
} else if(lineVals[0].equalsIgnoreCase("weight")){
weight = Integer.parseInt(lineVals[1].trim());
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
tv_text.setText(text);
}
});
}
The BufferedReader reads in one line at a time. For example just, "Height: 175"
The line is then split on the ":", returning a String[] with two values. Continuing with our Height example, the array looks something like this: ["Height", " 175"]
The if statements (could also be case statements) then determine whether we're dealing with the name, height or weight variable.
The value is then assigned to its appropriate variable. The trim() method is called during this assignment to remove the space after the colon. You could also circumvent this by performing the split() method on ": ".
You could also stick with your current method and do some String manipulation involving splitting, Regex, or some other method, but I am of the opinion that my proposed solution will be a bit easier to read/work with in the future.

Empty saved text file

There's a problem i'm fighting with for two days. Using FileWriter I try to save data into txt file. File is saved by an application but it's always empty.
b1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
try {
boolean usunieto = true;
boolean stworzono = false;
String t_magazyn = e_magazyn.getText().toString();
String nazwa = e_nazwa.getText().toString();
if(!t_magazyn.trim().equals("")){
#SuppressLint("SdCardPath") File plik = new File("/sdcard/"+nazwa+".txt");
// jeśli plik nie istnieje, stwórz go
if(plik.exists()){
usunieto = plik.delete();
Toast.makeText(getApplicationContext(),"Plik został usunięty!",Toast
.LENGTH_SHORT).show();
}
if(usunieto){
stworzono = plik.createNewFile();
Toast.makeText(getApplicationContext(),"Plik utworzony!",Toast
.LENGTH_SHORT).show();
}
if(!usunieto||!stworzono){
Toast.makeText(getApplicationContext(),"Apka dalej cie olewa xD",Toast
.LENGTH_SHORT).show();
}
//THIS PART DOESN'T WORK AS INTENDED
FileWriter wpis = new FileWriter(plik.getName(),true);
BufferedWriter bufor = new BufferedWriter(wpis);
bufor.write(e_magazyn.getText().toString());
i_e_magazyn.setText(e_magazyn.getText().toString());
bufor.close();
}
}
catch(IOException e) {
e.printStackTrace();
}
}
});
e_magazyn,e_nazwa are EditText fields and i_e_magazyn is TextView field
In b2 button which isn't visible here this line of code works.
i_e_magazyn.setText(e_magazyn.getText().toString());
I tried a lot of actions to update data into file but it looks like after creating a new FileWriter variables are made empty
How do i make it work?
You just need to write this line
FileWriter wpis = new FileWriter(plik,true);
Instead of
FileWriter wpis = new FileWriter(plik.getName(),true);

Write and Read Android

I have a problem with my code, I need to read EditText from a user and than put that text into another layout and do some calculations. My problem is that I don't understand how to read/write data in Android. Below is a snippet of the read/write code.
Thanks for the help!
EDIT: Should be noted that all of this is inside of my MainActivity class
public EditText editName;
public EditText editAMT;
public Button save;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editName = (EditText) findViewById(R.id.editName);
editAMT = (EditText) findViewById(R.id.editAMT);
save = (Button) findViewById(R.id.save);
File fName = new File(name);
File fAMT = new File(AMT);
//WRITING TO THE FILE
try{
FileOutputStream test = openFileOutput(name, Context.MODE_PRIVATE);
FileOutputStream test2 = openFileOutput(AMT, Context.MODE_PRIVATE);
test.write(editName.getText().toString().getBytes());
test2.write(editAMT.getText().toString().getBytes());
test.close();
test2.close();
} catch(Exception e){
e.printStackTrace();
}
//READING FROM THE FILE
try{
BufferedReader inputReader = new BufferedReader(new InputStreamReader(openFileInput(name)));
String inputString;
StringBuffer stringBuffer = new StringBuffer();
while ((inputString = inputReader.readLine()) != null){
stringBuffer.append(inputString + "\n");
}
} catch (IOException e){
e.printStackTrace();
}
}
EDIT: Here is my action plan.
1) Get information from EditText called (eAMT). 2) Get information from EditText called (eName). 3) Put the information of eAMT into a file called eName.txt 4) In another activity, search for the file called eName. 5) Once search is completed, pull the contents of that file and display onto another activity (Main activity).
Instead of writing to a file, use Android's SharedPreferences:
SharedPreferences preferences = getSharedPreferences("com.example.myapp", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("UniqueEditNameKey", editName.getText().toString);
From another activity, you can do the following to retrieve the value:
SharedPreferences preferences = getSharedPreferences("com.example.myapp", MODE_PRIVATE);
String name = preferences.getString("UniqueEditNameKey", ""); // second argument is default value if key does not exist

How can i read specific text from txt file in android

I'm trying to make a simple dictionary which searches the words from txt file. I created the txt file and stored some English words. I want to write the word to EditText. Then, this word will be found and displayed on the TextView. Here is my code. It displays the whole txt file. How can i find the specific word ?
public class MainActivity extends Activity {
//creating variables
TextView myText;
EditText myEdit;
Button myButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initializing the TextView EditText and Button
myText=(TextView) findViewById(R.id.idTextView);
myEdit=(EditText) findViewById(R.id.idEditText);
myButton=(Button) findViewById(R.id.idButton);
myButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String saveData=myEdit.getText().toString();
try{
myText.setText(readfile());
}catch(IOException e){
e.printStackTrace();
}
}
});
}
private String readfile()throws IOException {
String str="";
InputStream is = getResources().openRawResource(R.raw.translate);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line=reader.readLine();
while (line!=null)
{
str = str + line + "\n";
line = reader.readLine();
}
reader.close();
return str;
}
}
It all depends on how your readFile() is implemented. I suggest that you modify it to accept a String parameter. That way, it will search for that word in the file and return its meaning as another String that you can assign to TextView via setText()
myText.setText(readFile(saveData)));
is how the suggested implementation would look like.
Inside this method, when you read the file line-by-line, check if the String you just read from the file contains the required word. This can be done using the contains() method.
Think you're after a simple contains() check:
String fileText = readFile();
Boolean textFound = fileText.contains(saveData);
If that boolean is true, then you would display the value of saveData in the box. You could put this operation in a loop and search for multiple words as well if you wanted.

How to display data from a Text file in a listView

I've a plain text file which consist some lines, At the end of each line I insert a comma ( , ) . I also can read text files and set it on ListView but I don't know How can I make a new item in ListView by the lines that end with a comma . (I mean showing a single line in a single item.)
I've text file like this :
Test 1 ,
Test 2 ,
Test 3 ,
And this my ListActity:
public class MainMenuActivity extends ListActivity {
public String[] ListItems = new String[]{};
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
try {
Resources ResFiles = getResources();
InputStream ReadDbFile = ResFiles.openRawResource(R.raw.test);
byte[] Bytes = new byte[ReadDbFile.available()];
ReadDbFile.read(Bytes);
String DbLines = new String(Bytes);
ListItems= new String[]{DbLines};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.main_list, R.id.ListText, ListItems);
setListAdapter(adapter);
} catch (Exception e) {
}
}
This ListView just showing me all lines in a single item , Any idea?
ListItems= new String[]{DbLines}; will give you an array of one item!
DbLines.split(",") might be better ;-)
String DbLines = new String(Bytes); // One string containing all the file
ListItems= new String[]{DbLines}; // an array containing the previous string
Why do you expect ListView to show multiple items? Try to split your file content in a string array, like this:
ListItems = DbLines.split(",");
In the end:
public class MainMenuActivity extends ListActivity {
public String[] ListItems = new String[]{};
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
try {
Resources ResFiles = getResources();
InputStream ReadDbFile = ResFiles.openRawResource(R.raw.test);
byte[] Bytes = new byte[ReadDbFile.available()];
ReadDbFile.read(Bytes);
String DbLines = new String(Bytes);
ListItems = DbLines.split(","); // Split the content by ","
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.main_list, R.id.ListText, ListItems);
setListAdapter(adapter);
} catch (Exception e) {
}
}
You can also split using:
DbLines.append("\r\n"); //Splits by NL
Test 1
Test 2
Test 3
This was more appropriate for my code and may be for yours as well. I believe there is a .lineseperator method but this works for me.

Categories

Resources