Help storing data in Android - 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()));

Related

open text file from several file when clicked on button in 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.

Can not read text files

I am trying to write and read a text file which is full of words and add it to an ArrayList. The ArrayList later is used from another part of the program to display text in a TextView. But when i run the program and open the specific part of it, then there is nothing. The ArrayList is just empty. I don't get any exceptions but for some reason it doesn't work. Please help me.
I don't seem to have problems with the file writing:
TextView txt = (TextView)findViewById(R.id.testTxt);
safe = txt.getText().toString();
try {
FileOutputStream fOut = openFileOutput("test.txt", MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
try {
osw.write(safe);
osw.flush();
osw.close();
Toast.makeText(getBaseContext(), "Added to favorites", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException ex){
Log.e("Exception", "File write failed: ");
}
} catch (IOException e) {
Log.e("Exception", "File write failed: ");
}
But I think the problem is in the file reading. I made some "Log.d" and found out that everything works fine till the InputStreamReader line:
public favHacks() {
testList = new ArrayList<String>();
try {
//Works fine till here
InputStreamReader inputStreamReader = new InputStreamReader(openFileInput("test.txt"));
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
while ( (receiveString = bufferedReader.readLine()) != null )
{
testList.add(receiveString);
}
bufferedReader.close();
}
catch (FileNotFoundException ex) {
Log.d("login activity", "File not found: ");
} catch (IOException ex) {
Log.d("login activity", "Can not read file: ");
}
}
If you have a relatively small collection of key-values that you'd like to save, you should use the SharedPreferences APIs.
http://developer.android.com/training/basics/data-storage/shared-preferences.html
also if you want to write/read files, or do any kind of operations that can block the Main Thread try to use another Thread like when you are trying to save the data in a file or use a Handler if you have multiple Threads (one for saving and one for reading).
https://developer.android.com/training/multiple-threads/index.html
In your code the method called favHacks can return an ArrayList with the list of all the strings Something like
//
public ArrayList<String> readFromFile(String file){
ArrayList<String> mArrayList= new ArrayList<String>();
//read from file here
return mArrayList;
}
but as I said before, you need to the operations that can block the UI thread in a new Thread.
https://developer.android.com/training/multiple-threads/communicate-ui.html
And also I think that the best way to do this is using Asynk task
Why and how to use asynctask

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

Android - ObjectInputStream keeps on reading the previous value even with .reset()

I'm building an application for sending files between two Android phones, now i have a ListActivity that retrieves the sdcard and lists the files, when the ListActivity first starts on the two devices a ServerSocket is set up and listening with .accept() ...
this thread starts when the ListActivity starts :
ReceiveFileSendRequestThread ReceiveFileSendRequestThread = new ReceiveFileSendRequestThread();
ReceiveFileSendRequestThread.start();
and here is the full thread class:
static public class ReceiveFileSendRequestThread extends Thread {
public void run() {
ServerSocket serverSocket;
try {
serverSocket = new ServerSocket(6789, 200);
connectionServ = serverSocket.accept();
requestFileInServer = new ObjectInputStream(
connectionServ.getInputStream());
requestFileString = (String) requestFileInServer.readObject();
handler.post(new AcceptFileSendAlertDialogRunnable());
while (okToSend == null) {
}
if (okToSend == true) {
requestFileOutServer = new ObjectOutputStream(
connectionServ.getOutputStream());
requestFileOutServer.writeObject("oktosend");
requestFileOutServer.flush();
serverSocket.close(); // // Receive File
} else if (okToSend == false) {
requestFileOutServer = new ObjectOutputStream(
connectionServ.getOutputStream());
requestFileOutServer.reset();
requestFileOutServer.writeObject("notosend");
requestFileOutServer.flush();
serverSocket.close();
ReceiveFileSendRequestThread ReceiveFileSendRequestThread = new ReceiveFileSendRequestThread();
ReceiveFileSendRequestThread.start();
}
} catch (IOException e) {
Log.d("Connection Error:", "Error binding port!");
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And when onLongClick on an item (to send file) the following thread starts:
public boolean onItemLongClick(AdapterView<?> parentView, View childView,
int position, long id) {
// TODO Auto-generated method stub
fileClickedName = (((TextView) childView).getText()).toString();
fileClickedPath = file.toString() + "/" + fileClickedName;
fileClickedFile = new File(fileClickedPath);
SendFileThread SendFileThread = new SendFileThread();
SendFileThread.start();
return true;
}
SendFile Thread:
static public class SendFileThread extends Thread {
public void run() {
Socket socket = new Socket();
try {
socket.connect(new InetSocketAddress(sharedIp, 6789), 200);
requestFileOutClient = new ObjectOutputStream(
socket.getOutputStream());
requestFileOutClient.writeObject(fileClickedName);
requestFileOutClient.flush();
requestFileInClient = new ObjectInputStream(
socket.getInputStream());
toSendOrNot = (String) requestFileInClient.readObject();
if (toSendOrNot.equals("oktosend")) {
socket.close();
} else if (toSendOrNot.equals("notosend")) {
socket.close();
ReceiveFileSendRequestThread ReceiveFileSendRequestThread = new ReceiveFileSendRequestThread();
ReceiveFileSendRequestThread.start();
handler.post(new ClientFileSendAlertDialogRunnable());
}
// //
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Now, when I launch the ListActivity and longClick on an item, the the file name is sent to the second device, the second device pops up an alertDialog asking the user if to accept the file or not, (accepting file is still not ready for now) if the user presses on CANCEL (on the ReceiveFileSendRequestThread) a string is sent to the first device "notosend", the first user receives the string "notosend" and depending on that the thread closes the socket and re invoke the thread to listen to the second peer if he wants to send another file , AND pops up an alertDialog telling the first user that your file was refused to be received ... >>>> this is totally works >>>> but when the first device attempts to send another file (long press again on a file [item on the list] ) the second user receives the new file name selected by the first user successfully and alertDialog pops up if to accept or cancel BUT the first user receives that the file send was refused ... without having the second user pressing on the cancel button !!! ... i don't know why toSendOrNot = (String) requestFileInClient.readObject(); keeps on taking the previous value without even waiting for the second device to write the new object.
I would appreciate it if someone could help me with this , Many thanks.
AFTER HOURS OF DEBUGGING >>> I FINALLY FOUND THE BUG!
in thread ReceiveFileSendRequestThread() the Boolean variable okToSend is null when first receiving a request from the second device, when the second device cancels the request the oKtoSend will be set to notosend, so whenever the second device attempts to send another file the variable okToSend will always has the previously assigned value. So I simply added okToSend = null; before the while loop, and now is working perfectly.

Android application crashing despite exception caught

I'm writing a simple app which allows a user to enter their income and it deducts tax, then saves the amount in a file for future reference. Whenever I try to enter an amount I get a warning saying the application has stopped unexpectedly. Here is my code:
public void onClick(View v) {
// TODO Auto-generated method stub
try {
if (preTax !=null){
Double incomeAmount = Double.parseDouble(preTax.getText().toString());
incomeAmount =- (20 *100)/incomeAmount;
Double incomeRounded = Round(incomeAmount);
Toast.makeText(null, "Your income minus tax = "+incomeRounded, Toast.LENGTH_LONG).show();
FileOutputStream fos = openFileOutput("income", Context.MODE_PRIVATE);
fos.write("1000".getBytes());
fos.close();
}
else {
Double incomeAmount = Double.parseDouble(postTax.getText().toString());
Double incomeRounded = Round(incomeAmount);
Toast.makeText(null, "Your income is: "+ incomeRounded, Toast.LENGTH_LONG).show();
FileOutputStream fos = openFileOutput("income", Context.MODE_PRIVATE);
fos.write("1000".getBytes());
fos.close();
}
} catch (Exception e){
Toast.makeText(null, "Please fill in the catagories" + e, Toast.LENGTH_LONG).show();
}
}
This issue was happening before the fileoutstream stuff was added, so I know that that isn't the issue, but it is not clear to me what is. Program crashes regardless of whether the EditText is empty or not. Surely the try/catch should catch any errors?
Toast.makeText(null, "Please fill in the catagories" + e, Toast.LENGTH_LONG).show();
should be
Toast.makeText(v.getContext(), "Please fill in the catagories" + e, Toast.LENGTH_LONG).show();
you can't pass null in for the context, it needs to be valid.
Passing in null for the context does not exactly help. Your app in blowing up, getting caught and then blowing up again.

Categories

Resources