I have a file stored in my phone "SaveTT.txt" . Every word in the file is seperated by spaces. i wish to retrieve each word from the file and display every word in seperate textViews. How to do this. please help
I am able to retrieve the contents of the file into a string with the following code
try {
BufferedReader inputReader = new BufferedReader(new InputStreamReader(
openFileInput("SAVETT.txt")));
StringBuffer stringBuffer = new StringBuffer();
while ((inputString = inputReader.readLine()) != null) {
stringBuffer.append(inputString + "\n");
//EditText txt = (EditText) findViewById(R.id.temp);
//txt.setText(inputString);
}
} catch (IOException e) {
e.printStackTrace();
}
with this code get the entire string into inputString
after this . i am tokenizing the string with the following code
StringTokenizer tokenizer = new StringTokenizer(inputString);
String[] arr = new String[tokenizer.countTokens()];
while(tokenizer.hasMoreElements())
{
arr[i]= tokenizer.nextToken();
i++;
}
with the above code i am trying to save eack token in an array. Next I try to display the text in Textviews.
I dont know where i am goig wrong. the activity is stopped and a NullPointer exception is displayed.
I Figured out the problem myself. The problem was that the value of inputString is inaccessible from outside the Try catch block since it is set inside the block;
so if i write the string tokenisation block inside try catch it works perfectly fine
Related
I'm trying to show the status of something. This is done by saving the status in a textfile (Either online or offline) called status.txt
I then use this code:
try {
// Create a URL for the desired page
URL url = new URL("mywebsite.net/subfolder/status.txt");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
onlineStatus.setVisibility(View.VISIBLE);
onlineStatus.setText(str);
}
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
}
};
Nothing seems to happen, the app does not crash.
Any help would be appreciated.
Try this
URL url = new URL("http://mywebsite.net/subfolder/status.txt");
Also as good practice never completely ignore the thrown exceptions. Print the stacktrace at the very least. This is very helpful in the long term.
In your case maybe set the text to some generic error message.
Even after this, don't set the text in the while loop if you want to set the whole content in the text view.
I have a working filereader for a text file in my Raw Dir. The user should see the text file in the same format as I have formatted it in word but when the application is played, the text file is tightly grouped together with no paragraphs.
This is the file reader method below, as I said it does work but I just want the format to be as I have made it.
Your advice and guidance will be greatly appricated
#Override
protected void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.activity_support);
InputStreamReader isr = new InputStreamReader(this.getResources().openRawResource(R.raw.supporttext));
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String s;
try{
while ((s = br.readLine()) != null){
sb.append(s);
}
}catch (IOException e) {
e.printStackTrace();
}
TextView tv = (TextView)findViewById(R.id.supporttxt);
tv.setText(sb.toString());
From BufferedReader#readline java doc :
A String containing the contents of the line, not including any line-termination characters
So using readline strips the line-termination characters, that's why you do not see them in your Text View. You can add them back like this :
try{
while ((s = br.readLine()) != null){
sb.append(s);
sb.append("\n");
}
}catch (IOException e) {
e.printStackTrace();
}
Also, you should probably use getText instead of openRawResource
I want to read a txt file that contains a lot of different chunks of text separated by a string. In xcode this is pretty easy and i just use.
self.Array = [text componentsSeparatedByString: #"NEWSTRING"];
I don't seem to get this to work in android though, I can read in the whole text and put it into an array but it doesn't get separated so its just one long text.
I am using this code
AssetManager mngr;
String line = null;
boolean skillcheck = false;
StringBuffer sb = new StringBuffer(0);
String[] bb = null;
tester = new ArrayList <String>();
try {
mngr = getAssets();
InputStream is = mngr.open("mytext.txt");
InputStreamReader sir = new InputStreamReader(is);
BufferedReader br = new BufferedReader(sir);
while((line=br.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
tester.add(sb);
br.close();
} catch (IOException e1) {
}
Any good ways to do this?
You can use String.split method
String[] result = text.split("sometext");
For your acknowledgement
String.split returns the array of strings computed by splitting this
string around matches of the given regular expression
You should use StringTokenizer.
StringTokenizer sTok=new StringTokenizer(stringVariable, "newString");
while(sTok.hasMoreTokens())
System.out.println(sTok.nextToken());
stringVariable is the file contents and newString is the delimiter string.
EDIT
The second parameter of the StringTokenizer's constructor is the delimiter. It can be a new line \n or comma , or whatever you want.
I just want to delete 2 lines of text from a text file that I created. Currently, this is what I'm trying to get rid of the 2 lines:
private void deleteDataFromFile(String title, String Date) {
try {
//open the file
FileInputStream myIn= openFileInput(FILENAME);
//the reader given the input file stream.
InputStreamReader inputReader = new InputStreamReader(myIn);
//Aftert he inputstream is open, need also a bufferedReader
BufferedReader BR = new BufferedReader(inputReader);
//holds a line of input
String line;
//used for only erasing one date.
int counter = 0;
while ((line = BR.readLine()) != null && counter < 1) {
if (line.equals(title)) {
line.replace(title, "" + "\n");
line = BR.readLine();
line.replace(Date, "" + "\n");
counter++;
}
}
BR.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I realize that since I'm using the replace function on a string it has no effect on the actual file itself, but I can not find any other function in the IO library to affect the text file. What I'm thinking about doing is creating a new file on the phone with the exact contents of this file and just deleting the 2 lines from it. That seems troublesome and inefficient though, and I'd like to avoid it. Any suggestions?
try {
HttpResponse response = new DefaultHttpClient().execute(
new HttpGet(requestString));
InputStream is = response.getEntity().getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while ((line=br.readLine()) != null){
long temp = Long.parseLong(line);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Also check for valid response. Why would anyone cast web response to Long ?
Use StringBuilder or simple String for fetching response.
eg.
.
.
StringBuilder reponseBuilder=new StringBuilder("");
while ((line=br.readLine()) != null){
//long temp = Long.parseLong(line);
reponseBuilder.append(line);
}
.
.
And then use it as per scenario may be converting it to a String using:
reponseBuilder.toString();
and if still your facing same issue then,
Yup, This is truly regarding invalid permission stuff.
Add below code,
<uses-permission android:name="android.permission.INTERNET">
as child of your manifest file. And this will work as magic.
You haven't told us what error you are getting, but my guess would be that this line is giving you problems:
long temp = Long.parseLong(line)
Are you trying to parse HTTP reply as series of lines where each line contains a long?