Tuesday, March 29, 2016

Load something from Internet using URLConnection and BufferedReader, in Thread

Previous post show how to Load something from Internet using URLConnection and BufferedReader, in AsyncTask. This post show how to do it in Thread, and update UI using Handler.



MainActivity.java
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;

public class 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 = new MyThread("http://android-er.blogspot.com", textResult);
        myThread.start();
    }

    class MyThread extends Thread{
        String target;
        TextView textviewResult;

        private Handler handler = new Handler();

        public MyThread(String target, TextView textviewResult) {
            super();
            this.target = target;
            this.textviewResult = textviewResult;
        }

        @Override
        public void run() {
            String result = "";

            try {
                URL url = new URL(target);
                URLConnection urlConnection = url.openConnection();
                InputStream inputStream = urlConnection.getInputStream();
                InputStreamReader inputStreamReader =
                        new InputStreamReader(inputStream);
                BufferedReader buffReader = new BufferedReader(inputStreamReader);

                String line;
                while ((line = buffReader.readLine()) != null) {
                    result += line;
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            final String finalResult = result;
            handler.post(new Runnable() {
                @Override
                public void run() {
                    textviewResult.setText(finalResult);
                    Toast.makeText(MainActivity.this,
                            "finished", Toast.LENGTH_LONG).show();
                }
            });
        }
    }
}


For layout and AndroidManifest.xml, refer to the previous post "Load something from Internet using URLConnection and BufferedReader, in AsyncTask".

Related:
Load something from Internet using URLConnection and ReadableByteChannel, in Thread

No comments: