open text file from several file when clicked on button in android - android

i want create a book in android stodio
for example: i want when i click on first_season button open text1.txt file and when click on second_season button open text2.txt file and the rest as I said.
and i dont want make a activity for each page.
and i want use switch case for get button id and based on that id open the text file.
i just want to know how use switch case for create this application.
i use this code for open txt file:
TextView txtView = (TextView)findViewById(R.id.hellotxt);
InputStream inputStream = getResources().openRawResource(R.raw.nitish);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try {
i = inputStream.read();
while (i != -1)
{
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
txtView.setText(byteArrayOutputStream.toString());
consider names of my buttons are
season1, season2, season3, season4
and name of my text files are
txt1, txt2, txt3, txt4
thank for helping

Something like this you mean?
Map<Int, String> lookupTable = new HashMap<>();
lookupTable.put(R.id.season1, "txt1");
lookupTable.put(R.id.season2, "txt2");
// etc
for (Map.Entry<String,String> entry : lookupTable.entrySet()) {
findViewById(entry.getKey()).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtView.setText(readBookPageFromFile(entry.getValue());
}
})
}
Where readBookPageFromFile is your above code with the filename as a parameter.

Related

Opening Text Files Within ListView in Android

I am working on a simple word processing app, and I'm close to the point of being able to release it, except that I have one problem. When I click on an item in a ListView that displays the file names of all the text files the user has created with my app, I would like to open the file that corresponds with the item name, and place the text from that file inside the main EditText that the user uses to input data. However, when the item is clicked, nothing happens. Here is my code for that action.
filesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String itemName = filesListView.getItemAtPosition(position).toString();
FileInputStream fis;
String content = null;
try {
fis = openFileInput(itemName);
byte[] input = new byte[fis.available()];
while (fis.read(input) != -1) {
content += new String(input);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
textEntryEditText = (EditText) findViewById(R.id.textEntryEditText);
textEntryEditText.setText(content);
}
});
Please help. Thanks!
EDIT: SOLVED, check my Answer to see what I did.
There might be a problem with the focusable of your listView items.Set the focusable to false for the editText in the ListView.
Try to get the file or path object from the Listview adapter not file name.
when using openFileInput(String) method it creates or get the file from application files folder not from that file location. so use BaseAdapter and get File object using getItem(int) method
I believe you are using any a dapter for binding data to your listView,
So in custom adapter class
if(convertView==null){
convertView.setTag(holder);
convertView.setTag(R.string.fileName, array.get(position).getfileName());
}else {
holder = (ViewHolder) convertView.getTag();
}
then on item click try to fetch file name like this
fileName = view.getTag(R.string.fileName).toString();
Never mind, I solved it. After several hours of tears, rage, and frustration, I finally solved it, lol. But thank you everyone who responded. As for anyone else who has a similar problem, here's what I did.
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String itemName = filesListView.getItemAtPosition(position).toString();
StringBuffer fileRead = new StringBuffer("");
try {
FileInputStream fileInputStream = new FileInputStream(new File(getDir("FOLDER", Context.MODE_APPEND), itemName));
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String readString = bufferedReader.readLine();
while (readString != null) {
fileRead.append(readString);
readString = bufferedReader.readLine();
}
fileInputStream.close();
inputStreamReader.close();
bufferedReader.close();
textEntryEditText.setText(fileRead);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
My previous method of using the openFileInput was flawed, because I was trying to locate the file inside the default directory that openFileInput looks in, which is not where my file was. After, I tried referencing it directly, and found out that openFileInput does not allow this. So, I eventually tried just making a new FileInputStream, and telling it to make a new File object that uses the getDir method to reference the directory FOLDER, and the name of the file as determined by itemName. Hopefully this helps other who were struggling as I was, so that they don't have to suffer like I did. Thanks again to those who responded, even if I didn't use your advice!

How to create dynamically radiobutton while parcing a csv file in android

I'm new to Android. I want to create a group of radiobuttons in application that I'm working on, but I want to define the number of radiobuttons from csv file or database.
In a way that if I have two options in the csv file, show me 2 radiobutton and If I have 3 options in the csv file show me 3 radiobuttons.
How can i achieve this?
I'm using eclipse
1) read the csv file:
How to read csv file in android?
2) in your application add for each option a radiobutton dynamically:
how to set dynamically created Radio buttons into a RadioGroup?
Peace on you
to set dynamically created Radio buttons into a RadioGroupfor I find this solution
http://androiddesk.wordpress.com/2012/08/05/creating-dynamic-views-in-android/
and to parce the csv file I've used this fonction
private String[] loadArrayFromFileName(){
String[] liste=null;
String[] liste2=null;
String liste3=null;
int s=0;
try {
// Get input stream and Buffered Reader for our data file.
InputStream is = FocusTow.this.getAssets().open("Test.csv");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
//Read each line
while ((line = reader.readLine()) != null) {
liste2=line.split("\n");
for(int i=0; i< liste2.length;i++){
if(s==0) {
liste3=liste2[i];
s=1;
}
else liste3=liste3+","+liste2[i];
}
}
liste=liste3.split(",");
//Read each line
} catch (IOException e) {
e.printStackTrace();
}
return liste;
}
and this is the code of my button listener
mybutton.setOnClickListener(new OnClickListener() {
int j=0;
final String[] liste=loadArrayFromFileName();
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
for( j=0;j<liste.length/2;j++){
RadioButton radiobutton=new RadioButton(getApplicationContext());
radiobutton.setText(liste[j*2+1]);
radioGroup.addView(radiobutton);
}
}
});
I hope this help u,
Thanks.

Continuously Save and Auto Increment String Values to File - Android

I have code which saves a String to a file. The problem is that the String is constantly changing (as they are sensor values) but the string is only saved once, then seems to delete the file once closed and open and new one to which it prints only one value. I need it to save each value to the same file, while auto-incrementing to avoid losing any data.
Here is my code:
UPDATED: I have updated this code to the working version. The code now saves the string to the file, then updates the file each time. Thanks to #Sergii for the help!
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo_opengl_acc);
getActionBar().setTitle(R.string.title_demo_accelerometer);
viewText = (TextView) findViewById(R.id.text);
renderer = new OpenGLRenderer();
final GLSurfaceView view = (GLSurfaceView) findViewById(R.id.gl);
view.setRenderer(renderer);
}
#Override
public void onDataRecieved(TiSensor<?> sensor, String text) {
if (sensor instanceof TiAccelerometerSensor) {
try {
BufferedWriter writer =
new BufferedWriter(new FileWriter("/sdcard/test.txt", <> true));
writer.write(text);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("test", true)));
out.println(text);
out.close();
} catch (IOException e) {
//error message here or whatever...
}
}
final TiAccelerometerSensor accSensor = (TiAccelerometerSensor) sensor;
float[] values = accSensor.getData();
renderer.setRotation(values);
viewText.setText(text);
}
}
I would like to be able to open the file and see all of the values.
Thanks.
new FileWriter("/sdcard/acvalues.txt", true)
http://developer.android.com/reference/java/io/FileWriter.html#FileWriter(java.io.File, boolean)
The parameter append determines whether or not the file is opened and appended to or just opened and overwritten.
Also: How to append text to an existing file in Java

FileoutputStream / bufferreader

I have an equation which result is displayed in a TextView.
Then i have another TextView which act like a History. This History i want to save with a file and the file should be reloaded after the app will be killed an restarted.
Whats i dont understand is that the second TextView which is the View that i will save is displayed wierd stuff after starting the app
Thise line over and over again.
android.widget.TextView{41852c0 VFED.VCL ..... ID32,316-419,351 #7f09000a app:id/tvHistory}
My own Code:
final static String FILENAME = "marks.txt";
mNotenHistory=(TextView)findViewById(R.id.tVhistory);
mNotenHistory.setMovementMethod(new ScrollingMovementMethod());
private void loadTextfromFile()
{
File f = new File(getFilesDir(),FILENAME);
try {
BufferedReader br = new BufferedReader(new FileReader(f));
String line;
try {
while ((line = br.readLine()) != null)
{
mNotenHistory.setText(line+"\n"+mNotenHistory.getText());
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
#Override
public void onClick(View view)
{
[...]
mNotenHistory.setText(mNotenHistory.getText() + "\n" + string_note);
String noten_history_string = String.valueOf(mNotenHistory);
try {
FileOutputStream fo = openFileOutput(FILENAME, Context.MODE_APPEND);
fo.write(noten_history_string.getBytes());
fo.write("\n".getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Here is the offending line:
String noten_history_string = String.valueOf(mNotenHistory);
Look at this definition, from the Android documentation:
public static String valueOf(Object value)
Added in API level 1
Converts the specified object to its string representation. If the object is null return the string "null", otherwise use toString() to get the string representation.
The TextView class inherits toString() from the View class. Here is its definition:
public String toString ()
Added in API level 1
Returns a string containing a concise, human-readable description of this object. Subclasses are encouraged to override this method and provide an implementation that takes into account the object's type and data. The default implementation is equivalent to the following expression: getClass().getName() + '#' + Integer.toHexString(hashCode())
So this is your problem. String.valueOf(mNotenHistory) does not give you the text within the text view. Thus, you are writing something else (specifically, the line you mentioned) to your file. To obtain the text from your TextView, use the getText() method instead. This is what the line should look like:
String noten_history_string = mNotenHistory.getText();
Quick resume what i do want to a complish.
TextView A gets the result of an equation which is clear after each new calculation.
To save the result there is TextView B.
The Results should write from botton to top in TextView B so that the newest in on top.
The same time it should write the content of the TextView into a file.
After closing/killing the App and reopen it the TextView B will show all the saved data.
A Reset Button should clear all the content of the file so it will be empty.

Help storing data in Android

I have a button which stores whatever text is written in the text form above it when clicked. However, the application force closes when the button is clicked. What could be the problem?
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String FILEOUTPUT = Day;
BufferedWriter bfw;
try {
bfw = new BufferedWriter (new FileWriter(FILEOUTPUT));
Scanner scan = new Scanner((File) editData.getText());
bfw.write(scan.nextLine());
bfw.close();
Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_SHORT);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Save error", Toast.LENGTH_SHORT);
}
}
});
It's best to first look at the reported Exception from DDMS in these cases. Can you provide the reported exception from DDMS?
Where is editData? Is it an EditText or a TextView ? You are casting a String to a File directly in that line, instead you should be creating a File object.
should be like:
Scanner scan = new Scanner(new File(editData.getText()));

Categories

Resources