I'm making an android application that downloads some text from a web page and puts it in a String
, then it prints the string in a TextView
. But the content of the web page can change every seconds, so i want TextView
to update in real-time, showing the new String
every seconds. To download text from the webpage and set TextView
's text I used AsyncTask
, and i called the execute()
in onCreate()
method, in main Activity
. I don't know how update it, without make application crashed.
Sorry for bad English, that's my MainActivity:
package com.example.pack;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity
{
TextView textView;
URL url;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
url = null;
try
{
url = new URL("myURL");
}
catch (MalformedURLException e) {}
new VariabileLikeTask(textView).execute(url);
}
}
And that's my aSyncTask:
package com.example.pack;
import android.os.AsyncTask;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
public class VariabileLikeTask extends AsyncTask<URL, Void, CharSequence>
{
TextView textView;
public VariabileLikeTask(TextView textView)
{
this.textView = textView;
}
@Override
protected String doInBackground(URL... urls)
{
URL url = urls[0];
InputStream in = null;
int risposta = -1;
String text = "";
try
{
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("No connection");
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
risposta = httpConn.getResponseCode();
if (risposta == HttpURLConnection.HTTP_OK)
in = httpConn.getInputStream();
BufferedReader bf = new BufferedReader(new InputStreamReader(in));
text = bf.readLine();
in.close();
bf.close();
}
catch (Exception ex) {}
return text;
}
@Override
protected void onPostExecute(CharSequence text)
{
textView.setText(text);
}
}
Sorry if the format code is wrong, this is my first thread.