Android: Read a text file from assets from custom line - android

I'm using this code to read text from assets:
private void Read(String file){
try{
String Name = file;
Name = Name.replaceAll("'", "");
file = getAssets().open(Name + ".txt");
reader = new BufferedReader(new InputStreamReader(file));
line = reader.readLine();
Text ="";
while(line != null){
line = reader.readLine();
if (line !=null){
Text += line+"\n";
LineNumber++;
if(LineNumber==50){btnv.setVisibility(View.VISIBLE);break; }
}
}
if (LineNumber<50){btnv.setVisibility(View.GONE);}
txtv.setText(Text);
}
catch(IOException ioe){
ioe.printStackTrace();
}
}
So I have to read first 50 lines of text, because the text is more then 300 lines, and all I know is to read file line by line, so if I read 300 lines line by line the app freezes for to long, so I read 50 first lines then 50 other lines and so on...
So after I read the first 50 lines with that code I call this other code to read next ones:
private void ContinueReading(){
if (LineNumber >= 50){
try{
while(line != null){
line = reader.readLine();
if (line !=null){
Text += line+"\n";
LineNumber++;
if (LineNumber==100){break;}
if (LineNumber==150){break;}
if (LineNumber==200){break;}
if (LineNumber==250){break;}
if (LineNumber==300){break;}
if (LineNumber==350){break;}
if (LineNumber==400){break;}
if (LineNumber==450){break;}
}
else{
btnv.setVisibility(View.GONE);
}
}
txtv.setText(Text);
}
catch(IOException ioe){ioe.printStackTrace();}
}
}
But as you see I leave open :
file = getAssets().open(emri + ".txt");
reader = new BufferedReader(new InputStreamReader(file));
And this is no good, is anyway to close them and open them again and start reading from last line, or any idea how to start reading from ex. line 50, then from line 100, etc.. ?

This looks like a good place for an AsyncTask. You can even update the TextView with the text as it's being read from the file.
txtv.setText("");
new MyFileReader().execute(filename);
.
.
.
// inner class
public class MyFileReader extends AsyncTask<String, String, Void> {
#Override
protected Void doInBackground(String... params) {
try{
InputStream file = getAssets().open(params[0].replaceAll("'", "") + ".txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(file));
String line;
while ((line = reader.readLine()) != null) {
publishProgress(line + "\n");
}
reader.close();
} catch(IOException ioe){
Log.e(TAG, ioe);
}
return null;
}
#Override
protected void onProgressUpdate(String... values) {
txtv.append(values[0]);
}
}

You should use another Thread to read the complete file at once,
Please read this Asynctask in Android
But be care full you can not perform any UI related operations(Like change text of a TextView) on a different Thread instead Of Main Thread....! For that purpose, please also concern below link,
Android “Only the original thread that created a view hierarchy can touch its views.”

Related

Load simple JSON file into 2 dimensional Array in Android

Driving myself crazy over the simplest thing. I have a JSON file called config.txt. The file is shown below.
{
"UsePipesInGuestData": true
}
All I want to do is get a 2 dimensional array such that:
Array[0] = UsePipesInGuestData and
Array[1] = true
I have been trying for 4 hours with various attempts, my most recent is shown below:
private void getConfig(){
//Function to read the config information from config.txt
FileInputStream is;
BufferedReader reader;
try {
final File configFile = new File(Environment.getExternalStorageDirectory().getPath() + "/guestlink/config.txt");
if (configFile.exists()) {
is = new FileInputStream(configFile);
reader = new BufferedReader(new InputStreamReader(is));
String line = reader.readLine();
while (line != null) {
line = reader.readLine();
if(line!= null) {
line = line.replace("\"", ""); //Strip out Quotes
line = line.replace(" ", ""); //Strip out Spaces
if ((!line.equals("{")) || (!line.equals("}"))) {
} else {
String[] configValue = line.split(":");
switch (configValue[0]) {
case "UsePipesInGuestData":
if (configValue[1].equals("true")) {
sharedPreferences.edit().putString("UsePipes", "true").apply();
} else {
sharedPreferences.edit().putString("UsePipes", "false").apply();
}
break;
}
}
}
}
reader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
I cannot seem to ignore the lines with the { and } in them.
Clearly there MUST be an easier way. JAVA just seems to take an extremely large amount of code to do the simplest thing. Any help is greatly appreciated.
I believe your condition is incorrect. You try to read the file in the else of the condition (!line.equals("{")) || (!line.equals("}")). Simplifying, your code will run when the following happens:
!(!{ || !}) => { && } (applying De Morgan's law)
This means you will only run your code when the line is "{" AND it is "}" which is a contradiction. Try using simple conditions, like (!line.equals("{")) && (!line.equals("}")) (this is when you want to execute your code).
Additionally, you may be getting end of line characters (\n) in your string, which will make your condition fail ("{\n" != "{"). I suggest you debug and see the actual values you're getting in those lines.

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.

Loading data into a content provider

I have a long list of words and their definitions in a Google spead sheet. What would be the best way to load this data into a content provider.
You should check out the Android Sample Project called "Searchable Dictionary" from the sdk samples. You can download the samples using the Android sdk manager. The sample does something similar to what you are trying to accomplish.
They have a file called definitions.txt with the words and their definitions in a folder called "raw" under resources. Then in their SqliteOpenHelper class they are loading the words in the onCreate method with in a separate thread.
Here is a snippet of the method they are running.
private void loadWords() throws IOException {
Log.d(TAG, "Loading words...");
final Resources resources = mHelperContext.getResources();
InputStream inputStream = resources.openRawResource(R.raw.definitions);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String line;
while ((line = reader.readLine()) != null) {
String[] strings = TextUtils.split(line, "-");
if (strings.length < 2) continue;
long id = addWord(strings[0].trim(), strings[1].trim());
if (id < 0) {
Log.e(TAG, "unable to add word: " + strings[0].trim());
}
}
} finally {
reader.close();
}
Log.d(TAG, "DONE loading words.");
}

Android - Comparing String Input On A Textfile Content

May I ask you to guide me how I can accomplish this problem?
I need to compare an inputWord to a string inside a .txt file and if found, return the whole line but if not, show "word not found".
Example:
inputWord: abacus
Text file content:
abaca - n. large herbaceous Asian plant of the banana family.
aback - adv. archaic towards or situated to the rear.
abacus - n. a frame with rows of wires or grooves along which beads are slid, used for calculating.
...
so on
Returns: abacus with its definition
What i am trying to do is compare my inputWord to the words before the " - " (hyphen as delimiter), if they dont match, move to the next line. If they match, copy the whole line.
I hope it doesnt seem like im asking you to "do my homework" but I tried tutorials around different forums and sites. I also read java docs but i really cannot put them together to accomplish this.
Thank you in advance!
UPDATE:
Here's my current code:
if(enhancedStem.startsWith("a"))
{
InputStream inputStream = getResources().openRawResource(R.raw.definitiona);
try {
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
String s = in.readLine();
String delimiter = " - ";
String del[];
while(s != null)
{
s = in.readLine();
del = s.split(delimiter);
if (enhancedStem.equals(del[0]))
{
in.close();
databaseOutput.setText(s);
break;
}
}
in.close();
}
catch (FileNotFoundException e) {
databaseOutput.setText("" + e);
}
catch (IOException e1) {
databaseOutput.setText("" + e1);
}
}
Thanks a lot! Here's what I came up, and it returns the definition of inputs properly but the problem is, when i enter a word not found in the textfile, the app crashes. The catch phrase doesn't seem to work. Have any idea how I can trap it? Logcat says NullPointerExcepetion at line 4342 which is
s = in.readLine();
Assuming that the format of each line in the text file is uniform. This could be done in the following manner :
1) Read the file line by line.
2) Split each line based on the delimiter and collect the split String tokens in a temp String array.
3) The first entry in the temp token array will be the word before the "-" sign.
4) Compare the first entry in the temp array with the search string and return the entire line if there is a match.
Following code could be put up in a function to accomplish this :
String delimiter = "-";
String[] temp;
String searchString = "abacus";
BufferedReader in = new BufferedReader(new FileReader(file));
while (in.readLine() != null) {
String s = in.readLine();
temp = s.split(delimiter);
if(searchString.equals(temp[0])) {
in.close();
return s;
}
}
in.close();
return ("Word not found");
Hope this helps.
you may try like:
myreader = new BufferedReader(new FileReader(file));
String text = "MyInput Word";
while(!((text.equals(reader.readLine())).equals("0")));

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