How to read text file upon opening an app? - java

I am making an app where I have my school balance set and can press dedicated buttons to take away certain amounts depending on what I purchase. I am having trouble with the balance. I have a way of updating it to what I want, however after I terminate the application I want it to stay the same in a TextView. I so far was able to make it save it to a file, or at least I hope I was, with the help of a video.
How could I on opening the app read the text file and set the TextView equal to what is in the file?
submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String submitAmount = amountEnter.getText().toString();
balance.setText(submitAmount);
String myBalance = balance.getText().toString();
try {
FileOutputStream fou = openFileOutput("balance.txt",
MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fou);
try {
osw.write(myBalance);
osw.flush();
osw.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
});

You can save it in SharedPrefs
change it to
submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String submitAmount = amountEnter.getText().toString();
balance.setText(submitAmount);
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).
edit().putString("balance", submitAmount).commit();
}
});
and you can get it by
String balance=PreferenceManager.getDefaultSharedPreferences(getApplicationContext())
.getString("balance","nothing_there");

Seeing your code, i assume that you know how to read/write a file in android. If not, then see it from here . https://stackoverflow.com/questions/12421814/how-can-i-read-a-text-file-in-android/ You can try the following code. THe readfile method is from the upper link. You just have to read the particular line/string from the file at onCreate method of the activity. Get the reference of your desired TextView and then set the text to TextView like below. I hope it helps you
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
String texts = readfile();
TextView textView = findViewById(R.id.text_view);
textView.setText(text);
}
private String readfile() {
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard, "file.txt");
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
} catch (IOException e) {
//You'll need to add proper error handling here
}
return text.toString();
}

Related

AndroidStudio - save user info in CSV file and read it

I'm a newbie in programming on Android Studio. I'm trying to create a simple application to gain basic experience. In the application, I would need to store individual inputs to a file (ideally CSV) in internal memory. First of all, I am trying to save user data - my name and phone number. The save method looks like this:
public void save(View view)
{
String fileName = "user.csv";
ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
File directory = contextWrapper.getDir(getFilesDir().getName(), ContextWrapper.MODE_PRIVATE);
File file = new File(directory, fileName);
String data = "FirstName,LastName,PhoneNumber";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(fileName, Context.MODE_PRIVATE);
outputStream.write(data.getBytes());
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
The data seems to be saved and I'm redirected to MainActivity. Here is the method:
protected void onCreate(Bundle savedInstanceState) {
File file = new File(getFilesDir(),"user.csv");
if(!file.exists()) {
Intent intent = new Intent(this, activity_login.class);
startActivity(intent);
}
else {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv_name = findViewById(R.id.tv_name);
TextView tv_phone = findViewById(R.id.tv_phone);
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("user.csv"));
while ((sCurrentLine = br.readLine()) != null) {
tv_name.setText(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
No value is stored in TextView tv_name and the box is empty. Where am I making mistake?
Thank you very much for your help!
For reading data saved use this method uses, UTF_8 ENCODING
public static String readAsString(InputStream is) throws IOException {
BufferedReader reader = null;
StringBuilder sb = new StringBuilder();
try {
String line;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
reader = new BufferedReader(new InputStreamReader(is,UTF_8));
}
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} finally {
if (reader != null) {
reader.close();
}
}
return sb.toString();
}
Use this method as follows, parsing file "user.csv".
public static String readFileAsString(File file) throws IOException {
return readAsString(new FileInputStream(file));
}
Fetch string and set textView
Use as this to read file:
FileInputStream fis = new FileInputStream("your full file path");
BufferedReader bfr = new BufferedReader(new InputStreamReader(fis));
Below is the code for creating .csv file and inserting data into it.
For more look into my answer :https://stackoverflow.com/a/48643905/8448886
CODE HERE:
String csv = (Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyCsvFile.csv"); // Here csv file name is MyCsvFile.csv
//by Hiting button csv will create inside phone storage.
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CSVWriter writer = null;
try {
writer = new CSVWriter(new FileWriter(csv));
List<String[]> data = new ArrayList<String[]>();
data.add(new String[]{"Country", "Capital"});
data.add(new String[]{"India", "New Delhi"});
data.add(new String[]{"United States", "Washington D.C"});
data.add(new String[]{"Germany", "Berlin"});
writer.writeAll(data); // data is adding to csv
writer.close();
callRead();
} catch (IOException e) {
e.printStackTrace();
}
}
});

Reading Text file in android

I am trying to read a text file stored in my mobile device external storage , but it is throwing this error: -
Error occured while reading text file!!/storage/emulated/0/atom.txt: open failed: ENOENT (No such file or directory)
Here's the code
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.btn_picker);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
fileOpener();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
private void fileOpener() throws IOException {
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,"atom.txt");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
Log.e("Error", "Error occured while reading text file!!" + e.getMessage());
}
//Find the view by its id
Log.d("Text",text.toString());
}
}
How can I figure this out?
EDIT : The atom.txt file is already saved in my device but still it is throwing the same error.
The file doesn't exist, so the path returned by Environment.getExternalStorageDirectory is not what you are expecting it to be. According to the API docs, this path is not guaranteed to be an SD card.

Find words in text file from assets folder ANDROID STUDIO

I have a problem with my app.
What I'm trying to do is to find rhymes to a word entered from the user into a text field.
I have a dictionary in assets folder called "words.txt".
My app is working almost correctly, but it finds only one word from my text file.
How can I find all words that rhyme with the word from the text field?
Any ideas?
Here is my code:
#Override
protected void onCreate(Bundle saveInstanceState){
super.onCreate(saveInstanceState);
setContentView(R.layout.activity_main);
editTextWord = (EditText)findViewById(R.id.editTextWord);
b_read = (Button)findViewById(R.id.buttonSearch);
tv_text = (TextView)findViewById(R.id.nameTxt);
b_clear = (Button)findViewById(R.id.buttonClear);
b_clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, MainActivity.class);
startActivity(i);
}
});
b_read.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
InputStream is = getAssets().open("words.txt");
int size = is.available();
BufferedReader rd = new BufferedReader(new InputStreamReader(is,"UTF-8"));
String line;
String word = editTextWord.getText().toString();
if (word.isEmpty()){
Toast.makeText(getApplicationContext(), "Wpisz słowo", Toast.LENGTH_SHORT).show();
return;
}
while ((line = rd.readLine()) !=null ){
if (line.substring(line.length()-2).equals(word.substring(word.length()-2))){
tv_text.setText(line);
}
}
rd.close();
}catch (IOException ex){
ex.printStackTrace();
}
}
});
}
tv_text.setText overwrites anything that is already in the TextView. You need to use something like TextView.append(CharSequence)
Try:
tv_text.append(line + "\n");

Display a specific line in a text file - android/java

I'm trying to build an app which displays fun facts from a text file. To do this I get a random number and then display that specific line number from the file.When I run the app and try and press the button all I get is a blank text field. Here is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fun_facts);
// Declare and assign variables
final TextView factLabel = (TextView) findViewById(R.id.factTextView);
Button showFactButton = (Button) findViewById(R.id.showFactButton);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
/*
code here runs when button click is detected by line 29
code shows new fact
*/
String fact = "";
//get a random number to select a fact
Random randomNumberGenrator = new Random();//construct random object
int randomNumber = randomNumberGenrator.nextInt(391);
FileReader fr = null;
try {
fr = new FileReader("facts.txt ");//construct filereader and assign file
} catch (FileNotFoundException e) {
e.printStackTrace();//exception raised
}
LineNumberReader getFact = new LineNumberReader(fr);//construct lineNumberReader
getFact.setLineNumber(randomNumber);//set current line number to random number
try {
fact = getFact.readLine();//read current line and assign it to fact
} catch (IOException e) {
e.printStackTrace();
}
factLabel.setText(fact);
try {
getFact.close();//close lineReader
} catch (IOException e) {
e.printStackTrace();
}
try {
fr.close();//close fileReader
} catch (IOException e) {
e.printStackTrace();
}
}
};
showFactButton.setOnClickListener(listener);
}
Do you getting any errors?
check this line, maybe its typo but worth check it and remove that space from path.
OLD:
fr = new FileReader("facts.txt ");
NEW:
fr = new FileReader("facts.txt");

How to sort strings from txt file and post them to textview item

I am reading from txt file some strings.TextView shows me:"score=10" "score=1""score=5""score=11"
I want to sort this like:TextView shows:"score=1" "score=5""score=10""score=11"
I dont know how to sort this strings.this are not ints.
Can u Help me with an example ? Or can u see my code?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wyniki);
final TextView scores = (TextView) findViewById(R.id.textView4);
final Button button5 = (Button) findViewById(R.id.button5);
String saved_scores = readText();
if (saved_scores.length()>0){
scores.setText(saved_scores);}
sort();
button5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final File f = new File(Environment.getExternalStorageDirectory()+"/cos/Wynik.txt");
if (f.exists()){
f.delete();
Toast.makeText(getApplicationContext(),"Deleted",Toast.LENGTH_SHORT).show();
scores.setText(null);
}
}
});
}
public String readText(){
//this is your text
StringBuilder text = new StringBuilder();
try{
final File f = new File(Environment.getExternalStorageDirectory()+"/cos/Wynik.txt");
FileInputStream fileIS = new FileInputStream(f);
BufferedReader buf = new BufferedReader(new InputStreamReader(fileIS));
String readString = "";
//just reading each line and pass it on the debugger
while((readString = buf.readLine())!= null){
Log.d("line: ", readString);
text.append(readString + "\n");
}
buf.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
return text.toString();
}
Remove the "score=" part of each line in the text file, and for each line check if the remaining content is a valid number - if so, store that as an integer in a collection. Once you're done with reading the text file, you can just sort the collection and use the data in whatever fashion you want in your TextView.
You can do the following
Scanner Reader=new Scanner(fileName);
In a for loop read all the integers from using Reader.nextInt() function.

Categories

Resources