0

From this url : java.net.URL in android .. newbie question

when im uncomment this line my app start closed :

BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream()));

My Target is get acces to url. I mean get the html code and after that im parsing it. First try, on get image url success(sample in unused function), but for normal url i got stuck. Thanks for help..

my complete code :

public class MainActivity extends Activity {

    private ProgressDialog progressDialog;
    private Bitmap bitmap = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        final EditText editTexts = (EditText) findViewById(R.id.editText1);
        editTexts.setOnKeyListener(new EditText.OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) { // If the event is a key-down event on the "enter" button 
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) { // Perform action on key press 
                    String name = "Hello " + editTexts.getText();
                    Toast.makeText(MainActivity.this, name, Toast.LENGTH_SHORT).show();
                    TextView t = (TextView) findViewById(R.id.textView1);
                    t.setText(name);
                    if (checkInternetConenction()) {
                        //                          downloadImage("http://www.tutorialspoint.com/green/images/logo.png");
                        //https://postimg.org/image/5bjco36kl/597f512a/
                        //downloadImage("http://s10.postimg.org/5bjco36kl/Quotes_Cover_pic14.png"); // works
                        try {
                            URL url = new URL("http://www.google.com/humans.txt");
                            HttpURLConnection http = (HttpURLConnection) url.openConnection();
                            //int statusCode = http.getResponseCode();
                            String outdata = "";
                            String inputLine;
                            BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream()));
                            //while ((inputLine = in.readLine()) != null)
                            //    outdata += inputLine;
                            //t.setText(outdata);
                            //in.close();

                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }
                    }
                    //                      if(isOnline())  // works !
                    {
                        //                          Toast.makeText(MainActivity.this, "dalam in kondisi OL ?" , Toast.LENGTH_SHORT).show();
                        //                          t.setText(name+" boolean bro");
                    }
                }
                return false;
            }
        });
        return false;
    }

    public boolean isOnline() {
        ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

        Boolean res;
        res = false;
        if (conMgr.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED || conMgr.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING) {

            Toast.makeText(MainActivity.this, "online", Toast.LENGTH_SHORT).show();
            // notify user you are online
            res = true;
        } else if (conMgr.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED || conMgr.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED) {

            Toast.makeText(MainActivity.this, "offline", Toast.LENGTH_SHORT).show();
            res = false;
            // notify user you are not online
        }
        return res;
    }


    private boolean checkInternetConenction() {
        //      Toast.makeText(MainActivity.this, "here",   Toast.LENGTH_SHORT).show();

        // get Connectivity Manager object to check connection
        ConnectivityManager connec = (ConnectivityManager) getSystemService(getBaseContext().CONNECTIVITY_SERVICE);


        //        string stat = connec.getNetworkInfo(0).getState();

        //Toast.makeText(MainActivity.this, "stat"+stat,    Toast.LENGTH_SHORT).show();

        // Check for network connections
        if (connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTED ||

            connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTING ||
            connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTING ||
            connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED) {
            //          Toast.makeText(MainActivity.this, "here1",  Toast.LENGTH_SHORT).show();
            Toast.makeText(this, " Connected ", Toast.LENGTH_LONG).show();
            return true;
        } else if (
            connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.DISCONNECTED ||
            connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.DISCONNECTED) {
            //          Toast.makeText(MainActivity.this, "here2",  Toast.LENGTH_SHORT).show();
            Toast.makeText(this, " Not Connected ", Toast.LENGTH_LONG).show();
            return false;
        }
        //      Toast.makeText(MainActivity.this, "here3",  Toast.LENGTH_SHORT).show();
        return false;
    }

    private void downloadImage(String urlStr) {
        progressDialog = ProgressDialog.show(this, "", "Accessing data from " + urlStr);
        final String url = urlStr;

        new Thread() {
            public void run() {
                InputStream in = null;

                Message msg = Message.obtain();
                msg.what = 1;

                try { in = openHttpConnection(url);
                    // change start here..
                    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();
    }



    private void downloadImage_(String urlStr) {
        progressDialog = ProgressDialog.show(this, "", "Downloading Image from " + urlStr);
        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();
    }

    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;
    }

    private Handler messageHandler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            ImageView img = (ImageView) findViewById(R.id.imageView1);
            img.setImageBitmap((Bitmap)(msg.getData().getParcelable("bitmap")));
            progressDialog.dismiss();
        }
    };
}
7
  • 1
    Instead of your complete code, we need your logcat. Commented Aug 12, 2016 at 7:03
  • where i could get that? im still learn java.. and i'm testing directly on my phone, if i use avd take a age to complete the loading.. Commented Aug 12, 2016 at 7:06
  • You shouldn't be developing directly on the phone - only at last. If it runs well in the emulator, it will run faster on the device. Or you risk that your app runs decently on your super-pumped device and walks like a snail on lower end devices. Anyway, the logcat is still generated even if you run the app on your phone. Commented Aug 12, 2016 at 7:10
  • Its happening because you are doing network operation on main thread. Use some libaray for that if not try using asyctasks Commented Aug 12, 2016 at 7:11
  • @Rotwang, ok, ill take that risk.. so, where the logcat when i run my app in my phone? Commented Aug 12, 2016 at 7:14

1 Answer 1

1

You are not allowed to use an Internet connection on the Main Thread of an Android Application see here. Its probably easiest to use an AsyncTask But there are plenty of other options as well. More info can be found here.

Sign up to request clarification or add additional context in comments.

1 Comment

so it's different with test it? cz when i test it, it's works. Toast.makeText(MainActivity.this, "online", Toast.LENGTH_SHORT).show(); show the result in main display..

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.