Android Upload Image Using PHP MySQL and Display Images in ListView
Android Upload Image Using PHP MySQL and Display Images in ListView
So we also need to create a database table this time. But this time we will store the path to
the image in database. Create the following database
Inside the directory you need a script to connect to your database. So create a script name
dbConnect.php and write the following code
Database Connection
PHP
<?php
define('HOST','mysql.h
define('USER','u50245
define('PASS','belal_1
1
2
3
4
5
6
7
<?php
define('HOST','mysql.hostinger.in');
define('USER','u502452270_andro');
define('PASS','belal_123');
define('DB','u502452270_andro');
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
Now you need one more script that will handle the photo upload. So I created a script
named upload.php with the following code
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
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$image = $_POST['image'];
require_once('dbConnect.php');
$sql ="SELECT id FROM photos ORDER BY id ASC";
$res = mysqli_query($con,$sql);
$id = 0;
while($row = mysqli_fetch_array($res)){
$id = $row['id'];
}
$path = "uploads/$id.png";
$actualpath = "http://simplifiedcoding.16mb.com/PhotoUpload/$path";
$sql = "INSERT INTO photos (image) VALUES ('$actualpath')";
if(mysqli_query($con,$sql)){
file_put_contents($path,base64_decode($image));
echo "Successfully Uploaded";
}
mysqli_close($con);
}else{
echo "Error";
}
29
30
31
32
33
Now the above script will handle uploads. It will store the images sent to a directory
name uploads. So you also need to create a directory name uploads.
The above script will store the path to the images inside the MySQL database through
which we will fetch all the images.
So we need one more image which will give the urls of all the images. For getting the
urls we will use JSON.
Create a new script named getAllImages.php and write the following code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
require_once('dbConnect.php');
$sql = "select image from photos";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,array('url'=>$row['image']));
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
Now our server part is over. You can see below the snapshot of my servers directory.
This part is same as we did before in how to upload image from android
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
2
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
3
android:orientation="vertical"
4
android:layout_height="match_parent"
5 android:paddingLeft="@dimen/activity_horizontal_margin"
6
android:paddingRight="@dimen/activity_horizontal_margin"
7
android:paddingTop="@dimen/activity_vertical_margin"
8
android:paddingBottom="@dimen/activity_vertical_margin"
9 tools:context=".MainActivity">
10
11
12 <Button
13
android:layout_width="fill_parent"
14
android:layout_height="wrap_content"
15
android:text="@string/string_choose_file"
android:id="@+id/buttonChoose" />
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="@+id/imageView" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/string_upload_image"
android:id="@+id/buttonUpload" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/string_view_image"
android:id="@+id/buttonViewImage" />
</LinearLayout>
Create a new java class to handler our http request. I created RequestHandler.java
1
2
3
4
5
6
7
8
9
10
11
12
13
package net.simplifiedcoding.imageuploadsample;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
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
import javax.net.ssl.HttpsURLConnection;
/**
* Created by Belal on 8/19/2015.
*/
public class RequestHandler {
public String sendPostRequest(String requestURL,
HashMap<String, String> postDataParams) {
URL url;
StringBuilder sb = new StringBuilder();
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
sb = new StringBuilder();
String response;
while ((response = br.readLine()) != null){
sb.append(response);
}
}
} catch (Exception e) {
60
e.printStackTrace();
61
}
62
return sb.toString();
63 }
64
65 private String getPostDataString(HashMap<String, String> params) throws
66 UnsupportedEncodingException {
67
StringBuilder result = new StringBuilder();
68
boolean first = true;
69
for (Map.Entry<String, String> entry : params.entrySet()) {
70
if (first)
71
first = false;
72
else
73
result.append("&");
74
75
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
76
result.append("=");
77
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
78
}
79
80
return result.toString();
81 }
}
Now in the MainActivity.java write the following code to make the upload work.
1
2
3
4
5
6
7
8
9
10
11
12
13
package net.simplifiedcoding.imageuploadsample;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
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
import android.util.Log;
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 java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static final String UPLOAD_URL =
"http://simplifiedcoding.16mb.com/PhotoUpload/upload.php";
public static final String UPLOAD_KEY = "image";
60
}
61
62
private void showFileChooser() {
63
Intent intent = new Intent();
64
intent.setType("image/*");
65
intent.setAction(Intent.ACTION_GET_CONTENT);
66
startActivityForResult(Intent.createChooser(intent, "Select Picture"),
67 PICK_IMAGE_REQUEST);
68
}
69
70
@Override
71
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
72
super.onActivityResult(requestCode, resultCode, data);
73
74
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK &&
75 data != null && data.getData() != null) {
76
77
filePath = data.getData();
78
try {
79
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
80
imageView.setImageBitmap(bitmap);
81
} catch (IOException e) {
82
e.printStackTrace();
83
}
84
}
85
}
86
87
public String getStringImage(Bitmap bmp){
88
ByteArrayOutputStream baos = new ByteArrayOutputStream();
89
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
90
byte[] imageBytes = baos.toByteArray();
91
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
92
return encodedImage;
93
}
94
95
private void uploadImage(){
96
class UploadImage extends AsyncTask<Bitmap,Void,String>{
97
98
ProgressDialog loading;
99
RequestHandler rh = new RequestHandler();
100
101
@Override
102
protected void onPreExecute() {
103
super.onPreExecute();
104
loading = ProgressDialog.show(MainActivity.this, "Uploading...", null,true,true);
105
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
}
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
@Override
protected String doInBackground(Bitmap... params) {
Bitmap bitmap = params[0];
String uploadImage = getStringImage(bitmap);
HashMap<String,String> data = new HashMap<>();
data.put(UPLOAD_KEY, uploadImage);
String result = rh.sendPostRequest(UPLOAD_URL,data);
return result;
}
}
UploadImage ui = new UploadImage();
ui.execute(bitmap);
}
@Override
public void onClick(View v) {
if (v == buttonChoose) {
showFileChooser();
}
if(v == buttonUpload){
uploadImage();
}
if(v == buttonView){
viewImage();
}
}
private void viewImage() {
startActivity(new Intent(this, ImageListView.class));
}
}
Your app will now give you some error because we have not created new activity named
ImageListView.class. You can comment this line for now.
Now add Internet permission to your manifest. Your upload image will work at this point.
Uploading Image
Now the lets move to the next part which is downloading uploaded images.
The process I will be following here is good when you have to load few images. Because here
we will be downloading all the images at once. And if you have 100s or 1000s images to show
up on ListView, you should not follow this. So to make your list efficient check this tutorial here
Android Adding Items to List on Scroll
Uncomment your line which were causing error before. Now to remove this error we
need to create a new Activity.
Now when we will click the View Image button this activity should open.
In this activity we will create a ListView. So come to the respective layout of this activity.
(In my case it is activity_image_list_view.xml
You can use the following xml code for creating above layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
1
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
2
android:orientation="vertical"
3
android:layout_height="match_parent"
4
android:paddingLeft="@dimen/activity_horizontal_margin"
5
android:paddingRight="@dimen/activity_horizontal_margin"
6
android:paddingTop="@dimen/activity_vertical_margin"
7
android:paddingBottom="@dimen/activity_vertical_margin"
8
tools:context="net.simplifiedcoding.imageuploadsample.ImageListView">
9
10
11
<ListView
12
android:layout_width="match_parent"
13
android:layout_height="wrap_content"
14
android:id="@+id/listView" />
15
16
</LinearLayout>
We have to create a Custom List View for so we will create a new xml resource file for
our Custom List View.
I created image_list_view.xml
Now create a new class named CustomList for our Custom List View.
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
package net.simplifiedcoding.imageuploadsample;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Created by Belal on 7/22/2015.
*/
public class CustomList extends ArrayAdapter<String> {
private String[] urls;
private Bitmap[] bitmaps;
private Activity context;
public CustomList(Activity context, String[] urls, Bitmap[] bitmaps) {
super(context, R.layout.image_list_view, urls);
this.context = context;
this.urls= urls;
this.bitmaps= bitmaps;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.image_list_view, null, true);
TextView textViewURL = (TextView) listViewItem.findViewById(R.id.textViewURL);
ImageView image = (ImageView) listViewItem.findViewById(R.id.imageDownloaded);
textViewURL.setText(urls[position]);
image.setImageBitmap(Bitmap.createScaledBitmap(bitmaps[position],100,50,false));
return listViewItem;
38 }
39 }
Now we need to fetch all the Bitmaps from server. So for this we will create a new class.
I created GetAlImages.java
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
package net.simplifiedcoding.imageuploadsample;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by Belal on 9/19/2015.
*/
public class GetAlImages {
public static String[] imageURLs;
public static Bitmap[] bitmaps;
public static final String JSON_ARRAY="result";
public static final String IMAGE_URL = "url";
private String json;
private JSONArray urls;
public GetAlImages(String json){
this.json = json;
try {
JSONObject jsonObject = new JSONObject(json);
urls = jsonObject.getJSONArray(JSON_ARRAY);
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 }
} catch (JSONException e) {
e.printStackTrace();
}
}
private Bitmap getImage(JSONObject jo){
URL url = null;
Bitmap image = null;
try {
url = new URL(jo.getString(IMAGE_URL));
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return image;
}
public void getAllImages() throws JSONException {
bitmaps = new Bitmap[urls.length()];
imageURLs = new String[urls.length()];
for(int i=0;i<urls.length();i++){
imageURLs[i] = urls.getJSONObject(i).getString(IMAGE_URL);
JSONObject jsonObject = urls.getJSONObject(i);
bitmaps[i]=getImage(jsonObject);
}
}
We will pass the json string having all the urls of our images to the constructor of this
class.
We will get the json string having all the urls from our getAllImages.php script.
package net.simplifiedcoding.im
import android.app.ProgressDia
import android.content.Intent;
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
package net.simplifiedcoding.imageuploadsample;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.Image;
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.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import org.json.JSONException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class ImageListView extends AppCompatActivity implements
AdapterView.OnItemClickListener {
private ListView listView;
public static final String
GET_IMAGE_URL="http://simplifiedcoding.16mb.com/PhotoUpload/getAllImages.php";
public GetAlImages getAlImages;
public static final String BITMAP_ID = "BITMAP_ID";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_list_view);
42
listView = (ListView) findViewById(R.id.listView);
43
listView.setOnItemClickListener(this);
44
getURLs();
45
}
46
47
private void getImages(){
48
class GetImages extends AsyncTask<Void,Void,Void>{
49
ProgressDialog loading;
50
@Override
51
protected void onPreExecute() {
52
super.onPreExecute();
53
loading = ProgressDialog.show(ImageListView.this,"Downloading
54 images...","Please wait...",false,false);
55
}
56
57
@Override
58
protected void onPostExecute(Void v) {
59
super.onPostExecute(v);
60
loading.dismiss();
61
//Toast.makeText(ImageListView.this,"Success",Toast.LENGTH_LONG).show();
62
CustomList customList = new
63 CustomList(ImageListView.this,GetAlImages.imageURLs,GetAlImages.bitmaps);
64
listView.setAdapter(customList);
65
}
66
67
@Override
68
protected Void doInBackground(Void... voids) {
69
try {
70
getAlImages.getAllImages();
71
72
} catch (JSONException e) {
73
e.printStackTrace();
74
}
75
return null;
76
}
77
}
78
GetImages getImages = new GetImages();
79
getImages.execute();
80
}
81
82
private void getURLs() {
83
class GetURLs extends AsyncTask<String,Void,String>{
84
ProgressDialog loading;
85
86
@Override
87
protected void onPreExecute() {
88
super.onPreExecute();
89
loading = ProgressDialog.show(ImageListView.this,"Loading...","Please
90 Wait...",true,true);
91
}
92
93
@Override
94
protected void onPostExecute(String s) {
95
super.onPostExecute(s);
96
loading.dismiss();
97
getAlImages = new GetAlImages(s);
98
getImages();
99
}
100
101
@Override
102
protected String doInBackground(String... strings) {
103
BufferedReader bufferedReader = null;
104
try {
105
URL url = new URL(strings[0]);
106
HttpURLConnection con = (HttpURLConnection) url.openConnection();
107
StringBuilder sb = new StringBuilder();
108
109
bufferedReader = new BufferedReader(new
110 InputStreamReader(con.getInputStream()));
111
112
String json;
113
while((json = bufferedReader.readLine())!= null){
114
sb.append(json+"\n");
115
}
116
117
return sb.toString().trim();
118
119
}catch(Exception e){
120
return null;
121
}
122
}
123
}
124
GetURLs gu = new GetURLs();
125
gu.execute(GET_IMAGE_URL);
126 }
127
128 @Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(this, ViewFullImage.class);
intent.putExtra(BITMAP_ID,i);
startActivity(intent);
}
Now we will create a new activity to see the full size image. I created
ViewFullImage.java.
1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
2
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
3
android:layout_height="match_parent"
4 android:paddingLeft="@dimen/activity_horizontal_margin"
5
android:paddingRight="@dimen/activity_horizontal_margin"
6
android:paddingTop="@dimen/activity_vertical_margin"
7
android:paddingBottom="@dimen/activity_vertical_margin"
8
tools:context="net.simplifiedcoding.imageuploadsample.ViewFullImage">
9
10
11
12
13
14
15
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/imageViewFull"
/>
</RelativeLayout>
Inside your java class for this layout write the following code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package net.simplifiedcoding.imageuploadsample;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
public class ViewFullImage extends AppCompatActivity {
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_full_image);
Intent intent = getIntent();
int i = intent.getIntExtra(ImageListView.BITMAP_ID,0);
imageView = (ImageView) findViewById(R.id.imageViewFull);
imageView.setImageBitmap(GetAlImages.bitmaps[i]);
}
}
Now thats it. If you want the source code of this project you can download from here
Download Source
So thats it for this Android Upload Image Using PHP MySQL Tutorial friends. If you are having
confusions please leave you comments below.