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.contentimport 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; @Overridesuper.onCreate(savedInstanceState); setContepublic void onCreate(Bundle savedInstanceState) { ntView(R.layout.main); final Button btnUpload = (Button) findViewById(R.id.btn_upload);v) { openImageGallery(); } }); } private voidbtnUpload.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(Uplint 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; impimport java.io.File; import jav aort java.io.InputStreamReader;; import org.apache.http.HttpRespoimport org.apache.http.HttpEntit ynse; import org.apache.http.HttpVersion;olException; import org.apache.http.client.methods.Httimport 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 andimport android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; roid.widget.Toast;skimport com.hendi.example.download.CustomMultiPartEntity.ProgressListener; public class FileUploader extends AsyncTa{ private ProgressDialog progressDialog;private File file;text; private String urlprivate Context co n; private HttpPost request;failed"; public FileUploader(Contexprivate 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); progressDiaprogressDialog.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(CoreProprotected Boolean doInBackground(Void... params) { DefaultHttpClient client = new DefaultHttpClient(); request = new HttpPos ttocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); CustomMultiPartEntity mpEntity = new CustomMultiPartEntity(new ProgressListener() { @OverridetBase)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 = "uploadBufferedReader 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; } @Overrideoid onPostExecute(Boolean result) { progressDialprotected 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; importimport java.io.IOException; import j java.nio.charset.Charset;.mime.HttpMultipartMode; import org.apache.http.entitimport org.apache.http.entit yy.mime.MultipartEntity;tEntity extends MultipartEntity { private final Progrespublic 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 Strinthis.listener = listener; } public CustomMultiPartEntity(HttpMul tg boundary, final Charset charset, final ProgressListener listener) {rride public void writeTo(finalsuper(mode, boundary, charset); this.listener = listener; } @Ov eOutputStream outstream) throws IOException {eam, this.listener)); } public static interface ProgressListenersuper.writeTo(new CountingOutputStream(outst r { void transferred(long num); } public static class CountingOutputStream extends FilterOutputStream {tStream out, final ProgressListener listenprivate 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); thout.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:
kok force close ya mas? settingannya gimana yah? terimakasih
Tidak ada settigan apa2 sih. Di logcat error nya kenapa katanya?
Bisa sharing upload.php nya juga ga ??
bisa share upload.php nya juga ga hhha?
Bisa sharing upload.php nya juga ga ??
Posting Komentar