Load Something From Mesh Using Urlconnection As Well As Bufferedreader, Inwards Thread

Posted on

Previous post service present how to Load something from Internet using URLConnection too BufferedReader, inward AsyncTask. This post service present how to exercise it inward Thread, too update UI using Handler.


package com.blogspot.android_er.androidinternet;  import android.os.Bundle; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import android.widget.Toast;  import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection;  populace cast MainActivity extends AppCompatActivity {      TextView textResult;      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);         textResult = (TextView)findViewById(R.id.tresult);          MyThread myThread = novel MyThread("https://rootandroid.org/", textResult);         myThread.start();     }      cast MyThread extends Thread{         String target;         TextView textviewResult;          someone Handler handler = novel Handler();          populace MyThread(String target, TextView textviewResult) {             super();             this.target = target;             this.textviewResult = textviewResult;         }          @Override         populace void run() {             String outcome = "";              assay {                 URL url = novel URL(target);                 URLConnection urlConnection = url.openConnection();                 InputStream inputStream = urlConnection.getInputStream();                 InputStreamReader inputStreamReader =                         novel InputStreamReader(inputStream);                 BufferedReader buffReader = novel BufferedReader(inputStreamReader);                  String line;                 land ((line = buffReader.readLine()) != null) {                     outcome += line;                 }              } select cause got of (MalformedURLException e) {                 e.printStackTrace();             } select cause got of (IOException e) {                 e.printStackTrace();             }              lastly String finalResult = result;             handler.post(new Runnable() {                 @Override                 populace void run() {                     textviewResult.setText(finalResult);                     Toast.makeText(MainActivity.this,                             "finished", Toast.LENGTH_LONG).show();                 }             });         }     } }  

For layout and AndroidManifest.xml, elevate to the previous post service “Load something from Internet using URLConnection too BufferedReader, inward AsyncTask“.

– Load something from Internet using URLConnection too ReadableByteChannel, inward Thread