Reading Images From Server

By Kunal Kapoor
14-05-2018
160

In this project we will be demonstrating how to Read an image file from the server and saving it to your device and also displaying the same image in an Imageview.


First we will place an image onto our server. In our case we will be using the logo image of our website situated at URL : https://www.ourcoaching.com/images/ourcoaching-bg.png


Code:


AndroidManifest.xml:

Declaring Internet permission in Manifest file

xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ourcoaching.imagedownload">

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
intent-filter
>
activity>
application>

manifest>


activity_main.xml:

Declaring simple button, imageView and an edidtext for URL input:

xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.ourcoaching.imagedownload.MainActivity">

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Download"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.501"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.213" />

<EditText
android:id="@+id/editText"
android:layout_width="296dp"
android:layout_height="45dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:ems="10"
android:inputType="textPersonName"
android:text="https://www.ourcoaching.com/images/ourcoaching-bg.png"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.503"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.017" />

<ImageView
android:id="@+id/imageView"
android:layout_width="192dp"
android:layout_height="206dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.737"
app:srcCompat="@mipmap/ic_launcher" />

android.support.constraint.ConstraintLayout
>


MainActivity.java:

package com.ourcoaching.imagedownload;

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

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

import javax.net.ssl.HttpsURLConnection;

public class MainActivity extends AppCompatActivity {

private ImageView imageView;
private Button button;
private EditText editText;
private ProgressDialog progressDialog;

private String URL_Image;
private MyImageDownload myImageDownload;
private Bitmap bitmap;

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

imageView=(ImageView)findViewById(R.id.imageView);
button=(Button)findViewById(R.id.button);
editText=(EditText)findViewById(R.id.editText);
}

@Override
protected void onResume() {
super.onResume();

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
DownloadImageNow();
}
});
}

private void DownloadImageNow() {
URL_Image=editText.getText().toString();

if (URL_Image!=null){
myImageDownload=new MyImageDownload();
myImageDownload.execute();
}else Toast.makeText(this,"url empty",Toast.LENGTH_SHORT).show();

}

private class MyImageDownload extends AsyncTask{

URL url;
InputStream inputStream;
HttpsURLConnection httpsURLConnection;

@Override
protected void onPreExecute() {
super.onPreExecute();

if (!checknetworkstatus()){
cancel(true);
}else {
progressDialog=new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Downloading...");
progressDialog.setCancelable(false);
progressDialog.setSecondaryProgress(ProgressDialog.STYLE_SPINNER);
progressDialog.setIndeterminate(true);
progressDialog.show();
}
}

@Override
protected Bitmap doInBackground(String... strings) {
try {
url=new URL(URL_Image);
httpsURLConnection=(HttpsURLConnection)url.openConnection();
httpsURLConnection.setConnectTimeout(3000);

httpsURLConnection.setDoInput(true);

httpsURLConnection.connect();

httpsURLConnection.setReadTimeout(3000);
int responsecode;

responsecode=httpsURLConnection.getResponseCode();

if (responsecode==HttpURLConnection.HTTP_OK){
inputStream=httpsURLConnection.getInputStream();
if (inputStream!=null){
bitmap= BitmapFactory.decodeStream(inputStream);
}
inputStream.close();
httpsURLConnection.disconnect();

return bitmap;
}else cancel(true);


} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
return bitmap;
}
}

@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);

progressDialog.cancel();
if (bitmap!=null){
imageView.setImageBitmap(bitmap);
}else {
Toast.makeText(MainActivity.this,"There was a problem",Toast.LENGTH_SHORT).show();
}
}

private NetworkInfo getActiveNetworkInfo() {
ConnectivityManager connectivityManager =
(ConnectivityManager) getSystemService(MainActivity.this.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return networkInfo;
}

private boolean checknetworkstatus() {

boolean ch1 = false;
NetworkInfo networkInfo = getActiveNetworkInfo();
if (networkInfo == null || !networkInfo.isConnected() ||
(networkInfo.getType() != ConnectivityManager.TYPE_WIFI
&& networkInfo.getType() != ConnectivityManager.TYPE_MOBILE)) {
// If no connectivity, cancel task and update Callback with null data.
ch1 = false;
} else ch1 = true;

return ch1;
}

@Override
protected void onCancelled() {
super.onCancelled();

progressDialog.cancel();
Toast.makeText(MainActivity.this,"cancelled",Toast.LENGTH_SHORT).show();
}
}
}



Download the code from GitHub



Related Tutorials