Register Register Member Login Member Login Member Login Forgot Password ??
PHP , ASP , ASP.NET, VB.NET, C#, Java , jQuery , Android , iOS , Windows Phone
 

Registered : 109,027

HOME > Mobile > Android Tutorials - สอนเขียน Android App ฟรี เขียนโปรแกรมแอนดรอยด์บน SmartPhone / Tablets > Android แสดงรูปภาพ ImageView จาก Web URL ของเว็บไซต์ บน ListView



Clound SSD Virtual Server

Android แสดงรูปภาพ ImageView จาก Web URL ของเว็บไซต์ บน ListView

Android แสดงรูปภาพ ImageView จาก Web URL ของเว็บไซต์ บน ListView บทความ Advanced การใช้ ListView แสดงรูปภาพ ImageView โดยอ่านไฟล์รูปภาพที่อยู่บน URL จากเว็บไซต์ต่าง ๆ แสดงแบ่งรายการข้อมูลเป็น Column และมี Column ที่ดึงรูปภาพที่ถุกแปลงให้อยู่ในรูปแบบของ Bitmap ก่อนที่จะแสดงผลบน Custom Layout

Android ListView Custom Image Resource from URL


รูปอธิบายขั้นตอนการทำงาน และการเรียกรูปภาพที่อยู่บน Web Server โดยจะเรียกผ่าน URL ที่มีอยู่จริงในระบบ Internet

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

ในการเขียน Android เพื่อติดต่อกับ Internet จะต้องกำหนด Permission ในส่วนนี้ด้วยทุกครั้ง

    	final ArrayList<HashMap<String, String>> MyArrList = new ArrayList<HashMap<String, String>>();
		HashMap<String, String> map;
		
		/*** Rows 1 ***/
		map = new HashMap<String, String>();
		map.put("ImageID", "1");
		map.put("ImageDesc", "Sea View1");
		map.put("ImagePath", "https://www.thaicreate.com/android/pic_a.png");
		MyArrList.add(map);
		
		/*** Rows 2 ***/
		map = new HashMap<String, String>();
		map.put("ImageID", "2");
		map.put("ImageDesc", "Sea View2");
		map.put("ImagePath", "https://www.thaicreate.com/android/pic_b.png");
		MyArrList.add(map);	
		
		/*** Rows 3 ***/
		map = new HashMap<String, String>();
		map.put("ImageID", "3");
		map.put("ImageDesc", "Sea View 3");
		map.put("ImagePath", "https://www.thaicreate.com/android/pic_c.png");
		MyArrList.add(map);
		
		/*** Rows 4 ***/
		map = new HashMap<String, String>();
		map.put("ImageID", "4");
		map.put("ImageDesc", "Sea View 4");
		map.put("ImagePath", "https://www.thaicreate.com/android/pic_d.png");
		MyArrList.add(map);

สร้างชุดข้อมูลของ ArrayList ที่มี ImagePath อยู่ในระบบ Internet หลักการก็คือ จะทำ ArrayList ทำการ setAdapter ให้กับ ListView ผ่าน Custom Adapter ของ BaseAdapter จากนั้นใน Method ว่า getView() จะมีการอ้างถึงรูปภาพจาก URL
imageView.setImageBitmap(loadBitmap(MyArr.get(position).get("ImagePath")));

ซึ่งจะมี Method ว่า loadBitmap() ในการแปลง URL ของรุปภาพให้เป็น Bitmap ก่อนที่จะแสดงผลบน ImageView ของแต่ล่ Items

Example

โครงสร้างของไฟล์ประกอบด้วย 3 ไฟล์คือ MainActivity.java, activity_main.xml และ custom_fullimage_dialog.xml

Android ListView Custom Image Resource from URL

activity_main.xml
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tableLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
 
   	<TableRow
      android:id="@+id/tableRow1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" >
     
     <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="ListView Example : "
        android:layout_span="1"
        android:textAppearance="?android:attr/textAppearanceLarge" />
  	        
 	</TableRow>

	<View
		android:layout_height="1dip"
		android:background="#CCCCCC" />
 
  <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.1">   
     
     <ListView
         android:id="@+id/listView1"
         android:layout_width="match_parent"
         android:layout_height="wrap_content">
     </ListView>
  	        
 	</LinearLayout>

	<View
		android:layout_height="1dip"
		android:background="#CCCCCC" />
   		  
   	<LinearLayout
      android:id="@+id/LinearLayout1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:padding="5dip" >

   		<TextView
   		    android:id="@+id/textView2"
   		    android:layout_width="wrap_content"
   		    android:layout_height="wrap_content"
   		    android:text="By.. ThaiCreate.Com" />

	</LinearLayout>
	
</TableLayout>









Android ListView Custom Image Resource from URL

activity_column.xml
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tableLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
 
    <TableRow
        android:id="@+id/tableRow3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <ImageView
            android:id="@+id/ColImgPath"
	        android:layout_width="wrap_content"
	        android:layout_height="wrap_content"
            />
        
        <TextView
            android:id="@+id/ColImgID"
            android:text="Column 1" />

        <TextView
            android:id="@+id/ColImgDesc"
            android:text="Column 2" />
        
    </TableRow>

 
</TableLayout>


custom_fullimage_dialog.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout_root"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    android:padding="10dp" >

    <ImageView
        android:id="@+id/fullimage"
        android:layout_width="250dp"
        android:layout_height="200dp" />

    <TextView android:id="@+id/custom_fullimage_placename"
        android:layout_width="wrap_content" android:layout_height="fill_parent"
        android:textColor="#FFF">
    </TextView>
</LinearLayout>


MainActivity.java
package com.myapp;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class MainActivity extends Activity {

    @SuppressLint("NewApi")
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // Permission StrictMode
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        
        
    	final ArrayList<HashMap<String, String>> MyArrList = new ArrayList<HashMap<String, String>>();
		HashMap<String, String> map;
		
		/*** Rows 1 ***/
		map = new HashMap<String, String>();
		map.put("ImageID", "1");
		map.put("ImageDesc", "Sea View1");
		map.put("ImagePath", "https://www.thaicreate.com/android/pic_a.png");
		MyArrList.add(map);
		
		/*** Rows 2 ***/
		map = new HashMap<String, String>();
		map.put("ImageID", "2");
		map.put("ImageDesc", "Sea View2");
		map.put("ImagePath", "https://www.thaicreate.com/android/pic_b.png");
		MyArrList.add(map);	
		
		/*** Rows 3 ***/
		map = new HashMap<String, String>();
		map.put("ImageID", "3");
		map.put("ImageDesc", "Sea View 3");
		map.put("ImagePath", "https://www.thaicreate.com/android/pic_c.png");
		MyArrList.add(map);
		
		/*** Rows 4 ***/
		map = new HashMap<String, String>();
		map.put("ImageID", "4");
		map.put("ImageDesc", "Sea View 4");
		map.put("ImagePath", "https://www.thaicreate.com/android/pic_d.png");
		MyArrList.add(map);			
		
        // listView1
        final ListView lstView1 = (ListView)findViewById(R.id.listView1); 
        	
        lstView1.setAdapter(new ImageAdapter(this,MyArrList));
        
        // OnClick
        
        final AlertDialog.Builder imageDialog = new AlertDialog.Builder(this);
        final LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
        
        lstView1.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v,
				int position, long id) {
				
                View layout = inflater.inflate(R.layout.custom_fullimage_dialog,
                        (ViewGroup) findViewById(R.id.layout_root));
                ImageView image = (ImageView) layout.findViewById(R.id.fullimage);
                image.setPadding(5, 5, 5, 5);
                
	           	 try
	           	 {
	           		image.setImageBitmap(loadBitmap(MyArrList.get(position).get("ImagePath")));
	           	 } catch (Exception e) {
	           		 // When Error
	           		image.setImageResource(android.R.drawable.ic_menu_report_image);
	           	 }
				
                imageDialog.setIcon(android.R.drawable.btn_star_big_on);	
        		imageDialog.setTitle("View : " + MyArrList.get(position).get("ImageDesc"));
                imageDialog.setView(layout);
                imageDialog.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener(){

                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }

                });


                imageDialog.create();
                imageDialog.show(); 
		    	
			}
		});
      
    }
             
    
    public class ImageAdapter extends BaseAdapter 
    {
        private Context context;
        private ArrayList<HashMap<String, String>> MyArr = new ArrayList<HashMap<String, String>>();

        public ImageAdapter(Context c, ArrayList<HashMap<String, String>> list) 
        {
        	// TODO Auto-generated method stub
            context = c;
            MyArr = list;
        }
 
        public int getCount() {
        	// TODO Auto-generated method stub
            return MyArr.size();
        }
 
        public Object getItem(int position) {
        	// TODO Auto-generated method stub
            return position;
        }
 
        public long getItemId(int position) {
        	// TODO Auto-generated method stub
            return position;
        }
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			
			LayoutInflater inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		 		 
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.activity_column, null); 
			}
		 
					// ColImage
				ImageView imageView = (ImageView) convertView.findViewById(R.id.ColImgPath);
				imageView.getLayoutParams().height = 100;
				imageView.getLayoutParams().width = 100;
				imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            	 try
            	 {
            		 imageView.setImageBitmap(loadBitmap(MyArr.get(position).get("ImagePath")));
            	 } catch (Exception e) {
            		 // When Error
            		 imageView.setImageResource(android.R.drawable.ic_menu_report_image);
            	 }
					
				// ColPosition
				TextView txtPosition = (TextView) convertView.findViewById(R.id.ColImgID);
				txtPosition.setPadding(10, 0, 0, 0);
				txtPosition.setText("ID : " + MyArr.get(position).get("ImageID"));
				
				// ColPicname
				TextView txtPicName = (TextView) convertView.findViewById(R.id.ColImgDesc);
				txtPicName.setPadding(50, 0, 0, 0);
				txtPicName.setText("Desc : " + MyArr.get(position).get("ImageDesc"));

				
	 
			return convertView;
				
		}

    } 
    
    
    /***** Get Image Resource from URL (Start) *****/
	private static final String TAG = "ERROR";
	private static final int IO_BUFFER_SIZE = 4 * 1024;
	public static Bitmap loadBitmap(String url) {
	    Bitmap bitmap = null;
	    InputStream in = null;
	    BufferedOutputStream out = null;

	    try {
	        in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);

	        final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
	        out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
	        copy(in, out);
	        out.flush();

	        final byte[] data = dataStream.toByteArray();
	        BitmapFactory.Options options = new BitmapFactory.Options();
	        //options.inSampleSize = 1;

	        bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
	    } catch (IOException e) {
	        Log.e(TAG, "Could not load Bitmap from: " + url);
	    } finally {
	        closeStream(in);
	        closeStream(out);
	    }

	    return bitmap;
	}

	 private static void closeStream(Closeable stream) {
	        if (stream != null) {
	            try {
	                stream.close();
	            } catch (IOException e) {
	                android.util.Log.e(TAG, "Could not close stream", e);
	            }
	        }
	    }
	 
	 private static void copy(InputStream in, OutputStream out) throws IOException {
        byte[] b = new byte[IO_BUFFER_SIZE];
        int read;
        while ((read = in.read(b)) != -1) {
            out.write(b, 0, read);
        }
    }
	 /***** Get Image Resource from URL (End) *****/
    
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}









Screenshot

Android ListView Custom Image Resource from URL

แสดงรุปภาพจาก URL ของเว็บไซต์

Android ListView Custom Image Resource from URL

เมื่อคลิกแต่ล่ะ Item ของ ListView จะแสดง Full Image

ทั้งนี้สามารถออกแบบภาพเป็นแบบ Thumbnail กับ Full images เพื่อลดการโหลดของข้อมูล

   
Share


ช่วยกันสนับสนุนรักษาเว็บไซต์ความรู้แห่งนี้ไว้ด้วยการสนับสนุน Source Code 2.0 ของทีมงานไทยครีเอท


ลองใช้ค้นหาข้อมูล


   


Bookmark.   
       
  By : ThaiCreate.Com Team (บทความเป็นลิขสิทธิ์ของเว็บไทยครีเอทห้ามนำเผยแพร่ ณ เว็บไซต์อื่น ๆ)
  Score Rating :  
  Create/Update Date : 2012-08-11 09:18:44 / 2017-03-26 21:34:09
  Download : No files
 Sponsored Links / Related

 
Android ListView แบบ Custom Layout แสดงข้อมูล ListView หลายคอลัมบ์ Multiple Column
Rating :

 
Android ListView and ImageView Image / Text in ListView Custom Layout Column
Rating :

 
Android ListView Padding and Pagination
Rating :

 
Android กับ ListView แสดงข้อมูลจาก Database ของ SQLite
Rating :

 
Android ListView and Checkbox
Rating :

 
Android ListView and Buttons inside Create Custom Command in ListView
Rating :

 
Android Populate ListView ImageView get Image Resource from SD Card
Rating :

 
Android EditText or Textbox in ListView
Rating :

 
Android Gesture on ListView Detecting Sliding Items (Flip and Swipe)
Rating :

 
Android and Web Server ของ PHP กับ MySQL แสดงบน ListView ในรูปแบบของ JSON
Rating :

 
Android JSON Retrieving Data from URL Web Server (PHP MySQL and JSON)
Rating :

 
Android ProgressDialog When Click Item in ListView for Download file from Server
Rating :

 
Android Multiple Upload Send file to Server and Show Items ProgressBar in ListView
Rating :

 
Android Multiple Download file in ListView and Show Progress unit percentage
Rating :

 
Android AsyncTask update ListView notifyDataSetChanged when Items Load finish
Rating :

 
Android (ListView/GridView) get Result from Web Server and Paging Pagination
Rating :

 
Android Performance of Listview
Rating :


ThaiCreate.Com Forum


Comunity Forum Free Web Script
Jobs Freelance Free Uploads
Free Web Hosting Free Tools

สอน PHP ผ่าน Youtube ฟรี
สอน Android การเขียนโปรแกรม Android
สอน Windows Phone การเขียนโปรแกรม Windows Phone 7 และ 8
สอน iOS การเขียนโปรแกรม iPhone, iPad
สอน Java การเขียนโปรแกรม ภาษา Java
สอน Java GUI การเขียนโปรแกรม ภาษา Java GUI
สอน JSP การเขียนโปรแกรม ภาษา Java
สอน jQuery การเขียนโปรแกรม ภาษา jQuery
สอน .Net การเขียนโปรแกรม ภาษา .Net
Free Tutorial
สอน Google Maps Api
สอน Windows Service
สอน Entity Framework
สอน Android
สอน Java เขียน Java
Java GUI Swing
สอน JSP (Web App)
iOS (iPhone,iPad)
Windows Phone
Windows Azure
Windows Store
Laravel Framework
Yii PHP Framework
สอน jQuery
สอน jQuery กับ Ajax
สอน PHP OOP (Vdo)
Ajax Tutorials
SQL Tutorials
สอน SQL (Part 2)
JavaScript Tutorial
Javascript Tips
VBScript Tutorial
VBScript Validation
Microsoft Access
MySQL Tutorials
-- Stored Procedure
MariaDB Database
SQL Server Tutorial
SQL Server 2005
SQL Server 2008
SQL Server 2012
-- Stored Procedure
Oracle Database
-- Stored Procedure
SVN (Subversion)
แนวทางการทำ SEO
ปรับแต่งเว็บให้โหลดเร็ว


Hit Link
   







Load balance : Server 02
ThaiCreate.Com Logo
© www.ThaiCreate.Com. 2003-2024 All Rights Reserved.
ไทยครีเอทบริการ จัดทำดูแลแก้ไข Web Application ทุกรูปแบบ (PHP, .Net Application, VB.Net, C#)
[Conditions Privacy Statement] ติดต่อโฆษณา 081-987-6107 อัตราราคา คลิกที่นี่