I am new to Android programming and can really use some help with the program I am writing to establish an Http connection and display an image.
I use Wei Meng Li's book, βGetting Started Developing Android Applications.β The code compiles and there are no errors, but every time I run the program, the error message "error message" appears. Image is not displayed.
I have looked at various code samples for GET requests, but cannot find anything that works with my code.
Any help that anyone can offer will be very grateful, as I try my best to see a solution.
The last line of use-permission code was included in the manifest.
ImageView image; private InputStream OpenHttpConnection(String urlString) throws IOException { InputStream in = null; int response = -1; URL url = new URL(urlString); URLConnection conn = url.openConnection(); if(!(conn instanceof HttpURLConnection)) throw new IOException("Not an HTTP Connection"); try { HttpURLConnection httpConn = (HttpURLConnection) conn; httpConn.setAllowUserInteraction(false); httpConn.setInstanceFollowRedirects(true); httpConn.setRequestMethod("GET"); httpConn.connect(); response = httpConn.getResponseCode(); if (response == HttpURLConnection.HTTP_OK) { in = httpConn.getInputStream(); } } catch (Exception ex) { throw new IOException("Error connecting"); } return in; } private Bitmap DownloadImage(String URL) { Bitmap bitmap = null; InputStream in = null; try { in = OpenHttpConnection(URL); bitmap = BitmapFactory.decodeStream(in); in.close(); } catch (IOException e1) { Toast.makeText(this, e1.getLocalizedMessage(), Toast.LENGTH_LONG).show(); e1.printStackTrace(); } return bitmap; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_network); Bitmap bitmap = DownloadImage("http://www.mayoff.com/5-01cablecarDCP01934.jpg"); image = (ImageView) findViewById(R.id.image); image.setImageBitmap(bitmap); } <uses-permission android:name="android.permission.INTERNET" />
source share