Reading and writing to the file Android - android

I am learning Android and I am making some basic math program(game). It gets two random numbers, random operator, and 30 secs to solve math problems as much as you can. If you solve problem u get 1 point.
Anyway right now, I want to get number of points that user have made, and write it to the file, and later to read it ( for now just to log it).
When I click to button to write file, it does and I get this log message:
09-21 21:11:45.424: DEBUG/Writing(778): This is writing log: 2
Yeah, seems that it writes. Okey, lets read it.
09-21 21:11:56.134: DEBUG/Reading log(778): This is reading log:2
It reads it.
But when I try again to write, it seems that it will overwrite previous data.
09-21 21:17:19.183: DEBUG/Writing(778): This is writing log: 1
09-21 21:17:28.334: DEBUG/Reading log(778): This is reading log:1
As you can see it reads just last input.
Here it is that part of code, where I am writing and reading it.
public void zapisi() {
// WRITING
String eol = System.getProperty("line.separator");
try {
FileOutputStream fOut = openFileOutput("samplefile.txt",
MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(poenibrojanje+eol);
//for(int i=0;i<10;i++){
Log.d("Writing","This is writing log: "+poenibrojanje);
//}
//osw.flush();
osw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void citaj() {
// READING
String eol = System.getProperty("line.separator");
try {
BufferedReader input = new BufferedReader(new InputStreamReader(
openFileInput("samplefile.txt")));
String line;
StringBuffer buffer = new StringBuffer();
while ((line = input.readLine()) != null) {
buffer.append(line + eol);
}
//TextView textView = (TextView) findViewById(R.id.result);
Log.d("Reading log","This is reading log:"+buffer);
System.out.println(buffer);
//tvRezultat.setText(buffer.toString());
} catch (Exception e) {
e.printStackTrace();
}
}

You can use the openFileOutput ("samplefile.txt", MODE_APPEND)

Related

Getting current scheduler information for Android app using Android Studio

I'm trying to get the current scheduler information from the path "/sys/block/sda/queue/scheduler" to be output in my application. However, it doesn't seem to return anything, not sure what I am doing wrong here?\
private String getScheduler() {
StringBuffer sb = new StringBuffer();
String file = "/sys/block/sda/queue/scheduler"; // Gets governor for big cores
if (new File(file).exists()) {
try {
BufferedReader br = new BufferedReader(new FileReader(new File(file)));
String aLine;
while ((aLine = br.readLine()) != null)
sb.append(aLine + "\n");
if (br != null)
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
if (sb.toString().length() == 0) {
return "File not available";
}
return sb.toString();
}
It always return the string "File not available". I know this should work as I did the same thing for returning the current scaling governor. Do I need to request for root permissions within this app, even though my phone is already rooted?
Any help is greatly appreciated! Thank you so much!

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

Android - Compare String with .txt file in raw folder

I want to know how to compare string value with .txt file's every line and get equal value.
I get All values from .txt file but i don't understand how to compare it.
For example
ABC
CBA
CCC
are in my .txt file,
and in my activity
String someText = "ABC";
and how to compare it with .txt file eacline.
I done below code to get .txt file values.
String result;
try {
Resources res = getResources();
InputStream in_s = res.openRawResource(R.raw.out);
byte[] b = new byte[in_s.available()];
in_s.read(b);
result = new String(b);
tx.setText(result);
} catch (Exception e) {
// e.printStackTrace();
result = "Error: can't show file.";
tx.setText(result);
}
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("out.txt"), "UTF-8"));
// do reading, usually loop until end of file reading
String mLine = reader.readLine();
while (mLine != null) {
//process line
//mLine = reader.readLine();
if ("ABC".equals(mLine)){
Toast.makeText(this, "Yuppppiiiiii", 1000).show();
}
mLine = reader.readLine();
}
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
I think that your problem is because the way you read the file.
you currently read all file content into a string and this makes you difficult to compare.
Ok, now is the procedures:
You open the file (Create an InputStream, use the Assert, and then wrap it inside a BufferedReader)
You read it line by line, store value in a variable (Use readline() function of bufferreader)
You call the compare string function for this variable and your string (String.equal)
I hope you can understand it clearly. All remain task are about the Android docs.

Internal storage not being written

I'm trying to read from website url then write into device internal storage. Below are my code, the system output can print the line out but there is no file at internal storage.
Suppose the abc.xml will appear at "/data/data/my-package/abc.xml" but there is nothing...
Kindly help me on this problem.
try {
URL sourceUrl = new URL("mysite.php");
BufferedReader in = new BufferedReader(
new InputStreamReader(sourceUrl.openStream()));
String inputLine;
OutputStream out = openFileOutput("abc.xml", Context.MODE_PRIVATE);
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
out.write(inputLine.getBytes());
}
in.close();
out.close();
}
catch (IOException e) {
Log.d(LOG_TAG, e + "");
}
I wrote a simple function that saves a user object to the internal storage. The code works and seems like same you wrote above except 1 difference. I also add 1 more catch statement which is the following
catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
Log.e(LOGTAG, e1.toString());
return false;
}
I know it won't solve the problem but at least you may find out why it doesn't work if the program throws a FileNotFoundException

Reading Logcat within the app returns null

I read the other posts and can't figure out the "trick".
I looked at Log Collector but can't use a separate APK. I'm basically using the same approach and I consistently get nothing back on the processes inputstream.
I have READ_LOGS in the manifest.
From within my default activity, I'm able to get the log, but if I move the logic to another activity or utilize an asynctask, no output is returned.
this code is from my default activity... inline, i dump it to the log
try {
Process process = Runtime.getRuntime().exec("logcat -d");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
StringBuilder log=new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
log.append(line);
}
Log.d(LOGTAG, "Logcat: " +log.toString());
} catch (IOException e) {}
if i wrap it in an asynctask or just inline it in another activity, it returns nothing
ArrayList<String> commandLine = new ArrayList<String>();
//terminate on completion and suppress everything except the filter
commandLine.add("logcat -d -s");
...
//replace asynctask with inline (could not get log in asynctask)
showProgressDialog(getString(R.string.acquiring_log_progress_dialog_message));
final StringBuilder log = new StringBuilder();
BufferedReader bufferedReader = null;
try{
Process process = Runtime.getRuntime().exec(commandLine.toArray(new String[0]));
bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null){
log.append(line);
log.append(MangoApp.LINE_SEPARATOR);
}
sendIntent.putExtra(Intent.EXTRA_TEXT, log.toString());
startActivity(Intent.createChooser(sendIntent, getString(R.string.chooser_title)));
dismissProgressDialog();
dismissMainDialog();
finish();
}
catch (IOException e){
dismissProgressDialog();
showErrorDialog(getString(R.string.failed_to_get_log_message));
Log.e(LOGTAG, "Log collection failed: ", e);//$NON-NLS-1$
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException ignore) {}
}
}
Can anyone spot the diff or explain the magic? I'm pretty sure the commandline is right in the second version so scratching my head. I'm using 2.1 SDK 7 on the emulator.
Thanks
Hope this will be helpful, you don't have to create file by your self just execute the below command, to get the error info.
Runtime.getRuntime().exec("logcat -v time -r 100 -f /sdcard/log.txt *:E");
Logcat parameters options:
-r <size in kilobytes> -> for specifying the size of file
-f <filename> -> file to which you want to write the logs.
Can you try it without the ArrayList. Just pass the command String
I have implemented it in the following way (without the ArrayList). It works for me.
String baseCommand = "logcat -v time";
baseCommand += " MyApp:I "; // Info for my app
baseCommand += " *:S "; // Silence others
ServicesController.logReaderProcess = Runtime.getRuntime().exec(baseCommand);

Categories

Resources