AndroidでURLからImageViewに画像を読み込む方法を徹底解説
この記事では、AndroidアプリにおいてURLを指定してImageViewに画像を読み込む方法を、実際のサンプルコードとともにステップごとにわかりやすく解説します。ネットワーク上の画像を非同期でダウンロードして表示する基本的な仕組みを学びましょう。
手順1:Android Studioで新規プロジェクトを作成する
まず、Android Studioを起動し、メニューから「File」→「New Project」を選択します。必要な項目をすべて入力して、新しいプロジェクトを作成してください。
手順2:res/layout/activity_main.xml にコードを追加する
次に、レイアウトファイル activity_main.xml を以下のように記述します。TextViewとImageViewを縦方向に配置したシンプルな構成です。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:app="https://schemas.android.com/apk/res-auto" xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="16dp" android:orientation="vertical" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Load Image From URL in Android ImageView" android:textSize="20sp" /> <ImageView android:id="@+id/image_view" android:layout_width="fill_parent" android:layout_height="300dp" android:layout_marginTop="16dp" /> <TextView android:layout_width="fill_parent" android:layout_height="match_parent" android:text="ViralAndroid.com" android:textSize="24sp" android:gravity="center|bottom" android:textStyle="bold" /> </LinearLayout>
手順3:src/MainActivity.java にコードを追加する
続いて、メインアクティビティに画像をダウンロードする処理を実装します。ここでは AsyncTask を使用して、UIスレッドをブロックすることなくバックグラウンドで画像を取得しています。
package com.example.sample;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// インターネット上の画像リンク
new DownloadImageFromInternet((ImageView) findViewById(R.id.image_view)).execute("https://pbs.twimg.com/profile_images/630285593268752384/iD1MkFQ0.png");
}
private class DownloadImageFromInternet extends AsyncTask<String, Void, Bitmap> {
ImageView imageView;
public DownloadImageFromInternet(ImageView imageView) {
this.imageView=imageView;
Toast.makeText(getApplicationContext(), "Please wait, it may take a few minute...",Toast.LENGTH_SHORT).show();
}
protected Bitmap doInBackground(String... urls) {
String imageURL=urls[0];
Bitmap bimage=null;
try {
InputStream in=new java.net.URL(imageURL).openStream();
bimage=BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error Message", e.getMessage());
e.printStackTrace();
}
return bimage;
}
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
}
}
ポイント: doInBackground() メソッド内でURLから入力ストリームを開き、BitmapFactory.decodeStream() でBitmapに変換しています。ダウンロード完了後は onPostExecute() が呼ばれ、取得したBitmapがImageViewにセットされます。
手順4:res/values/strings.xml にコードを追加する
文字列リソースファイル strings.xml は以下のように定義します。
<resources> <string name="app_name">Sample</string> <string name="hello_world">Hello world!</string> <string name="action_settings">Settings</string> </resources>
手順5:AndroidManifest.xml にインターネット権限を追加する
ネットワーク通信を行うため、AndroidManifest.xml に INTERNET パーミッションを必ず追加してください。これを忘れると画像のダウンロードに失敗します。
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.example.sample"> <uses-permission android:name="android.permission.INTERNET"></uses-permission> <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>
アプリを実行して動作を確認しよう
それでは、アプリケーションを実行してみましょう。ここでは、実機のAndroidスマートフォンがパソコンに接続されていることを前提としています。Android Studioからアプリを実行するには、プロジェクト内のアクティビティファイルのいずれかを開き、ツールバーにある「Run」アイコンをクリックしてください。実行デバイスとして自分のモバイル端末を選択すると、端末の画面に以下のように画像が表示されます。

補足: 本記事のコードは AsyncTask を使用した古典的な手法ですが、現在のAndroid開発では Glide や Picasso といった画像読み込みライブラリ、あるいは Kotlin Coroutines や WorkManager を活用するのが一般的です。実務ではキャッシュ管理やエラーハンドリングも考慮できるライブラリの利用をおすすめします。
-
【Android】URLをエンコードする方法をわかりやすく解説|URLEncoderの使い方
AndroidでURLをエンコードするには? 本記事では、AndroidアプリでURLを適切にエンコードする方法を、実際に動作するサンプルコードとともに解説します。 URLに検索キーワードなどのパラメータを含めたい場合、スペースや日本語などの特殊文字がそのまま含まれていると、正しくリクエストが送信できないことがあります。そんなときに役立つのが java.net.URLEncoder クラスです。このクラスを使えば、文字列をUTF-8などでエンコードし、URLとして安全な形式に変換できます。 手順1:新しいプロジェクトを作成する Android Studioを起動し、メニューから「File」→
-
AndroidでアニメーションGIF画像を表示する方法【Glideライブラリ活用ガイド】
Androidアプリでは、ImageViewにそのままGIFファイルを読み込んでもアニメーションは再生されません。GIFを動かして表示するには、画像読み込みライブラリ「Glide」を利用するのが最も簡単で定番の方法です。この記事では、Android Studioでプロジェクトを作成し、Glideを使ってアニメーションGIFを表示するまでの手順を、サンプルコード付きでわかりやすく解説します。Step 1:プロジェクトの作成とGlideの導入まず、Android Studioで新しいプロジェクトを作成します。メニューバーから「File → New Project」を選択し、必要な項目を入力してプロ