i am new to android and dont know much .i need help to change this code . i want to download some text from a website. if i use the code: new DownloadTextTask().execute("http://www.test.com/"); it doesnt show the downloaded text in TextView but if i reopen the app i can see the test. i think its because its asyncrounous. and it has delay to download text.
how can i fix this . or just use this code instead: (i mean using DownloadText() function directly! it didnt work when i tried!)
TextView txt = (TextView)findViewById(R.id.textTest);
txt.setText(DownloadText("http://www.test.com/"));
All the codes :
public class MainActivity extends AppCompatActivity {
public InputStream OpenHttpConnection(String urlString) throws IOException
{
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
}
catch (Exception ex)
{
Log.d("MainActivity", ex.getLocalizedMessage());
throw new IOException("Error connecting");
}
return in;
}
public String DownloadText(String URL)
{
int BUFFER_SIZE = 2000;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
} catch (IOException e) {
Log.d("MainActivity", e.getLocalizedMessage());
return "";
}
InputStreamReader isr = new InputStreamReader(in);
int charRead;
String str = "";
char[] inputBuffer = new char[BUFFER_SIZE];
try {
while ((charRead = isr.read(inputBuffer))>0) {
//---convert the chars to a String--- String readString = String.copyValueOf(inputBuffer, 0, charRead); str += readString; inputBuffer = new char[BUFFER_SIZE]; } in.close(); } catch (IOException e) { Log.d("MainActivity", e.getLocalizedMessage()); return ""; } return str; }
private class DownloadTextTask extends AsyncTask {
protected String doInBackground(String... urls) {
return DownloadText(urls[0]);
}
@Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
}
}
public static class xmlClass
{
public static String xml ="";
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//new DownloadTextTask().execute("http://www.test.com/");
TextView txt = (TextView)findViewById(R.id.textTest);
txt.setText(DownloadText("http://www.test.com/"));
}
}
Aucun commentaire:
Enregistrer un commentaire