Download Code

Xamarin Fetch MYSQL Images Android

In Xamarin fetch mysql images android 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,xamarin fetch mysql,xamarin fetch mysql images,xamarin fetch mysql images android,fetch mysql images android,

Create new android application project.Go to Main.axml add two buttons and ImageView.

Main.axml

xamarin fetch mysql,xamarin fetch mysql images,xamarin fetch mysql images android,fetch mysql images android,

Next go to MainActivity.cs 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).

MainActivity.cs

namespace XamarinFetchImage
{
	[Activity(Label = "XamarinFetchImage", MainLauncher = true, Icon = "@mipmap/icon")]
	public class MainActivity : Activity, Android.Views.View.IOnClickListener
	{

		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

		protected override void OnCreate(Bundle savedInstanceState)
		{
			base.OnCreate(savedInstanceState);

			// Set our view from the "main" layout resource
			SetContentView(Resource.Layout.Main);
			initialize();
			// executing AsyncTask with server PHP file link
			FetchImageData FI = new FetchImageData(this);
			FI.Execute("http://192.168.1.100/serverImages/Images.php");
		}
		// method to refer id's and apply click event
		public void initialize()
		{
			displayImg = (ImageView)FindViewById(Resource.Id.img);
			prev = (Button)FindViewById(Resource.Id.prevBtn);
			next = (Button)FindViewById(Resource.Id.nextBtn);
			prev.SetOnClickListener(this);
			next.SetOnClickListener(this);
		}

		public void OnClick(View v)
		{
			switch (v.Id)
			{
				case Resource.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
							individualImage id = new individualImage(this);
							id.Execute(n);      // executing asyncTask to fetch an image
						}
						catch (JSONException e)
						{
							e.StackTrace.ToString();
						}
					}
					break;
				case Resource.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
							individualImage id = new individualImage(this);
							id.Execute(n);
						}
						catch (JSONException e)
						{
							e.StackTrace.ToString();
						}
					}
					break;
			}
		}

		// fetching complete data
		public class FetchImageData : AsyncTask<String, Java.Lang.Object, String>
		{
			ProgressDialog mDialog;
			MainActivity mainActivity;

			public FetchImageData(MainActivity mainActivity)
			{
				this.mainActivity = mainActivity;
			}

			protected override void OnPreExecute()
			{
				mDialog = new ProgressDialog(mainActivity);
				mDialog.SetMessage("Retrieving Data");
				mDialog.SetTitle("Please Wait....");
				mDialog.SetCancelable(true);
				mDialog.Show();
			}
			protected override string RunInBackground(params string[] @params)
			{
				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.InputStream));

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

					return sb.ToString().Trim();

				}
				catch (Exception e)
				{
					return null;
				}
			}
			protected override void OnPostExecute(string result)
			{
				mDialog.Dismiss();
				mainActivity.JSONString = result;
				try
				{
					JSONObject jsonObject = new JSONObject(mainActivity.JSONString);
					mainActivity.urlJSON = jsonObject.GetJSONArray("result");
				}
				catch (JSONException e)
				{
					e.StackTrace.ToString();
				}
				try
				{
					JSONObject jsonObject = mainActivity.urlJSON.GetJSONObject(index);
					String url = jsonObject.GetString("url");
					individualImage id = new individualImage(mainActivity);
					id.Execute(url);
				}
				catch (JSONException e)
				{
					e.StackTrace.ToString();
				}
			}
		}

		public class individualImage : AsyncTask<String, Java.Lang.Object, Bitmap>
		{
			ProgressDialog progress;
			MainActivity mainActivity;
			public individualImage(MainActivity mainActivity)
			{
				this.mainActivity = mainActivity;
			}
			protected override void OnPreExecute()
			{
				progress = new ProgressDialog(mainActivity);
				progress.SetMessage("Fetching Image Data");
				progress.SetTitle("Please Wait....");
				progress.SetCancelable(true);
				progress.Show();
			}
			protected override Bitmap RunInBackground(params string[] @params)
			{
				String uri = @params[0];
				Bitmap myBitmap = null;
				using (var webClient = new WebClient())
				{
					var bytes = webClient.DownloadData(uri);
					if (bytes != null && bytes.Length > 0)
					{
						myBitmap = BitmapFactory.DecodeByteArray(bytes, 0, bytes.Length);
					}
				}

				return myBitmap;
			}
			protected override void OnPostExecute(Bitmap result)
			{
				progress.Dismiss();
				mainActivity.displayImg.SetImageBitmap(result);
			}
		}

	}
}

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

Run your Xamarin fetch mysql images android application project.

xamarin fetch mysql,xamarin fetch mysql images,xamarin fetch mysql images android,fetch mysql images android,

That’s it for Xamarin fetch mysql images android tutorial.

For Java example visit Android Codec.

Thanks.