Download Code

Android Load Image Database JSON

In android load image database json tutorial you will learn how to load image from mysql database using JSON in android application.

Before starting this tutorial you should go through HTTP Components,Parsing data using JSON,Load data from mysql database.

Localhost/Server End do the following steps.

  • Create new database(codeclogin) and table(images).
  • Insert images data in database.
  • Create new PHP file and put code in that file.

Images.php

load image,json,retrieve images,json parser,jsonarray,jsonobject,getjsonstring, http,httpget,httppost,httpclient library,database, how to fetch images from mysql database in android source code, how to retrieve images from mysql database in android tutorial, url,httpurlconnection,bufferedReader,inputstreamreader,url open connection, stringbuilder,bitmapfactory,bitmap,how to execute asynctask in android, load images from database android,android load image database json,

Create new android application project.Go to activity_main.xml add two buttons and ImageView.

activity_main.xml

load image,json,retrieve images,json parser,jsonarray,jsonobject,getjsonstring, http,httpget,httppost,httpclient library,database, how to fetch images from mysql database in android source code, how to retrieve images from mysql database in android tutorial, url,httpurlconnection,bufferedReader,inputstreamreader,url open connection, stringbuilder,bitmapfactory,bitmap,how to execute asynctask in android, load images from database android,android load image database json,

Next go to MainActivity.java and do the following steps.

  • Create UI Component variables and refer their id’s.
  • Apply click event on buttons.
  • Create two AsyncTask(one for retrieve all images and second is for load image).
package developer.fetchimagedatabase;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

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

import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;


public class MainActivity extends Activity implements OnClickListener {

	ImageView displayImg;  // imageview variable/instance
	Button prev,next;      // button previous and next
	String JSONString;     // stored JSON String
	JSONArray urlJSON=null;    // keep JSON array 
	static int index = 0;       // index of individual image
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		// calling method to refer id's and apply click event
		initialize();
		// executing AsyncTask with server PHP file link
		new fetchImagesData().execute("http://192.168.1.100/serverImages/Images.php");
	}
	
	// method to refer id's and apply click event
	public void initialize(){
		displayImg = (ImageView) findViewById(R.id.img);
		prev = (Button) findViewById(R.id.prevBtn);
		next = (Button) findViewById(R.id.nextBtn);
		prev.setOnClickListener(this);
		next.setOnClickListener(this);
	}
	// onclick method for each button
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		// previous button case 
		case R.id.prevBtn:
			if(index > 0){
				index--;
				try {
					// getting previous link of an image using JSONObject
		            JSONObject jsonObject = urlJSON.getJSONObject(index);
		            String n = jsonObject.getString("url");  // getting data/valuepair
		            new individualImage().execute(n);      // executing asyncTask to fetch an image
		        } catch (JSONException e) {
		            e.printStackTrace();
		        }
			}
			break;
		case R.id.nextBtn:
			if(index < urlJSON.length()){
				index++;
				try {
					// getting next link of an image using JSONObject
		            JSONObject jsonObject = urlJSON.getJSONObject(index);
		            String n = jsonObject.getString("url");  // getting data/valuepair
		            new individualImage().execute(n);    // executing asyncTask to load image
		        } catch (JSONException e) {
		            e.printStackTrace();
		        }
			}
			break;
		}
	}
	// AsyncTask which will execute when application starts to fetch all images
	class fetchImagesData extends AsyncTask<String, Void, String>{
		ProgressDialog mDialog;
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			mDialog = new ProgressDialog(MainActivity.this);
			mDialog.setMessage("Retrieving Data");
			mDialog.setTitle("Please Wait....");
			mDialog.setIndeterminate(false);
			mDialog.setCancelable(true);
			mDialog.show();
			
		}

		

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			String uri = params[0];
            BufferedReader bufferedReader = null;
            try {
                URL url = new URL(uri);
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                StringBuilder sb = new StringBuilder();

                bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));

                String json;
                while((json = bufferedReader.readLine())!= null){
                    sb.append(json+"\n");
                }

                return sb.toString().trim();

            }catch(Exception e){
                return null;
            }
		}
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			mDialog.dismiss();
			JSONString = result;
			try {
	            JSONObject jsonObject = new JSONObject(JSONString);
	            urlJSON = jsonObject.getJSONArray("result");
	        } catch (JSONException e) {
	            e.printStackTrace();
	        }
			try {
	            JSONObject jsonObject = urlJSON.getJSONObject(index);
	            String url = jsonObject.getString("url");
	            new individualImage().execute(url);
	        } catch (JSONException e) {
	            e.printStackTrace();
	        }
		}
	}

	// AsyncTask to load image
	class individualImage extends AsyncTask<String, Void, Bitmap>{
		ProgressDialog progress;
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			progress = new ProgressDialog(MainActivity.this);
			progress.setMessage("Fetching Image Data");
			progress.setTitle("Please Wait....");
			progress.setIndeterminate(false);
			progress.setCancelable(true);
			progress.show();
		}
		
		
		@Override
		protected Bitmap doInBackground(String... params) {
			// TODO Auto-generated method stub
			URL url = null;
            Bitmap image = null;

            String urlToImage = params[0];
            try {
                url = new URL(urlToImage);
                image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return image;
		}
		@Override
		protected void onPostExecute(Bitmap result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			progress.dismiss();
			displayImg.setImageBitmap(result);
		}
	}	
}

Go to Android Manifest.xml file and add INTERNET permission.

load image,json,retrieve images,json parser,jsonarray,jsonobject,getjsonstring, http,httpget,httppost,httpclient library,database, how to fetch images from mysql database in android source code, how to retrieve images from mysql database in android tutorial, url,httpurlconnection,bufferedReader,inputstreamreader,url open connection, stringbuilder,bitmapfactory,bitmap,how to execute asynctask in android, load images from database android,android load image database json,

Run your android load image database json application project.

load image,json,retrieve images,json parser,jsonarray,jsonobject,getjsonstring, http,httpget,httppost,httpclient library,database, how to fetch images from mysql database in android source code, how to retrieve images from mysql database in android tutorial, url,httpurlconnection,bufferedReader,inputstreamreader,url open connection, stringbuilder,bitmapfactory,bitmap,how to execute asynctask in android, load images from database android,android load image database json,

That’s it for android load image database json tutorial.

Thanks.