Display a specific line in a text file - android/java - 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");

Related

How to read text file upon opening an app?

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

Android File IO: Not saving/not loading the data

Background:
I am using three fragments and one activity in my application. Two fragments use recyclerViews and the other uses an expandableListView.
Problem:
I am trying to properly program the onPause(), onResume(), onStop(), and onRestart() methods to save the state of my application when the home, back, or switch views buttons are pressed.
To save the state of the program and load it when it comes back I have created the save() and load() methods in my one and only activity.
//from the end of onCreate
load();
}
#Override
protected void onStart() {
super.onStart();
mRef = new Firebase("https://sure-7856d.firebaseio.com/");
}
#Override
protected void onStop(){
super.onStop();
save();
}
#Override
protected void onPause(){
super.onPause();
save();
}
#Override
protected void onResume(){
super.onResume();
load();
}
#Override
protected void onRestart(){
super.onRestart();
load();
}
In the save method I get the adapters from my 2 recyclerViews and my expandableListView`s ArrayList that keeps track of which checkboxes are checked.
After that I put them each into a temporary Arraylist then I add each of those ArrayLists to a single arraylist that will be saved to the file.
private void save(){
//saved_data = new File("saved_data");
/*try {
if(saved_data.exists()==false){
//saved_data.createNewFile();
saved_data.setWritable(true);
}
} catch (IOException e) {
e.printStackTrace();
}*/
File myFile;
try{
myFile = new File(getFilesDir().getAbsolutePath(), "dir/save_data.bin");
myFile.mkdirs();
myFile.createNewFile();
FILENAME = myFile.getName();
}catch (IOException e){
e.printStackTrace();
}
OneFragment f20 = (OneFragment) frags.get(0);
TwoFragment f21 = (TwoFragment) frags.get(1);
ThreeFragment f22 = (ThreeFragment) frags.get(2);
ArrayList saveTasks = f20.adapter.getList();
ArrayList saveReqs = f21.adapter.getList();
ArrayList saveMap = new ArrayList<String>();
if(f22.listAdapter!=null) {
if (f22.listAdapter.getExport() != null) {
saveMap = f22.listAdapter.getExport();
}
}
ArrayList results = new ArrayList();
results.add(saveTasks);
results.add(saveReqs);
results.add(saveMap);
ObjectOutputStream oos1 = null;
FileOutputStream fos1 = null;
try {
fos1 = openFileOutput(FILENAME, Context.MODE_PRIVATE);
oos1 = new ObjectOutputStream(fos1);
oos1.writeObject(results);
oos1.close();
fos1.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(oos1 != null){
try {
oos1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
In the load code I get the object from the file and update the adapters to their previous state.
private void load(){
//saved_data = new File("saved_data");
ArrayList results = new ArrayList();
FileInputStream fis = null;
ObjectInputStream ois = null;
if(FILENAME==null){
return;
}
try {
fis = new FileInputStream(FILENAME);
ois = new ObjectInputStream(fis);
}catch (FileNotFoundException e) {
e.printStackTrace();
return;
}catch (IOException e) {
e.printStackTrace();
}
try {
while (true) {
results = (ArrayList)(ois.readObject());
}
} catch (OptionalDataException e) {
if (!e.eof) try {
throw e;
} catch (OptionalDataException e1) {
e1.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ois.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
for(int i = 0; i < results.size();i++){
if(i == 0){
frags.set(0,results.get(i));
}
else if(i == 1){
frags.set(1,results.get(i));
}
else if(i == 2){
frags.set(2,results.get(i));
}
else{
}
}
}
When I press the square button at the bottom of the emulator and go back to it one of a few things happen
It crashes saying the file could not be found
W/System.err: Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
And this error points to the load method as the point of failure specifically
FileInputStream fis = null;
When I hit the triangle button nothing happens in logcat, everything is gone upon returning, and the app loses its functions of adding strings to lists on both recyclerViews and displaying both lists in the expandableListView.
Hitting the center circle button and going back to the app is fine nothing breaks.
Since Im getting a file not found error I think that the file isnt getting written
I have searched Stack for a solution and I am new to File IO and fragments, so I have no idea where to go from here.

Unfortunately, <app name> has stopped "String data = sharedData.getText().toString();"

Good morning guys!
Quick question, I am using file Input/Output in Java to save data into a String when the "Save" Button in my program is pressed. But whenever I hit the "Save" button, the program stops working.
I am also new to Java and Android, so I can't really tell yet if the problem is very specific to my code or a more general one which is why I am posting this question even if there are many others that are similar.
Using comment-outs "//, /*, /" I was able to locate the line in my code that causes the program to stop working, I have emphasised this line by placing "" at the beginning and at the end of it so you won't have trouble looking for it. I just want to know why this line is causing my app to stop and if possible, how it can be fixed.
Thanks guys. Your assistance will be very much appreciated.
Please take a look at my code snippet:
public class MainActivity extends ActionBarActivity {
EditText sharedData;
FileOutputStream fos;
String FILENAME = "InternalString";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
Button save = (Button) findViewById(R.id.btn_save);
save.setOnClickListener(onSave);
ListView list = (ListView) findViewById(R.id.restaurants);
adapter = new RestaurantAdapter();
list.setAdapter(adapter);
}
public View.OnClickListener onSave = new View.OnClickListener (){
#Override
public void onClick(View v) {
Info r = new Info();
EditText name = (EditText) findViewById(R.id.field_name);
EditText address = (EditText) findViewById(R.id.field_address);
TextView total= (TextView)findViewById(R.id.total);
RadioGroup types = (RadioGroup) findViewById(R.id.rgrp_types);
switch (types.getCheckedRadioButtonId()) {
case R.id.rbtn_sit_down:
r.setType("sit_down");
break;
case R.id.rbtn_take_out:
r.setType("take_out");
break;
}
r.setName(name.getText().toString());
r.setAddress(address.getText().toString());
r.setTotal(total.getText().toString());
String data = sharedData.getText().toString();*** <----- This line causes it to stop running
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(data.getBytes());
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String collected = null;
FileInputStream fis = null;
try {
fis = openFileInput(FILENAME);
byte[] dataArray = new byte[fis.available()];
while (fis.read(dataArray) != -1){
collected = new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
fis.close();
total.setText("Balance Total: " + collected +"Php");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Log.d("FoodTripActivity", "Name: " + r.getName() + "Address: " + r.getAddress() + "Type: " + r.getType());
adapter.add(r);
}
};
}
sharedData is not initialized. You need to initialize it before calling getText.
You have only declared it EditText sharedData;
sharedData =(EditText) findViewById(R.id.idforshareddata);
String data = sharedData.getText().toString();

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.

Reading from a text file in android

I'm trying to read a random line from a file. My code doesn't have error, just comes up with a force close as soon as it runs in the emulator and I can't work out why!
public class filereader extends Activity {
TextView t = (TextView)findViewById(R.id.text);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
Scanner s = new Scanner(getResources().openRawResource(R.raw.lev1)); {
try {
while (s.hasNext()) {
String word = s.next();
t.setText(word);
}
}
finally {
s.close();
}
}
}
TextView t = (TextView)findViewById(R.id.text);
you can not run findViewById until the setContentView has been called:
TextView t = null; #Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t = (TextView)findViewById(R.id.text);
}
please be sure that you declare text inside the main.xml
do this
BufferedReader myReader = null;
try
{
fIn = openFileInput("customer_number.txt");
myReader = new BufferedReader(new InputStreamReader(fIn));
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
String aDataRow = "";
//String aBuffer = "";
try
{
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
// TO display Whole Data of File
Toast.makeText(getBaseContext(),aBuffer,Toast.LENGTH_SHORT).show();
}
// To display Last Entered Number
Toast.makeText(getBaseContext(),last_number,Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public void readfromfile(){
try {
FileInputStream fileIn=openFileInput("mytextfile.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);
char[] inputBuffer= new char[READ_BLOCK_SIZE];
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0) {
// char to string conversion
String readstring=String.copyValueOf(inputBuffer,0,charRead);
String s +=readstring;
}
InputRead.close();
Toast.makeText(getBaseContext(), s,Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
It will read the text file named "mytext.txt" string by string and store it by appending it to string variable s. So the variable "s" contains final string taken from file.

Categories

Resources