The piece of code below is from my android app. The purpose is to read text file from server and display 100 last lines of it in textview. Obviously, the code below works correctly only if number of lines in text file is 2000.
What I can think of is that I first need to go through all lines to count the number of them and then go through again to display 100 last lines in textview. I have tried nested BufferedReaders but haven't succeeded.Any ideas?
protected Void doInBackground(String...params){
URL url;
int lines = 0;
try {
//create url object to point to the file location on internet
url = new URL(params[0]);
//make a request to server
HttpURLConnection con=(HttpURLConnection)url.openConnection();
//get InputStream instance
InputStream is=con.getInputStream();
//create BufferedReader object
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String line;
//read content of the file line by line
while((line=br.readLine())!=null){
if(++lines > 1900)
text+=line + "\n";
}
br.close();
}catch (Exception e) {
e.printStackTrace();
//close dialog if error occurs
if(pd!=null) pd.dismiss();
}
return null;
}
protected void onPostExecute(Void result){
//close dialog
if(pd!=null)
pd.dismiss();
TextView txtview = (TextView) findViewById(R.id.text_view);
txtview.setMovementMethod(ScrollingMovementMethod.getInstance());
//display read text in TextView
txtview.setText(text);
}
}
}