Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpURLConnection fails on Android 4.0

I am using this code to fetch my changelog from the net.

InputStream content = null;
           try {


               URL url = new URL("http://dreamhawk.blinkenshell.org/changelog.txt");
               HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
               urlConnection.setRequestMethod("GET");
               urlConnection.connect();

               content = urlConnection.getInputStream();


               BufferedReader r = new BufferedReader(new InputStreamReader(content));
               StringBuilder total = new StringBuilder();
               String line;
               String NL = System.getProperty("line.separator");
               try {
                   while ((line = r.readLine()) != null) {
                       total.append(line + NL);
                   }
               } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
               }

               String page = total.toString();

               Dialog dialog = new Dialog(Main.this);

               dialog.setContentView(R.layout.custom_dialog);
               dialog.setTitle(R.string.changelog);
               dialog.setCanceledOnTouchOutside(true);

               TextView text = (TextView) dialog.findViewById(R.id.text);
               text.setTextSize(13);
               text.setText(page);
               dialog.show();
           } catch (Exception e) {
               //handle the exception !
           }

This works, on Android 2.3 and below... But since the ICS update, i am getting nothing! No dialog, no response, no nothing! Help! :/

like image 451
DreamHawk Avatar asked Dec 06 '22 17:12

DreamHawk


1 Answers

I know in android 3.0 network connection on the main thread isnt permitted.

StrictMode is turned on automatically. Im sure it is the same for 4.0

To fix the issue, you must perform the network connection on a separate thread... for example, using an AsyncTask.


Read this blog post on the subject:

Why Ice Cream Sandwich Crashes Your App

like image 119
coder_For_Life22 Avatar answered Dec 26 '22 08:12

coder_For_Life22