(Android)Menampilkan Gambar Dari Data Base

Kalau Menampilkan Gambar pada App Desktop sering kita temukan , tapi kali ini kita akan menampilkan gambar pada smartphone android dari data base mysql , sumber ini saya dapat dari blog nya mas http://gedelumbung.com/ , karena saya sangat membutuhkan ini untuk membuat app dengan menggunakan images , terima kasih sekali saya terhadap blog nya mas Gedelumbung yang telah memposting tema ini , tetapi saya izin posting dan sedit pengembangan dari saya

1. Create Project Android dengan nama Gambar_Data_Base

Siapkan Gambar yang ingin di tampilkan pada folder

Create File dan tuliskan scrip di bawah ini untuk membuat koneksi

&lt?php
$h = "localhost";
$u = "root";
$p = "";
$d = "db_android";
mysql_connect($h,$u,$p);
mysql_select_db($d);
?&gt

Create File dan tuliskan Scrip di bawah ini untuk memanggil data gambar – gambar yang kita masukkan

&lt?php
include("koneksi.php");
$q = mysql_query("SELECT * FROM tbl_artikel");
$v = '{"berita" : [';
while($r=mysql_fetch_array($q))
{
	if(strlen($v)&lt15)
	{
		$v .= '{"judul" : "'.strip_tags($r['judul']).'", "gambar" : "http://10.0.2.2/android/gb_berita/'.strip_tags($r['gambar']).'", "tanggal" : "'.$r['tanggal'].'", "waktu" : "'.$r['waktu'].'"}';
	}
	else
	{
		$v .= ',{"judul" : "'.strip_tags($r['judul']).'", "gambar" : "http://10.0.2.2/android/gb_berita/'.strip_tags($r['gambar']).'", "tanggal" : "'.$r['tanggal'].'", "waktu" : "'.$r['waktu'].'"}';
	}

}
$v .= ']}';
	echo $v;
?&gt

Buat Data Base seperti di bawah Ini

CREATE TABLE IF NOT EXISTS `tbl_artikel` (
  `id_artikel` int(5) NOT NULL AUTO_INCREMENT,
  `judul` varchar(200) NOT NULL,
  `gambar` varchar(100) NOT NULL,
  `tanggal` varchar(50) NOT NULL,
  `waktu` varchar(50) NOT NULL,
  PRIMARY KEY (`id_artikel`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=19 ;

--
-- Daten für Tabelle `tbl_artikel`
--

INSERT INTO `tbl_artikel` (`id_artikel`, `judul`, `gambar`, `tanggal`, `waktu`) VALUES
(1, 'Batik Andorid\n', 'baju.png', '2010-07-31', '01:37:28'),
(2, 'Batik Java', 'javadalam.png', '2010-07-31', '01:35:18'),
(3, 'Tutorial Android', 'kaset.png', '2010-10-09', '10:46:00'),
(6, 'Kaos Ubuntu', 'KasoUbuntu.png', '2012-10-1', '10:10:10'),
(4, 'Android Kaos', 'KasoAndroid.png', '2012-10-1', '11:11:00'),
(5, 'Kaos Ios', 'Kasoios.png', '2012-10-1', '10:10:10');

Kita kembali ke project android , Buka File main.xml untuk membuat tampilan

&lt?xml version="1.0" encoding="utf-8"?&gt
&ltLinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"&gt
	
    &ltListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:divider="#b5b5b5"
        android:dividerHeight="1dp" /&gt

&lt/LinearLayout&gt

Buat Class dengan nama FileCache.java

package dlmbg.pckg.tampil.gambar;

import java.io.File;
import android.content.Context;

public class FileCache {
    
    private File cacheDir;
    
    public FileCache(Context context){
        //Find the dir to save cached images
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
            cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"LazyList");
        else
            cacheDir=context.getCacheDir();
        if(!cacheDir.exists())
            cacheDir.mkdirs();
    }
    
    public File getFile(String url){
        //I identify images by hashcode. Not a perfect solution, good for the demo.
        String filename=String.valueOf(url.hashCode());
        //Another possible solution (thanks to grantland)
        //String filename = URLEncoder.encode(url);
        File f = new File(cacheDir, filename);
        return f;
        
    }
    
    public void clear(){
        File[] files=cacheDir.listFiles();
        if(files==null)
            return;
        for(File f:files)
            f.delete();
    }

}

Create Class dengan ImagesLoader.java

package dlmbg.pckg.tampil.gambar;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;

public class ImageLoader {
    
    MemoryCache memoryCache=new MemoryCache();
    FileCache fileCache;
    private Map imageViews=Collections.synchronizedMap(new WeakHashMap());
    ExecutorService executorService; 
    
    public ImageLoader(Context context){
        fileCache=new FileCache(context);
        executorService=Executors.newFixedThreadPool(5);
    }
    
    final int stub_id=R.drawable.no;
    public void DisplayImage(String url, ImageView imageView)
    {
        imageViews.put(imageView, url);
        Bitmap bitmap=memoryCache.get(url);
        if(bitmap!=null)
            imageView.setImageBitmap(bitmap);
        else
        {
            queuePhoto(url, imageView);
            imageView.setImageResource(stub_id);
        }
    }
        
    private void queuePhoto(String url, ImageView imageView)
    {
        PhotoToLoad p=new PhotoToLoad(url, imageView);
        executorService.submit(new PhotosLoader(p));
    }
    
    private Bitmap getBitmap(String url) 
    {
        File f=fileCache.getFile(url);
        
        //from SD cache
        Bitmap b = decodeFile(f);
        if(b!=null)
            return b;
        
        //from web
        try {
            Bitmap bitmap=null;
            URL imageUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(true);
            InputStream is=conn.getInputStream();
            OutputStream os = new FileOutputStream(f);
            Utils.CopyStream(is, os);
            os.close();
            bitmap = decodeFile(f);
            return bitmap;
        } catch (Exception ex){
           ex.printStackTrace();
           return null;
        }
    }

    //decodes image and scales it to reduce memory consumption
    private Bitmap decodeFile(File f){
        try {
            //decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f),null,o);
            
            //Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE=70;
            int width_tmp=o.outWidth, height_tmp=o.outHeight;
            int scale=1;
            while(true){
                if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                    break;
                width_tmp/=2;
                height_tmp/=2;
                scale*=2;
            }
            
            //decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=scale;
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        } catch (FileNotFoundException e) {}
        return null;
    }
    
    //Task for the queue
    private class PhotoToLoad
    {
        public String url;
        public ImageView imageView;
        public PhotoToLoad(String u, ImageView i){
            url=u; 
            imageView=i;
        }
    }
    
    class PhotosLoader implements Runnable {
        PhotoToLoad photoToLoad;
        PhotosLoader(PhotoToLoad photoToLoad){
            this.photoToLoad=photoToLoad;
        }
        
        @Override
        public void run() {
            if(imageViewReused(photoToLoad))
                return;
            Bitmap bmp=getBitmap(photoToLoad.url);
            memoryCache.put(photoToLoad.url, bmp);
            if(imageViewReused(photoToLoad))
                return;
            BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
            Activity a=(Activity)photoToLoad.imageView.getContext();
            a.runOnUiThread(bd);
        }
    }
    
    boolean imageViewReused(PhotoToLoad photoToLoad){
        String tag=imageViews.get(photoToLoad.imageView);
        if(tag==null || !tag.equals(photoToLoad.url))
            return true;
        return false;
    }
    
    //Used to display bitmap in the UI thread
    class BitmapDisplayer implements Runnable
    {
        Bitmap bitmap;
        PhotoToLoad photoToLoad;
        public BitmapDisplayer(Bitmap b, PhotoToLoad p){bitmap=b;photoToLoad=p;}
        public void run()
        {
            if(imageViewReused(photoToLoad))
                return;
            if(bitmap!=null)
                photoToLoad.imageView.setImageBitmap(bitmap);
            else
                photoToLoad.imageView.setImageResource(stub_id);
        }
    }

    public void clearCache() {
        memoryCache.clear();
        fileCache.clear();
    }

}

Create Class dengan nama JSONPaser.java

package dlmbg.pckg.tampil.gambar;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

	static InputStream is = null;
	static JSONObject jObj = null;
	static String json = "";

	// constructor
	public JSONParser() {

	}

	public JSONObject AmbilJson(String url) {

		// Making HTTP request
		try {
			// defaultHttpClient
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(url);

			HttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			is = httpEntity.getContent();			

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			json = sb.toString();
		} catch (Exception e) {
			Log.e("Buffer Error", "Error converting result " + e.toString());
		}

		// try parse the string to a JSON object
		try {
			jObj = new JSONObject(json);
		} catch (JSONException e) {
			Log.e("JSON Parser", "Error parsing data " + e.toString());
		}

		// return JSON String
		return jObj;

	}
}

Create Class dengan nama Koneksi.java

package dlmbg.pckg.tampil.gambar;

public class Koneksi {
	
	public String isi_koneksi()
	{
		String isi = "http://10.0.2.2/android/";
		return isi;
	}

}

Create CLass dengan nama LazyAdapter.java

package dlmbg.pckg.tampil.gambar;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class LazyAdapter extends BaseAdapter {
    
    private Activity activity;
    private ArrayList<HashMap> data;
    private static LayoutInflater inflater=null;
    public ImageLoader imageLoader; 
    
    public LazyAdapter(Activity a, ArrayList<HashMap> d) {
        activity = a;
        data=d;
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        imageLoader=new ImageLoader(activity.getApplicationContext());
    }

    public int getCount() {
        return data.size();
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }
    
    public View getView(int position, View convertView, ViewGroup parent) {
        View vi=convertView;
        if(convertView==null)
        	
            vi = inflater.inflate(R.layout.list_row, null);

	        TextView judul = (TextView)vi.findViewById(R.id.judul); 
	        TextView tanggal = (TextView)vi.findViewById(R.id.tanggal); 
	        ImageView gambar=(ImageView)vi.findViewById(R.id.gambar);
	        
	        HashMap berita = new HashMap();
	        berita = data.get(position);
	        
	        judul.setText(berita.get(TampilkanGambarActivity.in_judul));
	        tanggal.setText(berita.get(TampilkanGambarActivity.in_waktu));
	        imageLoader.DisplayImage(berita.get(TampilkanGambarActivity.in_gambar), gambar);
	        return vi;
    }
}

Create Class dengan nama MemoryCache.java

package dlmbg.pckg.tampil.gambar;

import java.lang.ref.SoftReference;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import android.graphics.Bitmap;

public class MemoryCache {
    private Map<String, SoftReference> cache=Collections.synchronizedMap(new HashMap<String, SoftReference>());
    
    public Bitmap get(String id){
        if(!cache.containsKey(id))
            return null;
        SoftReference ref=cache.get(id);
        return ref.get();
    }
    
    public void put(String id, Bitmap bitmap){
        cache.put(id, new SoftReference(bitmap));
    }

    public void clear() {
        cache.clear();
    }
}

Create Class dengan nama Utils.java

package dlmbg.pckg.tampil.gambar;

import java.io.InputStream;
import java.io.OutputStream;

public class Utils {
    public static void CopyStream(InputStream is, OutputStream os)
    {
        final int buffer_size=1024;
        try
        {
            byte[] bytes=new byte[buffer_size];
            for(;;)
            {
              int count=is.read(bytes, 0, buffer_size);
              if(count==-1)
                  break;
              os.write(bytes, 0, count);
            }
        }
        catch(Exception ex){}
    }
}

Buka Class ViewActivity.java

package dlmbg.pckg.tampil.gambar;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;

public class TampilkanGambarActivity extends Activity {
	
	static String in_judul = "judul";
	static String in_waktu = "tanggal";
	static String in_gambar = "gambar";
	JSONArray str_json = null;
	public String lo_Koneksi,isi ;
	
	ListView list;
    LazyAdapter adapter;
	ArrayList<HashMap> data_map = new ArrayList<HashMap>();
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Koneksi lo_Koneksi = new Koneksi();
        isi = lo_Koneksi.isi_koneksi();
        
        String link_url = isi+"data.php";
		JSONParser jParser = new JSONParser();
		JSONObject json = jParser.AmbilJson(link_url);
		
		try {
			str_json = json.getJSONArray("berita");
			
			for(int i = 0; i < str_json.length(); i++){
				JSONObject ar = str_json.getJSONObject(i);

				String judul = ar.getString("judul");
				String gambar = ar.getString("gambar");
				String waktu = ar.getString("tanggal")+" | "+ar.getString("waktu");
				
				HashMap map = new HashMap();

				map.put(in_judul, judul);
				map.put(in_gambar, gambar);
				map.put(in_waktu, waktu);

				data_map.add(map);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		list=(ListView)findViewById(R.id.list);
        adapter=new LazyAdapter(this, data_map);        
        list.setAdapter(adapter);
    }
}

Run dan hasilnya seperti di bawah ini

Download Projcet.zip

Advertisements

Published by

jarcode

hello I am jarcode

27 thoughts on “(Android)Menampilkan Gambar Dari Data Base”

  1. minta project androidnya bos. yang di zip cuma php ma database. projectnya zonk… kalo bolehminta, kirim ke email saya bos.. thanks

      1. force close bang pas di coba
        bukanya harus pake AsyncTask bang??
        itu harus gk si??
        soal.a d.coba force close juga
        mohon solusinya bang

      1. public class BookmarkAsyntaskJson extends AsyncTask {
        super.onPreExecute();

        sebelum process background… atau bisa dibilang awal process pada asyntask
        }

        @Override
        protected Boolean doInBackground(Void… params) {
        process yang jalan pada background

        return null;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
        super.onPostExecute(aBoolean);

        setelah semua process selesai
        }

        }

      1. sudah gan. maksud ane launche itu di emulator PC tampil sempurna. pas ane install di HP kagak mau muncul gambar yg sebenarnya. cmn diambil defaultnya aja.

      2. itu ada di koneksi PHP dan ip di class Koneksi.java..

        File koneksi PHP menujukkan ke arah DB nya… terus Class Koneksi menunjukkan kearah PHPnya,,, ip 10.0.2.2. itu ip local,, bisa juga di ganti dengan 127.0.0.1

      3. kondisi terakhir. mash blum bisa muncul gambar. saya sdh cek koneksi, path gambar, dan db nya gak ada error. ini Saya langsung online ke web dbnya, tidak melalui localhost. Apa ada syarat ukuran dan format gambar dan lain-lain mungkin ???

  2. kang misalkan kita klik salah satu item di list view trus muncul detailnya sama gambarnya bisa gak kang ??
    bleh minta tutornya atau contoh aplikasinya ?

    1. bisa… tinggal kamu tambah di class lazy adapter dan masukkan di method getview …

      public View getView(int position, View convertView, ViewGroup parent) {
      View vi=convertView;
      if(convertView==null)

      vi = inflater.inflate(R.layout.list_row, null);

      TextView judul = (TextView)vi.findViewById(R.id.judul);
      TextView tanggal = (TextView)vi.findViewById(R.id.tanggal);
      ImageView gambar=(ImageView)vi.findViewById(R.id.gambar);

      HashMap berita = new HashMap();
      berita = data.get(position);

      judul.setText(berita.get(TampilkanGambarActivity.in_judul));
      tanggal.setText(berita.get(TampilkanGambarActivity.in_waktu));
      imageLoader.DisplayImage(berita.get(TampilkanGambarActivity.in_gambar), gambar);
      return vi;
      }

      itu sudah saya cache untuk gambarnya,,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s