Skip to content

Instantly share code, notes, and snippets.

Created March 19, 2015 06:07
Show Gist options
  • Save anonymous/68a06fe571cdfabfa9be to your computer and use it in GitHub Desktop.
Save anonymous/68a06fe571cdfabfa9be to your computer and use it in GitHub Desktop.
public class ImageUpload {
private String mImagePath = "";
private boolean isImageUploaded = false;
/**
* @return the mImagePath
*/
public String getmImagePath() {
return mImagePath;
}
/**
* @param mImagePath
* the mImagePath to set
*/
public void setmImagePath(String mImagePath) {
this.mImagePath = mImagePath;
}
/**
* @return the isImageUploaded
*/
public boolean isImageUploaded() {
return isImageUploaded;
}
/**
* @param isImageUploaded
* the isImageUploaded to set
*/
public void setImageUploaded(boolean isImageUploaded) {
this.isImageUploaded = isImageUploaded;
}
@Override
public String toString() {
return mImagePath;
}
}
Activity :
public class SampleActivity extends Activity {
private Handler handler = new Handler();;
private String strPath = "";
private String fileName = "";
private int position;
private ViewHolder holder;
private View v;
private static File file;
private static ListView lstView;
private static List<ImageUpload> ImageList;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*** Get Images from SDCard ***/
ImageList = getSD();
// ListView and imageAdapter
lstView = (ListView) findViewById(R.id.listView);
lstView.setAdapter(new ImageAdapter(this));
}
private List<ImageUpload> getSD() {
List<ImageUpload> it = new ArrayList<ImageUpload>();
// File f = new File("/storage/extSdCard/images/");
File f = new File("/mnt/sdcard/mydata/");
File[] files = f.listFiles();
for (int i = 0; i < files.length; i++) {
File file = files[i];
Log.d("Count", file.getPath());
it.add(new ImageUpload(file.getPath()));
}
return it;
}
private static class ViewHolder {
private TextView textName;
private ImageView thumbnail;
private TextView textStatus;
private Button btnUpload;
public ViewHolder(View convertView) {
}
}
public class ImageAdapter extends BaseAdapter {
public ImageAdapter(Context c) {
}
public int getCount() {
return ImageList.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Avoid unneccessary calls to findViewById() on each row, which is expensive!
holder = null;
ImageUpload mImageUpload = ImageList.get(position);
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.adapter_main, null);
holder = new ViewHolder(convertView);
// Create a ViewHolder and store references to the children views
holder.textName = (TextView) convertView.findViewById(R.id.textName);
holder.thumbnail = (ImageView) convertView.findViewById(R.id.thumbnail);
holder.btnUpload = (Button) convertView.findViewById(R.id.btnUpload);
holder.textStatus = (TextView) convertView.findViewById(R.id.textStatus);
// The tag can be any Object, this just happens to be the ViewHolder
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
strPath = mImageUpload.toString();
// Get File Name
fileName = strPath.substring(strPath.lastIndexOf('/') + 1, strPath.length());
file = new File(strPath);
@SuppressWarnings("unused")
long length = file.length();
holder.textName.setText(fileName);
final BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bm = BitmapFactory.decodeFile(strPath, options);
holder.thumbnail.setImageBitmap(bm);
if (mImageUpload.isImageUploaded())
holder.btnUpload.setEnabled(false);
else
holder.btnUpload.setEnabled(true);
// btnUpload
holder.btnUpload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Upload
startUpload(position);
}
});
return convertView;
}
}
// Upload
public void startUpload(final int position) {
Runnable runnable = new Runnable() {
public void run() {
handler.post(new Runnable() {
public void run() {
v = lstView.getChildAt(position - lstView.getFirstVisiblePosition());
holder = (ViewHolder) v.getTag();
holder.btnUpload.setEnabled(false);
new UploadFileAsync().execute(String.valueOf(position));
}
});
}
};
new Thread(runnable).start();
}
// Async Upload
public class UploadFileAsync extends AsyncTask<String, Void, Void> {
String resServer;
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(String... params) {
position = Integer.parseInt(params[0]);
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
int resCode = 0;
String resMessage = "";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
// File Path
String strSDPath = ImageList.get(position).toString();
// Upload to PHP Script
String strUrlServer = "http://10.0.2.2/uploadFile.php";
try {
/** Check file on SD Card ***/
File file = new File(strSDPath);
if (!file.exists()) {
resServer = "{\"StatusID\":\"0\",\"Message\":\"Please check path on SD Card\"}";
return null;
}
FileInputStream fileInputStream = new FileInputStream(new File(strSDPath));
URL url = new URL(strUrlServer);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
DataOutputStream outputStream = new DataOutputStream(conn.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"filUpload\";filename=\"" + strSDPath + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Response Code and Message
resCode = conn.getResponseCode();
if (resCode == HttpURLConnection.HTTP_OK) {
InputStream is = conn.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int read = 0;
while ((read = is.read()) != -1) {
bos.write(read);
}
byte[] result = bos.toByteArray();
bos.close();
resMessage = new String(result);
}
Log.d("resCode=", Integer.toString(resCode));
Log.d("resMessage=", resMessage.toString());
fileInputStream.close();
outputStream.flush();
outputStream.close();
resServer = resMessage.toString();
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
protected void onPostExecute(Void unused) {
statusWhenFinish(position, resServer);
}
}
// When Upload Finish
@SuppressWarnings("unused")
protected void statusWhenFinish(int position, String resServer) {
/*** Default Value ***/
String strStatusID = "0";
String strError = "";
try {
JSONObject c = new JSONObject(resServer);
strStatusID = c.getString("StatusID");
strError = c.getString("Message");
} catch (JSONException e) {
e.printStackTrace();
}
// prepare Status
if (strStatusID.equals("0")) {
// When update Failed
holder.textStatus.setText("Failed");
holder.btnUpload.setEnabled(true);
ImageList.get(position).setImageUploaded(false);
} else {
holder.textStatus.setText("Uploaded");
holder.btnUpload.setEnabled(false);
ImageList.get(position).setImageUploaded(true);
}
Toast.makeText(SampleActivity.this, "position : " + position + "\nStatus : " + strStatusID, Toast.LENGTH_SHORT).show();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment