Hello friends welcome to one more Android Programming Tutorial. In the last couple of Android Development Tutorial posts we have seen uploading image from android gallery to MySQL database. And fetching images from MySQL database to android. In this android app tutorial we will fetch all the images stored in our MySQL database at once.
Before going further in this tutorial you should check the last android programming tutorials.
If you have already read the last android programming tutorial then lets move ahead.
Lets Start our Android Programming Tutorial
- We will be using the same database, where we have already uploaded some images. My database is as follows.
- As you can see our database has images.
- Now we will create a simple php script to get the live URL of all the images in our database.
- for getting the URL we will use our getImage.php script which we have created in last tutorial.
- We can get a particular image using our getImage.php, with a simple get request. For example if we want to get image of id 31 we will execute our getImage.php like -> getImage.php?id=31.
- But in this tutorial we will have to get all the images at once. So we will create a new script to get all the images.
- Create a php file and copy the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?php require_once('dbConnect.php'); $sql = "select id from images"; $res = mysqli_query($con,$sql); $result = array(); $url = "http://simplifiedcoding.16mb.com/ImageUpload/getImage.php?id="; while($row = mysqli_fetch_array($res)){ array_push($result,array('url'=>$url.$row['id'])); } echo json_encode(array("result"=>$result)); mysqli_close($con); |
- As you can see in the above code we have the url of our getImage.php. And inside the loop we are concatenating ids of the image at the end and storing it to an array.
- The loop will store url of all the images inside our array.
- And finally we are encoding the array in json format.
- We will read the json from Android.
- Save the above file and upload it to your hosting account. In my case I have uploaded it to http://simplifiedcoding.16mb.com/ImageUpload/getAllImages.php
- If we go to the above given URL we will see the JSON as follows
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
{ Â Â Â "result": [ Â Â Â Â Â Â { Â Â Â Â Â Â Â Â Â "url": "http://simplifiedcoding.16mb.com/ImageUpload/getImage.php?id=6" Â Â Â Â Â Â }, Â Â Â Â Â Â { Â Â Â Â Â Â Â Â Â "url": "http://simplifiedcoding.16mb.com/ImageUpload/getImage.php?id=7" Â Â Â Â Â Â }, Â Â Â Â Â Â { Â Â Â Â Â Â Â Â Â "url": "http://simplifiedcoding.16mb.com/ImageUpload/getImage.php?id=8" Â Â Â Â Â Â }, Â Â Â Â Â Â { Â Â Â Â Â Â Â Â Â "url": "http://simplifiedcoding.16mb.com/ImageUpload/getImage.php?id=29" Â Â Â Â Â Â }, Â Â Â Â Â Â { Â Â Â Â Â Â Â Â Â "url": "http://simplifiedcoding.16mb.com/ImageUpload/getImage.php?id=31" Â Â Â Â Â Â }, Â Â Â Â Â Â { Â Â Â Â Â Â Â Â Â "url": "http://simplifiedcoding.16mb.com/ImageUpload/getImage.php?id=32" Â Â Â Â Â Â }, Â Â Â Â Â Â { Â Â Â Â Â Â Â Â Â "url": "http://simplifiedcoding.16mb.com/ImageUpload/getImage.php?id=33" Â Â Â Â Â Â }, Â Â Â Â Â Â { Â Â Â Â Â Â Â Â Â "url": "http://simplifiedcoding.16mb.com/ImageUpload/getImage.php?id=34" Â Â Â Â Â Â } Â Â Â ] } |
Creating a new Android Project
- Create a new Android Project.
- In activity_main.xml we have to create the following layout.
- The above layout has three buttons and one image view. You can use the following xml code to create the above layout.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:orientation="vertical" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Fetch Images" android:id="@+id/buttonFetchImages" /> <ImageView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:id="@+id/imageView" /> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Previous" android:layout_weight="1" android:id="@+id/buttonPrev" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Next" android:layout_weight="1" android:id="@+id/buttonNext" /> </LinearLayout> </LinearLayout> |
- Now lets move to your MainActivity.java file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
public class MainActivity extends AppCompatActivity implements View.OnClickListener { private static final String IMAGES_URL = "http://www.simplifiedcoding.16mb.com/ImageUpload/getAllImages.php"; private Button buttonFetchImages; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); buttonFetchImages = (Button) findViewById(R.id.buttonFetchImages); buttonFetchImages.setOnClickListener(this); } @Override public void onClick(View v) { if(v == buttonFetchImages) { getAllImages(); } } } |
- As you can see we have implemented View.OnClickListener interface. Created our button and added the listener to the button. We also declared a String having the URL of our getAllImages.php file.
- Now we need to create the getAllImages() method.
- This is our getAllImages method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
private void getAllImages() { class GetAllImages extends AsyncTask<String,Void,String>{ ProgressDialog loading; @Override protected void onPreExecute() { super.onPreExecute(); loading = ProgressDialog.show(MainActivity.this, "Fetching Data","Please Wait...",true,true); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); loading.dismiss(); Toast.makeText(MainActivity.this,s,Toast.LENGTH_LONG).show(); } @Override protected String doInBackground(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.getInputStream())); String json; while((json = bufferedReader.readLine())!= null){ sb.append(json+"\n"); } return sb.toString().trim(); }catch(Exception e){ return null; } } } GetAllImages gai = new GetAllImages(); gai.execute(IMAGES_URL); } |
- So the above code is very simple, we are using AsyncTask to read our JSON. And after reading we are displaying the json in a toast message. We are displaying json in toast only to check that json have been read or not. We will remove this toast further. But for now lets check whether the json is being read successfully or not.
- Now add internet permission to your manifest and run the project.
1 2 3 |
<uses-permission android:name="android.permission.INTERNET"/> |
- If you are getting the json string in a toast message after pressing fetch all images button then your project is working fine and you can move ahead. You should see the following output.
Converting JSON to Images
- Remove the Toast Message.
- We need some more components, so declare the following inside your MainActivity.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public class MainActivity extends AppCompatActivity implements View.OnClickListener { private String imagesJSON; private static final String JSON_ARRAY ="result"; private static final String IMAGE_URL = "url"; private JSONArray arrayImages= null; private int TRACK = 0; private static final String IMAGES_URL = "http://www.simplifiedcoding.16mb.com/ImageUpload/getAllImages.php"; private Button buttonFetchImages; private Button buttonMoveNext; private Button buttonMovePrevious; private ImageView imageView; |
- Inside onCreate, initialize them and add listeners to buttons.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView = (ImageView) findViewById(R.id.imageView); buttonFetchImages = (Button) findViewById(R.id.buttonFetchImages); buttonMoveNext = (Button) findViewById(R.id.buttonNext); buttonMovePrevious = (Button) findViewById(R.id.buttonPrev); buttonFetchImages.setOnClickListener(this); buttonMoveNext.setOnClickListener(this); buttonMovePrevious.setOnClickListener(this); } |
- Now we will create a getImage method. This method will take a string as a parameter. The string would have the url to image extracted from json array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
private void getImage(String urlToImage){ class GetImage extends AsyncTask<String,Void,Bitmap>{ ProgressDialog loading; @Override protected Bitmap doInBackground(String... params) { 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 onPreExecute() { super.onPreExecute(); loading = ProgressDialog.show(MainActivity.this,"Downloading Image...","Please wait...",true,true); } @Override protected void onPostExecute(Bitmap bitmap) { super.onPostExecute(bitmap); loading.dismiss(); imageView.setImageBitmap(bitmap); } } GetImage gi = new GetImage(); gi.execute(urlToImage); } |
- Now we will create two more methods. The first one to extract json and other one to show image.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
private void extractJSON(){ try { JSONObject jsonObject = new JSONObject(imagesJSON); arrayImages = jsonObject.getJSONArray(JSON_ARRAY); } catch (JSONException e) { e.printStackTrace(); } } private void showImage(){ try { JSONObject jsonObject = arrayImages.getJSONObject(TRACK); getImage(jsonObject.getString(IMAGE_URL)); } catch (JSONException e) { e.printStackTrace(); } } |
- We need to make some little changes in our getAllImages method.
- Inside onPostExecute we have to call  the extractJSON and showImage() method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
private void getAllImages() { class GetAllImages extends AsyncTask<String,Void,String>{ ProgressDialog loading; @Override protected void onPreExecute() { super.onPreExecute(); loading = ProgressDialog.show(MainActivity.this, "Fetching Data...","Please Wait...",true,true); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); loading.dismiss(); imagesJSON = s; extractJSON(); showImage(); } @Override protected String doInBackground(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.getInputStream())); String json; while((json = bufferedReader.readLine())!= null){ sb.append(json+"\n"); } return sb.toString().trim(); }catch(Exception e){ return null; } } } GetAllImages gai = new GetAllImages(); gai.execute(IMAGES_URL); } |
- Now at last we need to create two more methods to display the next or previous image.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
private void moveNext(){ if(TRACK < arrayImages.length()){ TRACK++; showImage(); } } private void movePrevious(){ if(TRACK>0){ TRACK--; showImage(); } } |
- Now finally call these methods inside onClick.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
@Override public void onClick(View v) { if(v == buttonFetchImages) { getAllImages(); } if(v == buttonMoveNext){ moveNext(); } if(v== buttonMovePrevious){ movePrevious(); } } |
- You can see the final complete code below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 |
package net.simplifiedcoding.getallimages; import android.app.ProgressDialog; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private String imagesJSON; private static final String JSON_ARRAY ="result"; private static final String IMAGE_URL = "url"; private JSONArray arrayImages= null; private int TRACK = 0; private static final String IMAGES_URL = "http://www.simplifiedcoding.16mb.com/ImageUpload/getAllImages.php"; private Button buttonFetchImages; private Button buttonMoveNext; private Button buttonMovePrevious; private ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView = (ImageView) findViewById(R.id.imageView); buttonFetchImages = (Button) findViewById(R.id.buttonFetchImages); buttonMoveNext = (Button) findViewById(R.id.buttonNext); buttonMovePrevious = (Button) findViewById(R.id.buttonPrev); buttonFetchImages.setOnClickListener(this); buttonMoveNext.setOnClickListener(this); buttonMovePrevious.setOnClickListener(this); } private void extractJSON(){ try { JSONObject jsonObject = new JSONObject(imagesJSON); arrayImages = jsonObject.getJSONArray(JSON_ARRAY); } catch (JSONException e) { e.printStackTrace(); } } private void showImage(){ try { JSONObject jsonObject = arrayImages.getJSONObject(TRACK); getImage(jsonObject.getString(IMAGE_URL)); } catch (JSONException e) { e.printStackTrace(); } } private void moveNext(){ if(TRACK < arrayImages.length()){ TRACK++; showImage(); } } private void movePrevious(){ if(TRACK>0){ TRACK--; showImage(); } } private void getAllImages() { class GetAllImages extends AsyncTask<String,Void,String>{ ProgressDialog loading; @Override protected void onPreExecute() { super.onPreExecute(); loading = ProgressDialog.show(MainActivity.this, "Fetching Data...","Please Wait...",true,true); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); loading.dismiss(); imagesJSON = s; extractJSON(); showImage(); } @Override protected String doInBackground(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.getInputStream())); String json; while((json = bufferedReader.readLine())!= null){ sb.append(json+"\n"); } return sb.toString().trim(); }catch(Exception e){ return null; } } } GetAllImages gai = new GetAllImages(); gai.execute(IMAGES_URL); } private void getImage(String urlToImage){ class GetImage extends AsyncTask<String,Void,Bitmap>{ ProgressDialog loading; @Override protected Bitmap doInBackground(String... params) { 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 onPreExecute() { super.onPreExecute(); loading = ProgressDialog.show(MainActivity.this,"Downloading Image...","Please wait...",true,true); } @Override protected void onPostExecute(Bitmap bitmap) { super.onPostExecute(bitmap); loading.dismiss(); imageView.setImageBitmap(bitmap); } } GetImage gi = new GetImage(); gi.execute(urlToImage); } @Override public void onClick(View v) { if(v == buttonFetchImages) { getAllImages(); } if(v == buttonMoveNext){ moveNext(); } if(v== buttonMovePrevious){ movePrevious(); } } } |
Video Demo of Final Output
You can check this video demonstration of what we have created in this tutorial.
Download Source code of this Android Programming Tutorial
If you are having trouble in creating the app shown in this Android Programming Tutorial. Download the source code from the link given below
[easy_media_download url=”https://dl.dropboxusercontent.com/s/su8raogxy4w3kwf/android-programming-tutorial-get-all-images-from-server.zip?dl=0″ text=”Download Source”]
To display all the images in a List check this tutorial
So thats all for this Android Programming Tutorial friends. If you want to learn more about android application development you can go through the official android developers website. And leave your comments for any kind of queries. Thank You 🙂