Sabtu, 28 April 2012

Upload Image Dengan Progress Bar


Setelah beberapa lama gw ga ngeBlog lagi, akhirnya mulai diberdayakan kembali untuk menulis di blog ini. Pada kesempatan kali ini gw akan coba buat sebuah contoh aplikasi dan contoh coding nya untuk mengupload image di android. Berikut penampakan aplikasi nya. Monggo disimak.



Nah untuk membuat aplikasi kayak diatas cukup dengan menuliskan code di beberapa file berikut.


AndroidManifest.xml
Main.xml
UploadActivity.java
package com.hendi.example.download;
import java.io.File;
vity; import android.content
import android.app.Act i.Intent; import android.database.Cursor;
Bundle; import android.
import android.net.Uri; import android.os .provider.MediaStore; import android.view.View;
adActivity extends Activity {
import android.widget.Button; public class Upl o private static final int SELECT_PICTURE = 0; @Override
super.onCreate(savedInstanceState); setConte
public void onCreate(Bundle savedInstanceState) { ntView(R.layout.main); final Button btnUpload = (Button) findViewById(R.id.btn_upload);
v) { openImageGallery(); } }); } private void
btnUpload.setOnClickListener(new View.OnClickListener() { @Override public void onClick(Vie w openImageGallery(){ Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(
, Intent data) { if(resultCode == RESULT_OK){ if(
Intent.createChooser(intent, "Select image from"), SELECT_PICTURE); } @Override protected void onActivityResult(int requestCode, int resultCod erequestCode == SELECT_PICTURE){ Uri uri = data.getData(); String[] projection = { MediaStore.Images.Media.DATA }; Cursor cursor = managedQuery(uri, projection, null, null, null);
le file = new File(filePath); FileUploader fileUploader = new FileUploader(Upl
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); String filePath = cursor.getString(column_index); F ioadActivity.this, file, "http://hendi.comli.com/learn/upload.php"); fileUploader.execute(); } } }
}
FileUploader.java
package com.hendi.example.download;
import java.io.BufferedReader;
.io.IOException; imp
import java.io.File; import jav aort java.io.InputStreamReader;
; import org.apache.http.HttpRespo
import org.apache.http.HttpEntit ynse; import org.apache.http.HttpVersion;
olException; import org.apache.http.client.methods.Htt
import org.apache.http.client.ClientProto cpEntityEnclosingRequestBase; import org.apache.http.client.methods.HttpPost;
pl.client.DefaultHttpClient; import org.apache.http.
import org.apache.http.entity.mime.content.FileBody; import org.apache.http.i mparams.CoreProtocolPNames; import android.app.ProgressDialog; import android.content.Context;
import android.os.AsyncTask; import and
import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; roid.widget.Toast;
sk
import com.hendi.example.download.CustomMultiPartEntity.ProgressListener; public class FileUploader extends AsyncT
a {
private ProgressDialog progressDialog;
private File file;
text; private String url
private Context co n; private HttpPost request;
failed"; public FileUploader(Contex
private String msg = "upload t context, File file, String url) { this.file = file;
void showProgressDialog(
this.context = context; this.url = url; } privat e){ progressDialog = new ProgressDialog(context); progressDialog.setMax(100);
ogressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDia
progressDialog.setMessage("Uploading " + file.getName()); progressDialog.setP rlog.setProgress(0); progressDialog.setButton("Cancel", new OnClickListener() {
msg = "upload aborted"; request.abort();
public void onClick(DialogInterface dialog, int which) { } }); progressDialog.show(); } @Override protected void onPreExecute() { showProgressDialog(); } @Override
(url); client.getParams().setParameter(CorePro
protected Boolean doInBackground(Void... params) { DefaultHttpClient client = new DefaultHttpClient(); request = new HttpPos ttocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); CustomMultiPartEntity mpEntity = new CustomMultiPartEntity(new ProgressListener() { @Override
tBase)request).setEntity(mpEntity);
public void transferred(long num) { publishProgress(num); } }); mpEntity.addPart("file", new FileBody(file)); ((HttpEntityEnclosingReque s try { HttpResponse response = client.execute(request); HttpEntity entity = response.getEntity();
line = br.readLine(); if(line!=null && line.equalsIgnoreCase("1")){ msg = "upload
BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()), 8 * 1024); String success"; return true; } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; } @Override
oid onPostExecute(Boolean result) { progressDial
protected void onProgressUpdate(Long... values) { int percent = (int)(100.0*(double)values[0]/file.length() + 0.5); progressDialog.setProgress(percent); } @Override protected vog.dismiss(); showToast(); } private void showToast(){ Toast.makeText(context, msg, 3).show(); }
}
CustomMultiPartEntity.java
package com.hendi.example.download;
import java.io.FilterOutputStream;
ava.io.OutputStream; import
import java.io.IOException; import j java.nio.charset.Charset;
.mime.HttpMultipartMode; import org.apache.http.entit
import org.apache.http.entit yy.mime.MultipartEntity;
tEntity extends MultipartEntity { private final Progres
public class CustomMultiPa rsListener listener; public CustomMultiPartEntity(final ProgressListener listener)
pM
{ super(); this.listener = listener; } public CustomMultiPartEntity(final Ht tultipartMode mode, final ProgressListener listener) { super(mode);
ipartMode mode, final Strin
this.listener = listener; } public CustomMultiPartEntity(HttpMul tg boundary, final Charset charset, final ProgressListener listener) {
rride public void writeTo(final
super(mode, boundary, charset); this.listener = listener; } @Ov eOutputStream outstream) throws IOException {
eam, this.listener)); } public static interface ProgressListener
super.writeTo(new CountingOutputStream(outst r { void transferred(long num); } public static class CountingOutputStream extends FilterOutputStream {
tStream out, final ProgressListener listen
private final ProgressListener listener; private long transferred; public CountingOutputStream(final Outp uer) { super(out); this.listener = listener; this.transferred = 0; } public void write(byte[] b, int off, int len) throws IOException {
{ out.write(b); th
out.write(b, off, len); this.transferred += len; this.listener.transferred(this.transferred); } public void write(int b) throws IOException is.transferred++;
this.listener.transferred(this.transferred); } }
}
Untuk lebih jelasnya dapat dicoba code di atas melalui project yang dapat di donlot disini.

5 komentar:

Anonim mengatakan...

kok force close ya mas? settingannya gimana yah? terimakasih

☻☻ SINCERELY ☻☻ mengatakan...

Tidak ada settigan apa2 sih. Di logcat error nya kenapa katanya?

the next future job mengatakan...

Bisa sharing upload.php nya juga ga ??

the next future job mengatakan...

bisa share upload.php nya juga ga hhha?

the next future job mengatakan...

Bisa sharing upload.php nya juga ga ??

Sign up for PayPal and start accepting credit card payments instantly.