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
Related
I just started to learn developping android and I have a (probably) basic questions, but I didn't find anything clear.
I'm trying to store data in a JSON file, well, I've understood the logic to store it, my way is:
public boolean writeFileJson(JSONObject jobj) {
try {
FileOutputStream fOut = openFileOutput(file, Context.MODE_PRIVATE);
fOut.write(jobj.toString().getBytes());
fOut.close();
Toast.makeText(getBaseContext(), "file saved", Toast.LENGTH_SHORT).show();
} catch (Exception e1) {
e1.printStackTrace();
}
return true;
}
But my problem is to read, and concretely for the first time, because the way I do it is:
public String readFileJson() {
int c;
String temp = "";
try {
FileInputStream fin = openFileInput(file);
while ((c = fin.read()) != -1) {
temp = temp + Character.toString((char) c);
}
Toast.makeText(getBaseContext(), "file read", Toast.LENGTH_SHORT).show();
} catch (Exception e2) {
}
return temp;
}
So wen I read it for the first time and I want to acces to a parameter of my JSON is obvious that any JSON Object already exist in the file.
So I try to save a first JSON Object with my parameters in onCreate() method and save it in the file, but wen I run the app, and I stop it, it returns again to execute onCreate() and deletes all data stored during the run time.
So my question is: There is any way to init only for one time the parameters of the JSON file to could access for the first time unlike it's empty???
I hope that I'd explained well!!
Thanxxxx!!!!
You can create your own flag boolean and check when you start.
Well I don't understand well why you can use a flag if the flag is set to init value in onCreate(), but I've tried a basic method: check each time if the json file is null. But it's like so basic no? Is there any ther way, or trying to understand how to use flags without reset their values?
msgjson = readFileJson();
if(msgjson == "") {
json.put("ARRAY", jsonArray);
}else{
json = new JSONObject(msgjson);
}
Thanx!!
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
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);
}
I am trying to get the Logcat (at least last few lines) on a button click but nothing comes up -
view.findViewById(R.id.logdone).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Make file name.
String fullName = "userlogs";
// Extract to file.
File file = new File(fullName);
InputStreamReader reader = null;
FileWriter writer = null;
try
{
// get input stream
String cmd = "logcat -d -v time";
Process process = Runtime.getRuntime().exec(cmd);
reader = new InputStreamReader (process.getInputStream());
// write output stream
writer = new FileWriter (file);
char[] buffer = new char[10000];
do
{
int n = reader.read (buffer, 0, buffer.length);
if (n == -1)
break;
writer.write (buffer, 0, n);
} while (true);
reader.close();
writer.close();
}
catch (IOException e)
{
if (writer != null)
try {
writer.close();
} catch (IOException e1) {
}
if (reader != null)
try {
reader.close();
} catch (IOException e1) {
}
e.printStackTrace();
return;
}
}
}
NOTE:
I do have permissions -
<uses-permission android:name="android.permission.READ_LOGS" />
UPDATE:
My most of the content is in Log.d() then Log.v() then Log.e() then Log.i(). But how to get the last event lines on a button click. My purpose is to get those lines and send them via email to the developer.
I am using the popular third party API known as ACRA to send email which is working fine.
I can use StringBuilder to put all my device logs into it and then to send via email.
But I am unable to get.
Any elegant way that works well effectively ?
Given the comment I made about the READ_LOGS permission no longer being granted to non-system apps, I would instead recommend using a MemoryHandler with a standard Java Logger. On a button click, you can push the messages to a target StreamHandler (which you can use to just dump them into the output buffer of your choice).
Is it possible to get the last few lines of a logcat on a button click?
There has never been a documented and supported way for apps to get anything from LogCat. And, as Turix notes, things were locked down further in Android 4.2.
Any elegant way that works well effectively ?
Log the data yourself to a file that you control, rather than (or in addition to) logging the data to LogCat.
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