Pages

Thursday, December 1, 2016

Membuat Aplikasi Android Upload Gambar ke Server MySQL dengan Eclipse

Tutorial kali ini kita akan mempelajari cara membuat aplikasi android upload gambar ke server MySQL menggunakan Eclipse. untuk lebih jelasnya kita ikuti saja tutorial berikut ini. Buat database dengan nama upload, buat table datamobil seperti pada gambar.

 

Buat file php dan simpan ke xampp/htdocs/upload
upload.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
echo '<pre>';
print_r($_FILES);
echo '</pre>';
 
echo '<pre>';
print_r($_POST);
echo '</pre>';
 
$file_path="img/";
$file_path=$file_path.basename($_FILES['file']['name']);
 
if (move_uploaded_file($_FILES['file']['tmp_name'],$file_path)){
 echo "file save success";
 } else {
 echo "failed to save file";
 }
  
?>

Simpan.php
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
<?php
$f=mysql_connect('localhost','root','');
mysql_select_db('upload',$f);
$response = array();
 
if (isset($_POST['nama']) && isset($_POST['img']))  {
    $name = $_POST['nama'];
 $img = $_POST['img'];
  
    $result = mysql_query("INSERT INTO datamobil(nama_mobil,image) VALUES('$name','$img')");
 
    // cek data udah masuk belum
    if ($result) {
        // kalo sukses
        $response["success"] = 1;
        $response["message"] = "Tambah berhasil";
 
        // echoing JSON response
        echo json_encode($response);
    } else {
        // fkalo gagal
        $response["success"] = 0;
        $response["message"] = "Sistem mendeteksi kesalahan, silahkan coba lagi";
         
        // echoing JSON response
        echo json_encode($response);
    }
} else {
    $response["success"] = 0;
    $response["message"] = "Silahkan lengkapi aksi sebelum memulai permintaan anda";
 
    // echoing JSON response
    echo json_encode($response);
}
?>

Buka eclipse buat project baru


Ubah file activity_main.xml seperti berikut.
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
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
 
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Upload Gambar"
        android:textAppearance="?android:attr/textAppearanceLarge" />
 
    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Nama Mobil" />
 
    <EditText
        android:id="@+id/editnama"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" >
 
        <requestFocus />
    </EditText>
 
    <LinearLayout




Buat file java baru dengan nama berikut di folder package project anda.
CustomMultiPartEntity.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
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
package com.uploadgambar;
 
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
 
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
 
public class CustomMultiPartEntity extends MultipartEntity {
 
 private UploadProgressListener uploadProgressListener;
 
 public CustomMultiPartEntity() {
  super();
 
 }
 
 public CustomMultiPartEntity(final HttpMultipartMode mode) {
  super(mode);
 
 }
 
 public CustomMultiPartEntity(HttpMultipartMode mode, final String boundary,
   final Charset charset) {
  super(mode, boundary, charset);
 
 }
 
 @Override
 public void writeTo(final OutputStream outstream) throws IOException {
  super.writeTo(new CountingOutputStream(outstream,
    this.uploadProgressListener));
 
 }
 
 /**
  *
  * @return
  */
 public UploadProgressListener getUploadProgressListener() {
  return uploadProgressListener;
 }
 
 /**
  *
  * @param uploadProgressListener
  */
 public void setUploadProgressListener(
   UploadProgressListener uploadProgressListener) {
  this.uploadProgressListener = uploadProgressListener;
 }
 
 /**
  *
  * Count the OutputStream
  *
  */
 public static class CountingOutputStream extends FilterOutputStream {
 
  private final UploadProgressListener uploadProgressListener;
  private long transferred;
 
  public CountingOutputStream(final OutputStream out,
    final UploadProgressListener uploadProgressListener) {
   super(out);
   this.uploadProgressListener = uploadProgressListener;
   this.transferred = 0;
  }
 
  @Override
  public void write(byte[] b, int off, int len) throws IOException {
   out.write(b, off, len);
   this.transferred += len;
 
   if (this.uploadProgressListener != null) {
 
    this.uploadProgressListener.transferred(this.transferred);
 
   }
 
  }
 
  @Override
  public void write(int b) throws IOException {
   out.write(b);
   this.transferred++;
 
   if (this.uploadProgressListener != null) {
 
    this.uploadProgressListener.transferred(this.transferred);
 
   }
 
  }
 }
}

JSONParser.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
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
package com.uploadgambar;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
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() {
 
 }
 
 // function get json from url
 // by making HTTP POST or GET mehtod
 public JSONObject makeHttpRequest(String url, String method,
   List<NameValuePair> params) {
 
  try {
   if (method == "POST") {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    httpPost.setEntity(new UrlEncodedFormEntity(params));
 
    HttpResponse httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();
    is = httpEntity.getContent();
 
   } else if (method == "GET") {
    // request method is GET
    DefaultHttpClient httpClient = new DefaultHttpClient();
    String paramString = URLEncodedUtils.format(params, "utf-8");
    url += "?" + paramString;
    HttpGet httpGet = new HttpGet(url);
 
    HttpResponse httpResponse = httpClient.execute(httpGet);
    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;
 
 }
}

MainActivity.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
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
package com.uploadgambar;
 
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
 
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
 
import android.R.integer;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
 
public class MainActivity extends Activity implements OnClickListener {
 String imagePath;
 String imageName;
 ImageView imgeView;
 long imageSize = 0; // kb
 // Progress Dialog
 private ProgressDialog pDialog;
 final static int REQUEST_CODE = 1;
 JSONParser jsonParser = new JSONParser();
 EditText inputName;
 TextView status;
 Button upload;
 
 HttpURLConnection connection = null;
 DataOutputStream outputStream = null;
 DataInputStream inputStream = null;
 
 Bitmap bm;
 String user = null;
 static String pathToOurFile = "", format;
 public String Koneksi, isi;
 String urlServer = "";
 String lineEnd = "\r\n", twoHyphens = "--", boundary = "*****";
 
 int nilai = (int) (Math.random() * 9999999);
 int bytesRead, bytesAvailable, bufferSize;
 byte[] buffer;
 int maxBufferSize = 1 * 1024 * 1024;
 private static String url_tambah_pendaftaran = "";
 
 private static final String TAG_SUCCESS = "success";
 
 @SuppressLint("NewApi")
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  url_tambah_pendaftaran = "http://10.0.2.2/upload/simpan.php";
  StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
    .permitAll().build();
  StrictMode.setThreadPolicy(policy);
  inputName = (EditText) findViewById(R.id.editnama);
  imgeView = (ImageView) findViewById(R.id.imageView1);
  Button btnsimpan = (Button) findViewById(R.id.simpan);
  upload = (Button) findViewById(R.id.pilihimage);
  upload.setOnClickListener(this);
  btnsimpan.setOnClickListener(this);
  status = (TextView) findViewById(R.id.detail);
 }
 
 @Override
 public void onClick(View v) {
  switch (v.getId()) {
  case R.id.pilihimage:
   Intent intent = new Intent();
   intent.setType("image/*");
   intent.setAction(Intent.ACTION_GET_CONTENT);
   startActivityForResult(
     Intent.createChooser(intent, "Select Picture"),
     REQUEST_CODE);
   break;
  case R.id.simpan:
   if (this.imagePath == null) {
    // IF NO IMAGE SELECTED DO NOTHING
    Toast.makeText(this, "No image selected", Toast.LENGTH_SHORT)
      .show();
    return;
   }
 
   this.pDialog = this.createDialog();
   this.pDialog.show();
 
   // EXECUTED ASYNCTASK TO UPLOAD IMAGE
   new ImageUploader().execute();
   break;
  default:
   break;
  }
 }
 
 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  // TODO Auto-generated method stub
  super.onActivityResult(requestCode, resultCode, data);
 
  if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
 
   Uri selectedImageUri = data.getData();
 
   // GET IMAGE PATH
   imagePath = getPath(selectedImageUri);
 
   // IMAGE NAME
   imageName = imagePath.substring(imagePath.lastIndexOf("/"));
 
   imageSize = this.getFileSize(imagePath);
 
   // DECODE TO BITMAP
   Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
 
   // DISPLAY IMAGE
   imgeView.setImageBitmap(bitmap);
   status.setText("File path :" + imageName);
 
  }
 }
 
 /**
  * Get the image path
  *
  * @param uri
  * @return
  */
 private String getPath(Uri uri) {
  String[] projection = { MediaStore.Images.Media.DATA };
  Cursor cursor = managedQuery(uri, projection, null, null, null);
  int column_index = cursor
    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
  cursor.moveToFirst();
  return cursor.getString(column_index);
 }
 
 private ProgressDialog createDialog() {
  ProgressDialog progressDialog = new ProgressDialog(this);
  progressDialog.setMessage("Please wait.. Uploading File");
  progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
  progressDialog.setCancelable(false);
 
  return progressDialog;
 }
 
 /**
  * Get the file size in kilobytes
  *
  * @return
  */
 private long getFileSize(String imagePath) {
  long length = 0;
 
  try {
 
   File file = new File(imagePath);
   length = file.length();
   length = length / 2048;
 
  } catch (Exception e) {
 
   e.printStackTrace();
  }
 
  return length;
 }
 
 /**
  * This class is responsible for uploading data
  *
  * @author lauro
  *
  */
 private class ImageUploader extends AsyncTask<Void, Integer, Boolean>
   implements UploadProgressListener {
 
  @Override
  protected Boolean doInBackground(Void... params) {
 
   try {
 
    InputStream inputStream = new FileInputStream(new File(
      imagePath));
 
    // *** CONVERT INPUTSTREAM TO BYTE ARRAY
 
    byte[] data = this.convertToByteArray(inputStream);
 
    HttpClient httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter(
      CoreProtocolPNames.USER_AGENT,
      System.getProperty("http.agent"));
 
    HttpPost httpPost = new HttpPost(urlServer);
 
    // STRING DATA
    StringBody dataString = new StringBody(
      "This is the sample image");
 
    // FILE DATA OR IMAGE DATA
    InputStreamBody inputStreamBody = new InputStreamBody(
      new ByteArrayInputStream(data), imageName);
 
    // MultipartEntity multipartEntity = new MultipartEntity();
    CustomMultiPartEntity multipartEntity = new CustomMultiPartEntity();
 
    // SET UPLOAD LISTENER
    multipartEntity.setUploadProgressListener(this);
 
    // *** ADD THE FILE
    multipartEntity.addPart("file", inputStreamBody);
 
    // *** ADD STRING DATA
    multipartEntity.addPart("description", dataString);
 
    httpPost.setEntity(multipartEntity);
    httpPost.setEntity(multipartEntity);
 
    // EXECUTE HTTPPOST
    HttpResponse httpResponse = httpClient.execute(httpPost);
 
    // THE RESPONSE FROM SERVER
    String stringResponse = EntityUtils.toString(httpResponse
      .getEntity());
 
    // DISPLAY RESPONSE OF THE SERVER
    Log.d("data from server", stringResponse);
 
    String name = inputName.getText().toString();
    // parameter
    List<NameValuePair> param = new ArrayList<NameValuePair>();
    param.add(new BasicNameValuePair("nama", name));
    param.add(new BasicNameValuePair("img", imageName));
 
    // json object
    JSONObject json = jsonParser.makeHttpRequest(
      url_tambah_pendaftaran, "POST", param);
 
    // cek respon di logcat
    Log.d("Create Response", json.toString());
 
   } catch (FileNotFoundException e1) {
    e1.printStackTrace();
 
    return false;
 
   } catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
 
    return false;
 
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
 
    return false;
   }
 
   return true;
  }
 
  /**
    *
    */
  @Override
  public void transferred(long num) {
 
   // COMPUTE DATA UPLOADED BY PERCENT
 
   long dataUploaded = ((num / 2048) * 100) / imageSize;
 
   // PUBLISH PROGRESS
 
   this.publishProgress((int) dataUploaded);
 
  }
 
  /**
   * Convert the InputStream to byte[]
   *
   * @param inputStream
   * @return
   * @throws IOException
   */
  private byte[] convertToByteArray(InputStream inputStream)
    throws IOException {
 
   ByteArrayOutputStream bos = new ByteArrayOutputStream();
 
   int next = inputStream.read();
   while (next > -1) {
    bos.write(next);
    next = inputStream.read();
   }
 
   bos.flush();
 
   return bos.toByteArray();
  }
 
  @Override
  protected void onProgressUpdate(Integer... values) {
   super.onProgressUpdate(values);
 
   // UPDATE THE PROGRESS DIALOG
 
   pDialog.setProgress(values[0]);
 
  }
 
  @Override
  protected void onPostExecute(Boolean uploaded) {
   // TODO Auto-generated method stub
   super.onPostExecute(uploaded);
 
   if (uploaded) {
 
    // UPLOADING DATA SUCCESS
 
    pDialog.dismiss();
    Toast.makeText(MainActivity.this, "File Uploaded",
      Toast.LENGTH_SHORT).show();
   } else {
 
    // UPLOADING DATA FAILED
 
    pDialog.setMessage("Uploading Failed");
    pDialog.setCancelable(true);
 
   }
 
  }
 
 }
}

UploadProgressListene.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.uploadgambar;
 
/**
 * Upload Listener
 *
 */
public interface UploadProgressListener {
 /**
  * This method updated how much data size uploaded to server
  *
  * @param num
  */
 void transferred(long num);
}


Demikianlah tutorial Membuat Aplikasi Upload Gambar Android ke Server MySQL dengan Eclipse yang dapat saya tuliskan semoga bermanfaat buat anda semua.

Source Code : download disini

3 comments:

  1. thanks banget gan tutorialnya.
    mau tanya kalo misalkan sourcenya di export menjadi .apk bagaimana configurasi pemanggilan ke xamppnya itu apa tetap menggunakan IP yang sama atau ada konfigurasi tambahan ?

    thanks gan.

    ReplyDelete
  2. gan kok punya saya error ya ? dibagian int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    null object

    ReplyDelete
  3. gan bisa bantuin ane benerin coding ane yang error ini

    protected void onActivityResult(int requestCode, int resultCode, Intent data ) {
    switch (requestCode ) {

    case 1:
    REQUEST_CHOOSER:
    if (resultCode == RESULT_OK) {

    final Uri uri = data.getData();
    final String path = FileUtils.getPath(this, uri);
    textViewPath.setText(path);
    }
    break;
    case REQUEST_CHOOSER:
    if (resultCode == RESULT_OK) {

    final Uri gg = data.getData();
    final String path2 = FileUtils.getPath(this, gg);
    textViewPath2.setText(path2);
    }
    break;



    }

    }

    ReplyDelete