views:

106

answers:

1
package com.android.handler;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class HandlerEx extends Activity {
    public ProgressDialog progressDialog;
    public Button start ;
    public TextView tv ;
    public Bitmap bitmap;
    public static int flag = 1;

    private Handler messageHandler = new Handler() {

        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            TextView text = (TextView) findViewById(R.id.text);
            ImageView img = (ImageView) findViewById(R.id.img);
            switch (msg.what) {
            case 1:
                text.setVisibility(View.GONE);
                img.setImageBitmap((Bitmap)(msg.getData().getParcelable("bitmap")));
                img.setVisibility(View.VISIBLE);
                break;

            case 2:
                img.setVisibility(View.GONE);
                text.setText(msg.getData().getString("text"));
                text.setVisibility(View.VISIBLE);
                break;

            case 3:
                img.setVisibility(View.GONE);
                text.setText(msg.getData().getString("text"));
                text.setVisibility(View.VISIBLE);
                break;
            }
            progressDialog.dismiss();
        }

    };
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        fetchData();
        progressDialog.dismiss();

        start = (Button) findViewById(R.id.click);

        start.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {


                switch (flag) {
                case 1:
                    downloadImage("http://www.android.com/media/wallpaper/gif/android_logo.gif");
                    flag = 2;
                    break;

                case 2:
                    downloadText("http://saigeethamn.blogspot.com/feeds/posts/default");
                    flag = 3;
                    break;
                case 3:
                    fetchData();
                    flag = 1;
                    break;
                }


            }
        });
    }

    protected void fetchData() {


        progressDialog = ProgressDialog.show(this, "", "Doing...");


        new Thread() {


            public void run() {
                Message msg = Message.obtain();
                try {

                    msg.what=3;
                    Thread.sleep(1800);
                    Bundle b = new Bundle();
                    b.putString("text", "clicked");
                    msg.setData(b);
                } catch (InterruptedException e) {
                }
                messageHandler.sendMessage(msg);
            }

        }.start();
    }


    /*
     * Method for downloading the text
     * @param String as url
     * @response set data in handler
     * 
     */


    private void downloadText(String urlStr) {
        progressDialog = ProgressDialog.show(this, "", "Fetching Text...");
        final String url = urlStr;

        new Thread () {

            public void run() {
                int BUFFER_SIZE = 2000;
                InputStream in = null;
                Message msg = Message.obtain();
                msg.what=2;
                try {

                    in = openHttpConnection(url);
                    InputStreamReader isr = new InputStreamReader(in);
                    int charRead;
                    String text = "";
                    char[] inputBuffer = new char[BUFFER_SIZE];
                    while ((charRead = isr.read(inputBuffer))>0)
                    {
                        //---convert the chars to a String---
                        String readString =
                            String.copyValueOf(inputBuffer, 0, charRead);
                        text += readString;
                        inputBuffer = new char[BUFFER_SIZE];
                    }
                    Bundle b = new Bundle();
                    b.putString("text", text);
                    msg.setData(b);
                    in.close();

                } catch (IOException e) {
                    e.printStackTrace();
                }
                messageHandler.sendMessage(msg);
            }
        }.start();

    }

    /*
     * Method for downloading image from url
     * @param String as url
     * @response set data to handler
     */

    private void downloadImage(String urlStr) {
        progressDialog = ProgressDialog.show(this, "", "Fetching Image...");
        final String url = urlStr;

        new Thread() {
            public void run() {
                InputStream in = null;
                Message msg = Message.obtain();
                msg.what = 1;
                try {

                    in = openHttpConnection(url);
                    bitmap = BitmapFactory.decodeStream(in);
                    Bundle b = new Bundle();
                    b.putParcelable("bitmap", bitmap);

                    msg.setData(b);
                    in.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }

                messageHandler.sendMessage(msg);

            }
        }.start();
    }
    /* method for httpconnection
     * @param string as url
     * @return inputstream
     */
    private InputStream openHttpConnection(String urlStr) {
        InputStream in = null;
        int resCode = -1;

        try {


            URL url = new URL(urlStr);
            URLConnection urlConn = url.openConnection();

            if (!(urlConn instanceof HttpURLConnection)) {

                throw new IOException ("URL is not an Http URL");

            }

            HttpURLConnection httpConn = (HttpURLConnection)urlConn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();
            resCode = httpConn.getResponseCode();


            if (resCode == HttpURLConnection.HTTP_OK) {

                in = httpConn.getInputStream(); 

            } 

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

        return in;
    }


}
A: 

check ur AndroidMainfest.xml for this line

<uses-permission android:name="android.permission.INTERNET" />
Tilsan The Fighter