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);
}
Related
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.
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")));
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
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)
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);