Internal storage not being written - android

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

Related

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.

I can't read .txt files from the raw folder

I am trying to learn how basic operations work in android apps. I have a .txt file in row folder and I can't read anything. Because when I execute the code (although I don't get any logcat errors) after one second, the emulator turns into a black screen.
String str="";
InputStream is=getResources().openRawResource(R.raw.readme);
StringBuilder finalstring=new StringBuilder();
BufferedReader bf=new BufferedReader(new InputStreamReader(is));
try {
while(str!=bf.readLine()){
finalstring.append(str);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
TextView tv=(TextView)findViewById(R.id.tvli);
tv.setText(finalstring);
Your while loop appears to be the problem. The condition in it doesn't really make sense. Try:
while((str = bf.readLine()) != null){
finalstring.append(str);
}
Your current loop will never run, as it will evaluate to "while str doesn't equal the line form my text file"
Replace your while statement with this:
while((str = bf.readLine()) != null) {
finalString.append(str);
}

Large text files load not working on android [duplicate]

This question already has answers here:
how to faster read text file to ArrayList on android
(2 answers)
Closed 9 years ago.
Here is the code of function:
public void loadTextFile(String textFileName, ArrayList<String> dictionary)
{
AssetManager assetManager = getAssets(); //files manager
//reader = public bufferedReader
//word = public String
//dictionary = public ArrayList<String>
//load file to buffer
try {
reader = new BufferedReader(new InputStreamReader(assetManager.open(textFileName)));
} catch (IOException e1) {
e1.printStackTrace();
}
word = " ";
//loop, save words from buffer to dictionary
while(word != null)
{
try {
word = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
word = null;
}
if (word != null) {
dictionary.add(word);
}
}//end while
//buffer close
try {
reader.close();
} catch (IOException e1) {
e1.printStackTrace();
}
} //end function
If I try load small file <1MB, It works fine and rather fast.
If the files(partialy) are more than 1MB, but less than about 3MB, it works slow (4-6min).
If the files are bigger, it's not working, and I have information in emulator:
"The application app (process processing.test.app) has stopped unexpectedly. Please try again". I don't know what is wrong.
I try: pre-allocated ArrayList, load file to few ArrayList's, but still not working.
I will be grateful for any suggestions.
First off, word can become null somewhere along the file and the loop will exit (since you explicitly set word to null on an exception). Do you get a stack trace?
Try to move the code to a background process using AsyncTask AsyncTask
Execute on real device if you have one

Reading and writing to the file 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)

Categories

Resources