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
<?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
<?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.
<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
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
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
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";
  urlServer = "http://10.0.2.2/upload/upload.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
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