I have this code, for a android app i’m working on:
package com.exercise.AndroidInternetTxt;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class AndroidInternetTxt extends Activity {
TextView textMsg, textPrompt, textSite;
final String textSource = "http://www.xxx/s.php";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textPrompt = (TextView)findViewById(R.id.textprompt);
textMsg = (TextView)findViewById(R.id.textmsg);
textSite = (TextView)findViewById(R.id.textsite);
//textPrompt.setText("Asteapta...");
URL textUrl;
try {
textUrl = new URL(textSource);
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(textUrl.openStream()));
String StringBuffer;
String stringText = "";
while ((StringBuffer = bufferReader.readLine()) != null) {
stringText += StringBuffer;
}
bufferReader.close();
textMsg.setText(stringText);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
textMsg.setText(e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
textMsg.setText(e.toString());
}
//textPrompt.setText("Terminat!");
}
}
It works fine, it outputs a text from the .php file. I would like it to autorefresh every 10 seconds, but sincerely i don`t know how to do that. Can you please help me solve this out? Thanks!
A timer task will not work, as it will create a different thread and only originating thread may touch its views.
For android the preferred way to do this is to use a handler. Ether by
or having a seperate instance of the Handler class