Uploading bulk images to server on button click, but have one issue, whenever I do click on upload all button, it starts uploading of all list item images, but every time it resumes new progress for each and every list row.
Like i have 500 list items in a list, so it resuming 500 progress, whereas I just want to use single progress for all.
Here is my code, which I am using :
public class MainActivity extends Activity {
static ListView lstView;
private Handler handler = new Handler();;
static List<MyData> ImageList;
String strPath;
int position;
File newFile;
ViewHolder holder;
View v;
String fileName;
ImageAdapter mAdapter;
Button btnUploadAll;
int i=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnUploadAll = (Button) findViewById(R.id.btnUploadAll);
btnUploadAll.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(ImageList.size()!=0)
{
new UploadFileAsync().execute(String.valueOf(i));
}
}
});
/*** Get Images from SDCard ***/
ImageList = getSD();
// ListView and imageAdapter
lstView = (ListView) findViewById(R.id.listView);
mAdapter = new ImageAdapter(this);
lstView.setAdapter(mAdapter);
}
private List<MyData> getSD() {
List<MyData> it = new ArrayList<MyData>();
String root_sd = Environment.getExternalStorageDirectory().toString();
File f = new File(root_sd + "/mydata");
File[] files = f.listFiles();
for (int i = 0; i < files.length; i++) {
File file = files[i];
Log.d("Count", file.getPath());
MyData data = new MyData();
data.setImages(file.getPath());
data.setStatusEnable(true);
it.add(data);
}
return it;
}
static class ViewHolder {
public ViewHolder(View convertView) {
// TODO Auto-generated constructor stub
}
TextView textName;
ImageView thumbnail;
TextView textStatus;
Button btnUpload;
}
public class ImageAdapter extends BaseAdapter {
public ImageAdapter(Context c) {
}
public int getCount() {
// TODO Auto-generated method stub
return ImageList.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
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;
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();
}
holder.btnUpload.setEnabled(ImageList.get(position)
.isStatusEnable());
holder.textStatus.setText(ImageList.get(position).getMessage());
strPath = ImageList.get(position).getImages().toString();
// Get File Name
fileName = strPath.substring(strPath.lastIndexOf('/') + 1,
strPath.length());
File 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);
// 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();
synchronized (this) {
ImageList.get(position).setStatusEnable(false);
mAdapter.notifyDataSetChanged();
}
new UploadFileAsync().execute(String.valueOf(position));
}
});
}
};
new Thread(runnable).start();
}
// Async Upload
public class UploadFileAsync extends AsyncTask<String, Void, Void> {
private ProgressDialog pDialog;
String resServer;
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#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).getImages().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) {
if(i<imageList.size()){
i++;
new UploadFileAsync().execute(String.valueOf(i));
}
statusWhenFinish(position, resServer);
// dismiss the dialog once product deleted
pDialog.dismiss();
}
}
// When Upload Finish
#SuppressWarnings("unused")
protected void statusWhenFinish(int position, String resServer) {
/*** Default Value ***/
String strStatusID = "";
String strError = "";
try {
JSONObject c = new JSONObject(resServer);
strStatusID = c.getString("StatusID");
strError = c.getString("Message");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// // prepare Status
if (strStatusID.equals("0")) {
ImageList.get(position).setMessage("Failed");
ImageList.get(position).setStatusEnable(true);
mAdapter.notifyDataSetChanged();
} else if (strStatusID.equals("1")) {
ImageList.get(position).setMessage("Already Exists");
ImageList.get(position).setStatusEnable(false);
mAdapter.notifyDataSetChanged();
} else if(strStatusID.equals("2")) {
ImageList.get(position).setMessage("Uploaded");
ImageList.get(position).setStatusEnable(false);
mAdapter.notifyDataSetChanged();
} else {
}
}
/**
* Introduce a class with below attributes to hold a state of each row in
* single element
*
*/
public class MyData {
/* Image url or path of image in single row */
private String images;
/* anme of image in single row */
private String name;
/* status ID of image in single row */
private String statusID;
/* message of image in single row */
private String message;
private boolean statusEnable;
public boolean isStatusEnable() {
return statusEnable;
}
public void setStatusEnable(boolean statusEnable) {
this.statusEnable = statusEnable;
}
// Generate getters and setter
public String getImages() {
return images;
}
public void setImages(String images) {
this.images = images;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStatusID() {
return statusID;
}
public void setStatusID(String statusID) {
this.statusID = statusID;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
}
Sorry again, i'm too busy now for editing your whole code, so i will give you directions instead.
First, move your private ProgressDialog pDialog; in your asynctask class to your global variable, like :
String fileName;
ImageAdapter mAdapter;
Button btnUploadAll;
int i=0;
private ProgressDialog pDialog;
Second, move your instantiate object for progress dialog to :
if(ImageList.size()!=0)
{
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
new UploadFileAsync().execute(String.valueOf(i));
}
Third, close your dialog after upload all of your image:
if(i<imageList.size()){
i++;
new UploadFileAsync().execute(String.valueOf(i));
}
else {
pDialog.dismiss();
}
statusWhenFinish(position, resServer);
package com.example.slideanim.temp;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.example.slideanim.R;
public class MainActivity extends Activity {
static ListView lstView;
private Handler handler = new Handler();;
static List<MyData> ImageList;
String strPath;
int position;
File newFile;
ViewHolder holder;
View v;
String fileName;
ImageAdapter mAdapter;
Button btnUploadAll;
int i = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnUploadAll = (Button) findViewById(R.id.btnUploadAll);
btnUploadAll.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (ImageList.size() != 0) {
new UploadFileAsync().execute(String.valueOf(i));
}
}
});
/*** Get Images from SDCard ***/
ImageList = getSD();
// ListView and imageAdapter
lstView = (ListView) findViewById(R.id.listView);
mAdapter = new ImageAdapter(this);
lstView.setAdapter(mAdapter);
}
private List<MyData> getSD() {
List<MyData> it = new ArrayList<MyData>();
String root_sd = Environment.getExternalStorageDirectory().toString();
File f = new File(root_sd + "/mydata");
File[] files = f.listFiles();
for (int i = 0; i < files.length; i++) {
File file = files[i];
Log.d("Count", file.getPath());
MyData data = new MyData();
data.setImages(file.getPath());
data.setStatusEnable(true);
it.add(data);
}
return it;
}
static class ViewHolder {
public ViewHolder(View convertView) {
// TODO Auto-generated constructor stub
}
TextView textName;
ImageView thumbnail;
TextView textStatus;
Button btnUpload;
}
public class ImageAdapter extends BaseAdapter {
public ImageAdapter(Context c) {
}
public int getCount() {
// TODO Auto-generated method stub
return ImageList.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
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;
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();
}
holder.btnUpload.setEnabled(ImageList.get(position)
.isStatusEnable());
holder.textStatus.setText(ImageList.get(position).getMessage());
strPath = ImageList.get(position).getImages().toString();
// Get File Name
fileName = strPath.substring(strPath.lastIndexOf('/') + 1,
strPath.length());
File 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);
// 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();
synchronized (this) {
ImageList.get(position).setStatusEnable(false);
mAdapter.notifyDataSetChanged();
}
new UploadFileAsync().execute(String.valueOf(position));
}
});
}
};
new Thread(runnable).start();
}
// Async Upload
public class UploadFileAsync extends AsyncTask<String, Void, Void> {
private ProgressDialog pDialog;
String resServer;
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Void doInBackground(String... params) {
if (ImageList == null || ImageList.size() == 0)
return null;
//below you need to change
for (MyData myData : ImageList) {
// 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 = myData.getImages().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);
// dismiss the dialog once product deleted
pDialog.dismiss();
}
}
// When Upload Finish
#SuppressWarnings("unused")
protected void statusWhenFinish(int position, String resServer) {
/*** Default Value ***/
String strStatusID = "";
String strError = "";
try {
JSONObject c = new JSONObject(resServer);
strStatusID = c.getString("StatusID");
strError = c.getString("Message");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// // prepare Status
if (strStatusID.equals("0")) {
ImageList.get(position).setMessage("Failed");
ImageList.get(position).setStatusEnable(true);
mAdapter.notifyDataSetChanged();
} else if (strStatusID.equals("1")) {
ImageList.get(position).setMessage("Already Exists");
ImageList.get(position).setStatusEnable(false);
mAdapter.notifyDataSetChanged();
} else if (strStatusID.equals("2")) {
ImageList.get(position).setMessage("Uploaded");
ImageList.get(position).setStatusEnable(false);
mAdapter.notifyDataSetChanged();
} else {
}
}
/**
* Introduce a class with below attributes to hold a state of each row in
* single element
*
*/
public class MyData {
/* Image url or path of image in single row */
private String images;
/* anme of image in single row */
private String name;
/* status ID of image in single row */
private String statusID;
/* message of image in single row */
private String message;
private boolean statusEnable;
public boolean isStatusEnable() {
return statusEnable;
}
public void setStatusEnable(boolean statusEnable) {
this.statusEnable = statusEnable;
}
// Generate getters and setter
public String getImages() {
return images;
}
public void setImages(String images) {
this.images = images;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStatusID() {
return statusID;
}
public void setStatusID(String statusID) {
this.statusID = statusID;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
}
While uploading first image show pDialog and at upload of last image dismiss the pDialog.
ProgressDialog pDialog;
public void showProgressDialog(){
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
public void onPreExecute(..){
if(pDialog==null)
showProgressDialog()
}
public void onPostExecute(..){
.....
.......
if(i==imageList.size(){
if(pDialog!=null) pDialog.dismiss();
}
You can Use Lazy Loading with asyntask and upload all images first time and save it in sd card or table , If you access it second time that time check condition from sd card or table its all are available or not and use it from sd card or table
http://codehenge.net/blog/2011/06/android-development-tutorial-asynchronous-lazy-loading-and-caching-of-listview-images/
Related
I'm creating a multi-upload screen with android based on an example I found on the internet. I made some simple modifications that make with whom to each file send it passes to the next one of the list.
I used these simple lines:
int n = ImageList.size()-1;
if (position<n) {
startUpload(position + 1);
}
Here is the complete code on the link.
Ex: http://www.thaicreate.com/mobile/android-upload-file-show-items-progressbar-listview.html
More ran into parts. The problem is when it goes to the problem field of the listview automatically and it is not visible on the screen the system stops and it sucks the message and error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById (int)' on a null object reference.
I already searched the forum and I did not find the solution.
Error occurs in this lines:
View v = lstView.getChildAt(position - lstView.getFirstVisiblePosition());
COMPLETE CODE:
public class MainActivity extends Activity {
private ListView lstView;
private Handler handler = new Handler();
private int counter = 0;
List <String> ImageList;
private ProgressBar progress;
private TextView status;
private Button btnUpload;
#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.listView1);
lstView.setAdapter(new ImageAdapter(this));
}
private List <String> getSD()
{
List <String> it = new ArrayList <String>();
File f = new File ("/mnt/sdcard/RAIOTOI/photo/");
File[] files = f.listFiles ();
for (int i = 0; i <files.length; i++)
{
File file = files[i];
Log.d("Count",file.getPath());
it.add (file.getPath());
}
return it;
}
public class ImageAdapter extends BaseAdapter
{
private Context context;
public ImageAdapter(Context c)
{
// TODO Auto-generated method stub
context = c;
}
public int getCount() {
// TODO Auto-generated method stub
return ImageList.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.activity_column, null);
}
status = (TextView) convertView.findViewById(R.id.ColStatus);
btnUpload = (Button) convertView.findViewById(R.id.btnUpload);
// ColImgName
TextView txtName = (TextView) convertView.findViewById(R.id.ColImgName);
String strPath = ImageList.get(position).toString();
// Get File Name
String fileName = strPath.substring( strPath.lastIndexOf('/')+1, strPath.length() );
File file = new File(strPath);
long length = file.length();
txtName.setPadding(3, 0, 0, 0);
txtName.setText(fileName + " ("+length/1024+" KB.)");
// Image Resource
ImageView imageView = (ImageView) convertView.findViewById(R.id.ColImgPath);
imageView.getLayoutParams().height = 110;
imageView.getLayoutParams().width = 110;
imageView.setPadding(10, 10, 2, 10);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
Bitmap bm = BitmapFactory.decodeFile(strPath);
imageView.setImageBitmap(bm);
// ColStatus
final TextView txtStatus = (TextView) convertView.findViewById(R.id.ColStatus);
txtStatus.setPadding(3, 0, 0, 0);
txtStatus.setText("...");
// progressBar
progress = (ProgressBar) convertView.findViewById(R.id.progressBar);
progress.setVisibility(View.GONE);
progress.setPadding(0, 0, 0, 0);
//btnUpload
final Button btnUpload = (Button) convertView.findViewById(R.id.btnUpload);
btnUpload.setTextColor(Color.BLACK);
btnUpload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Upload
btnUpload.setEnabled(false);
btnUpload.setTextColor(Color.GRAY);
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() {
View v = lstView.getChildAt(position - lstView.getFirstVisiblePosition());
// Show ProgressBar
ProgressBar progress = (ProgressBar) v.findViewById(R.id.progressBar);
progress.setVisibility(View.VISIBLE);
// Status
status = (TextView) v.findViewById(R.id.ColStatus);
status.setText("Enviando...");
new UploadFileAsync().execute(String.valueOf(position));
}
});
}
};
new Thread(runnable).start();
}
// Async Upload
public class UploadFileAsync extends AsyncTask<String, Void, Void> {
String resServer;
int position;
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
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://192.168.1.134:8080/up.php";
try {
/** Check file on SD Card ***/
File file = new File(strSDPath);
if(!file.exists())
{
resServer = "{\"StatusID\":\"0\",\"Error\":\"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) {
// Exception handling
return null;
}
return null;
}
protected void onPostExecute(Void unused) {
statusWhenFinish(position,resServer);
}
}
// When UPload Finish
protected void statusWhenFinish(int position, String resServer) {
View v = lstView.getChildAt(position - lstView.getFirstVisiblePosition());
progress = (ProgressBar) v.findViewById(R.id.progressBar);
// Show ProgressBar
progress.setVisibility(View.GONE);
// Status
status = (TextView) v.findViewById(R.id.ColStatus);
/** Get result from Server (Return the JSON Code)
* StatusID = ? [0=Failed,1=Complete]
* Error = ? [On case error return custom error message]
*
* Eg Upload Failed = {"StatusID":"0","Error":"Cannot Upload file!"}
* Eg Upload Complete = {"StatusID":"1","Error":""}
*/
/*** Default Value ***/
String strStatusID = "0";
String strError = "Unknow Status!";
try {
JSONObject c = new JSONObject(resServer);
strStatusID = c.getString("StatusID");
strError = c.getString("Error");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Prepare Status
if(strStatusID.equals("0"))
{
// When update Failed
status.setText("FALHOU ("+ strError +")");
status.setTextColor(Color.RED);
// Enabled Button again
btnUpload = (Button) v.findViewById(R.id.btnUpload);
btnUpload.setText("Repetir");
btnUpload.setTextColor(Color.RED);
btnUpload.setEnabled(true);
}
else
{
status.setText("Envio completo.");
status.setTextColor(Color.GREEN);
btnUpload.setEnabled(false);
btnUpload.setTextColor(Color.GRAY);
int n = ImageList.size()-1;
Log.i("IDID", " "+position+" "+n);
if (position<n) {
startUpload(position + 1);
}
}
}
}
Your lstView is null, make sure you findViewById() it first.
i Was try to display image to card view but it not working and do not show error. Anyone help me please. I am new android. i checked file exists from downloaded folder: /storage/emulated/0/hismart/hinhmon
public class Album {
private String name;
private String gia;
private String thumbnail;
private String url;
public Album() {
}
public Album(String name, String gias, String thumbnail, String url) {
this.name = name;
this.gia = gias;
this.thumbnail = thumbnail;
this.url = url;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGia() {
return gia;
}
public void setGia(String gia) {
this.gia = gia;
}
public String getThumbnail() {
return thumbnail;
}
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
Creat and add data to ArrayList:
List<String> ArrTenmon = new ArrayList<String>();
List<String> ArrGia = new ArrayList<String>();
List<String> ArrImgLocal = new ArrayList<String>();
List<String> ArrImgUrl = new ArrayList<String>();
and add
} Cursor c = db.getdata("select * from tbl_mon_app");
int count = c.getCount();
for (int i = 0; i < count; i++) {
new DownloadFile().execute(ArrImgUrl.get(i));
if (!fileloc.exists()) {
fileloc.mkdirs();
}
Album a = new Album(ArrTenmon.get(i), ArrGia.get(i), ArrImgLocal.get(i), ArrImgUrl.get(i));
albumList.add(a);
adapter.notifyDataSetChanged();
}
and in adapter:
String folder_main = "hismart/hinhmon";
File fileloc = new File(Environment.getExternalStorageDirectory(), folder_main);
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title, count;
public ImageView thumbnail, overflow;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
count = (TextView) view.findViewById(R.id.count);
thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
overflow = (ImageView) view.findViewById(R.id.overflow);
}
}
public AlbumsAdapter(Context mContext, List<Album> albumList) {
this.mContext = mContext;
this.albumList = albumList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.album_card, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
Album album = albumList.get(position);
holder.title.setText(album.getName());
holder.count.setText(album.getGia() + " vnđ");
File imgFile = new File(fileloc+"/"+ "album" + position);
Glide.with(mContext).load(imgFile).into(holder.thumbnail);
}
#Override
public int getItemCount() {
return albumList.size();
}
And Problem in bellow can not display image, name of image is: album1, alubm2...
File imgFile = new File(fileloc+"/"+ "album" + position);
Glide.with(mContext).load(imgFile).into(holder.thumbnail);
Download file:
class DownloadFile extends AsyncTask<String, Integer, String> {
ProgressDialog mProgressDialog = new ProgressDialog(BookActivity.this);// Change Mainactivity.this with your activity name.
String strFolderName;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... aurl) {
int count;
String targetFileName = null;
try {
URL url = new URL((String) aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
targetFileName = aurl[0].substring(aurl[0].lastIndexOf("/") + 1);
int lenghtOfFile = conexion.getContentLength();
String PATH = Environment.getExternalStorageDirectory() + "/hismart/hinhmon/";
File folder = new File(PATH);
if (!folder.exists()) {
folder.mkdir();//If there is no folder it will be created.
}
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(PATH + targetFileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100 / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return targetFileName;
}
protected void onProgressUpdate(Integer... progress) {
mProgressDialog.setProgress(progress[0]);
if (mProgressDialog.getProgress() == mProgressDialog.getMax()) {
mProgressDialog.dismiss();
}
}
protected void onPostExecute(String result) {
}
}
call asyntask to download file
Cursor c = db.getdata("select * from tbl_mon_app");
int count = c.getCount();
for (int i = 0; i < count; i++) {
new DownloadFile().execute(ArrImgLocal.get(i));
if (!fileloc.exists()) {
fileloc.mkdirs();
}
}
Logcat: Show nothing error
Result like this:image after run
I am sure Glide code which you used will works, i have used it many project. There might be problem in your image file. Cross check all the points Sd card permissions, file path use are getting correct
if not worked try to convert file to Uri, it may help
File imgFile = new File(fileloc+"/"+ "album" + position);
Uri imageUri = Uri.fromFile(file);
Glide.with(this).load(imageUri).into(imgView);
Let's see screenshots of work, for better understanding of issue:
I have uploaded first list item's image to server [i.e:- Thumbnail 1.png], see below image:
I got uploaded Image under myfile folder, using Localhost:
When I scrolls down ListView, getting this - here comes the actual pain, as you can see Thumbnail 7, i have not clicked on it:
And when again i scrolls up ListView, getting something this - that's irritating me, in a same way for Thumbnail 2, i did not touch that:
I think that's enough to explain you, what i am trying to do, what's happening and where i am getting issue
So now your turn to let me know the solution, How can i resolve this issue ?
Some Explanation:
I have uploaded first list item's image to server (and as per my requirement i got status of image as "uploaded" and upload button is now disabled) but when i scroll down/up listview its showing any one of the item in a list as uploaded not that one i have uploaded (i noticed mainly that list item which is visible) and resetting status of first list item which originally uploaded to server...
So here i just want to make upload status stable for that particular one which i have uploaded originally... not any of the visible item (those have not uploaded yet)
Just effecting on listview, nothing happening to server (getting only one image which i have uploaded)
MainActivity.java:-
public class MainActivity extends Activity {
static ListView lstView;
private Handler handler = new Handler();;
static List <String> ImageList;
String strPath;
int position ;
static File f;
File newFile;
static File[] files ;
static File file ;
ViewHolder holder;
View v ;
String fileName;
#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 <String> getSD()
{
List <String> it = new ArrayList <String>();
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 (file.getPath());
}
return it;
}
static class ViewHolder {
public ViewHolder(View convertView) {
// TODO Auto-generated constructor stub
}
TextView textName;
ImageView thumbnail;
TextView textStatus;
Button btnUpload;
}
public class ImageAdapter extends BaseAdapter
{
public ImageAdapter(Context c)
{
}
public int getCount() {
// TODO Auto-generated method stub
return ImageList.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
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;
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 = ImageList.get(position).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);
//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) {
// TODO Auto-generated method stub
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) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// prepare Status
if(strStatusID.equals("0"))
{
// When update Failed
holder.textStatus.setText("Failed");
holder.btnUpload.setEnabled(true);
}
else
{
holder.textStatus.setText("Uploaded");
holder.btnUpload.setEnabled(false);
}
}
}
Introduce a structure like below :
/**
* Introduce a class with below attributes to hold a state of each row in single
* element
*
*/
public class MyData {
/* Image url or path of image in single row */
private String images;
/* anme of image in single row */
private String name;
/* status ID of image in single row */
private String statusID;
/* message of image in single row */
private String message;
// Generate getters and setter
public String getImages() {
return images;
}
public void setImages(String images) {
this.images = images;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStatusID() {
return statusID;
}
public void setStatusID(String statusID) {
this.statusID = statusID;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
Added appropriate comments to understand the code.
// MyDataList is the arrylist ArrayList(), you need to init this data structure in constructor
public View getView(int position, View convertView, ViewGroup parent) {
MyData fields = MyDataList.get(position);
}
Edit :
I have edite the code above posted , Look at code below how i used The MyData to set the status
package com.example.trial;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
static ListView lstView;
private Handler handler = new Handler();;
static List<MyData> ImageList;
String strPath;
int position;
File newFile;
ViewHolder holder;
View v;
String fileName;
ImageAdapter mAdapter;
#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);
mAdapter = new ImageAdapter(this);
lstView.setAdapter(mAdapter);
}
private List<MyData> getSD() {
List<MyData> it = new ArrayList<MyData>();
String root_sd = Environment.getExternalStorageDirectory().toString();
File f = new File(root_sd + "/Download");
File[] files = f.listFiles();
for (int i = 0; i < files.length; i++) {
File file = files[i];
Log.d("Count", file.getPath());
MyData data = new MyData();
data.setImages(file.getPath());
data.setStatusEnable(true);
it.add(data);
}
return it;
}
static class ViewHolder {
public ViewHolder(View convertView) {
// TODO Auto-generated constructor stub
}
TextView textName;
ImageView thumbnail;
TextView textStatus;
Button btnUpload;
}
public class ImageAdapter extends BaseAdapter {
public ImageAdapter(Context c) {
}
public int getCount() {
// TODO Auto-generated method stub
return ImageList.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
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;
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();
}
holder.btnUpload.setEnabled(ImageList.get(position)
.isStatusEnable());
holder.textStatus.setText(ImageList.get(position).getMessage());
strPath = ImageList.get(position).getImages().toString();
// Get File Name
fileName = strPath.substring(strPath.lastIndexOf('/') + 1,
strPath.length());
File 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);
// 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();
synchronized (this) {
ImageList.get(position).setStatusEnable(false);
mAdapter.notifyDataSetChanged();
}
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).getImages().toString();
// Upload to PHP Script
String strUrlServer = "http://mymasterpeice.comxa.com/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) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// // prepare Status
if (strStatusID.equals("0")) {
// When update Failed
ImageList.get(position).setMessage("Failed");
ImageList.get(position).setStatusEnable(true);
mAdapter.notifyDataSetChanged();
} else {
ImageList.get(position).setMessage("Uploded");
ImageList.get(position).setStatusEnable(false);
mAdapter.notifyDataSetChanged();
}
}
/**
* Introduce a class with below attributes to hold a state of each row in
* single element
*
*/
public class MyData {
/* Image url or path of image in single row */
private String images;
/* anme of image in single row */
private String name;
/* status ID of image in single row */
private String statusID;
/* message of image in single row */
private String message;
private boolean statusEnable;
public boolean isStatusEnable() {
return statusEnable;
}
public void setStatusEnable(boolean statusEnable) {
this.statusEnable = statusEnable;
}
// Generate getters and setter
public String getImages() {
return images;
}
public void setImages(String images) {
this.images = images;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStatusID() {
return statusID;
}
public void setStatusID(String statusID) {
this.statusID = statusID;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
}
Create a list of datatype you want to use. E.g.
class YourDataType{
String name, status;
Bitmap image;
}
Then use a list to hold all the objects you have in your list.
List<YourDataType> listOfObjects;
Then create the adapter with parameters like and pass the list of objects to your adapter's constructor.
class ImagesAdapter extends BaseAdapter{
public ImagesAdapter(Context c, List<YourDataType> listOfObjects){
this.listOfObjects = listOfObjects;
}
public View getView(params, position){
YourDataType data = listOfObjects.get(position);
//Here you can use data to access specific object and upload the specific image and then mark this object's status to marked, then you can change the status of any listview item relevant to the object.
if(data.status == uploaded)
viewHolder.textStatus.setText("Uploaded");
}
}
And the best practice is to separate the adapter
Hope it helps. If you have any further questions comment below.
You should have a Array of Upload Status which is to be passed to the Adapter with default value is false and each time you successfully upload a file on server change the status into the Array corresponding to that position of listitem.
For example
Default Array (Assume size of list is 7)
{"false","false""false""false""false""false""false"}
Each time you successfully upload a file, change the status of Array to
{"false","true""false""false""false""false""true"}
Now you only need to update the values in this array and have to call
youradapter.notifydatasetchanged();
I have a custom Listview, where each item contains a progressbar. But when the list contains many items, and I use the scrollbar to navigate through listview, some ProgressBars disappear and facing same issue with imageview using to show status of uploaded image(s), what could be the reason and how can i resolve this ? see my code below
static class ViewHolder {
public ViewHolder(View convertView) {
// TODO Auto-generated constructor stub
}
TextView imageNameTextView;
ImageView sdCardImageView, statusImageView;
ProgressBar uploadProgressBar;
ImageButton uploadImageButton, dataImageButton, printImageButton, viewImageButton, deleteImageButton ;
}
public class ImageAdapter extends BaseAdapter
{
public ImageAdapter(Context c)
{
}
public int getCount() {
// TODO Auto-generated method stub
return ImageList.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
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;
// If this item is to be synced
if(flags.get(position)) {
startUpload(position);
// Mark as synced
flags.put(position, false);
}
/*
* If convertView is not null, we can reuse it directly, no inflation required!
* We only inflate a new View when the convertView is null.
*/
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.list_upload, null);
holder = new ViewHolder(convertView);
// Create a ViewHolder and store references to the children views
holder.imageNameTextView = (TextView) convertView.findViewById(R.id.ColImgName);
holder.sdCardImageView = (ImageView) convertView.findViewById(R.id.ColImgPath);
holder.statusImageView = (ImageView) convertView.findViewById(R.id.ColStatus);
holder.uploadProgressBar = (ProgressBar) convertView.findViewById(R.id.progressBar);
holder.uploadImageButton = (ImageButton) convertView.findViewById(R.id.btnUpload);
holder.dataImageButton = (ImageButton) convertView.findViewById(R.id.btnData);
holder.printImageButton = (ImageButton) convertView.findViewById(R.id.btnPrint);
holder.viewImageButton = (ImageButton) convertView.findViewById(R.id.btnView);
holder.deleteImageButton = (ImageButton) convertView.findViewById(R.id.btnDelete);
// The tag can be any Object, this just happens to be the ViewHolder
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
strPath = ImageList.get(position).toString();
// Get File Name
fileName = strPath.substring( strPath.lastIndexOf('_')+1, strPath.length() );
file = new File(strPath);
#SuppressWarnings("unused")
long length = file.length();
holder.imageNameTextView.setText(fileName);
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap bm = BitmapFactory.decodeFile(strPath,options);
holder.sdCardImageView.setImageBitmap(bm);
holder.statusImageView.setImageResource(R.drawable.bullet_button);
holder.uploadProgressBar.setVisibility(View.GONE);
//btnUpload
holder.uploadImageButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Upload
cd = new ConnectionDetector(getApplicationContext());
// Check for internet connection
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(UploadActivity.this, "Internet not available",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
startUpload(position);
}
});
//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.uploadProgressBar.setVisibility(View.VISIBLE);
holder.statusImageView.setImageResource(R.drawable.bullet_button);
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) {
// TODO Auto-generated method stub
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://domein/fiile.php";
try {
/** Check file on SD Card ***/
File file = new File(strSDPath);
if(!file.exists())
{
resServer = "{\"StatusID\":\"0\",\"Error\":\"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) {
View v = lstView.getChildAt(position - lstView.getFirstVisiblePosition());
// hide ProgressBar
holder.uploadProgressBar.setVisibility(View.GONE);
/*** Default Value ***/
String strStatusID = "0" ;
String strError = "" ;
try {
JSONObject c = new JSONObject(resServer);
strStatusID = c.getString("StatusID");
strError = c.getString("Message");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// using if - else if
if(strStatusID.equals("0"))
{
// already exist
holder.statusImageView.setImageResource(R.drawable.already_exist);
}
else if(strStatusID.equals("1")) {
// upload done
holder.statusImageView.setImageResource(R.drawable.upload_done);
}
else // if upload failed
{
// upload failed
holder.statusImageView.setImageResource(R.drawable.upload_failed);
}
}
}
In your ViewHolder class :
static class ViewHolder {
//...
boolean isUploading = false;
//...
}
In your getView():
public View getView(final int position, View convertView, ViewGroup parent) {
//...
if(holder.isUploading) {
holder.uploadProgressBar.setVisibility(View.VISIBLE);
} else {
holder.uploadProgressBar.setVisibility(View.GONE);
}
//...
}
In your startUpload():
public void startUpload(final int position) {
//...
holder.uploadProgressBar.setVisibility(View.VISIBLE);
holder.isUploading = true;
//...
}
Hope it will work.
So for your ProgressBar.
Whenever getView() is called, you set its visibility to GONE.
holder.uploadProgressBar.setVisibility(View.GONE);
So when starts to upload something (and sets uploadProgressBar to VISIBLE), and you scroll down (makes the list item invisible), then scroll up, getView() will be called again, and it will make your ProgressBar invisible.
So you need wrap the state in an object, or use a list to record each item state. For example, in your ImageAdapter
boolean[] uploadings = new boolean[getCount()];
Arrays.fill(uploadings, false);
in your getView()
if (uploadings[position]) {
// You need this, since you are not sure whether you are
// using newly inflated view or ConvertView
holder.uploadProgressBar.setVisibility(View.VISIBLE);
} else {
holder.uploadProgressBar.setVisibility(View.GONE);
}
And in your startUpload() method, whenever you set your prograss bar to GONE or VISIBILE, set uploadings[position] to false or true correspondingly.
And I think your ImageView probably has the same problem.
try to use a holder for your cell view
put this class at the end of your adapter
class ViewHolder {
TextView txtName,txtStatus;
ImageView imageView;
public ViewHolder(View convertview) {
txtName = (TextView) convertview.findViewById(R.id.txtName );
imageView = (ImageView) convertview.findViewById(R.id.ColImgPath);
//and so on...
}
}
replace:
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_upload, null);
}
with:
if (convertview == null) {
convertview = activity.getLayoutInflater().inflate(R.layout.list_upload, null);
holder = new ViewHolder(convertview);
convertview.setTag(holder);
} else {
holder = (ViewHolder) convertview.getTag();
}
after that do your job with holder...
holder.imageView instead of imageView and so on for all views
Check out the Listview with ProgressBar it might help you
You must set progress state in getView() method because android reuse ListView items.
to get you a clue how to resolve this:
`
public View getView(final int position, View convertView, ViewGroup parent) {
.
.
.
Int rowId = holder.id;
UploadTask task = Uploader.getTaskById(rowId);
if (task == null) {
holder.progressBar.setVisibility(View.Gone);
} else {
int progress = task.getUploadProgress();
holder.progressBar.setVisibility(View.Visible);
holder.progressBar.setProgress(progress);
}
}
p.s. You should watch this Google IO video about listviewListView
How to show exact value of list item in a dialog by using click on a Button
In above image we have first list item with name of IMG_20130626_095144.jpg and last record with name of IMG_20130626_095154.jpg
and here i have clicked on first row's upload button, but getting last row value in Dialog, please tell me where i am missing?
Activity:
// Get File Name
fileName = strPath.substring(strPath.lastIndexOf('/')+1, strPath.length());
}
Here is your code check it and reply me if we have done
public class OldUploadActivity extends Activity {
public static final String LOG_TAG = "OldUploadActivity";
private ListView lstView;
Bundle bundle;
String keytitle;
private Handler handler = new Handler();;
List <String> ImageList;
String fileName;
// created by farrukh
String selectedFileName;
TextView txtName ;
File file;
String name;
String strPath;
String strSDPath;
final private static int DIALOG_LOGIN = 1;
EditText file_name, image_name, person_name, person_email ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_uploads);
// Permission StrictMode
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
bundle = getIntent().getExtras();
keytitle = bundle.getString("KEY");
/*** Get Images from SDCard ***/
ImageList = getSD();
// ListView and imageAdapter
lstView = (ListView) findViewById(R.id.listView1);
lstView.setAdapter(new ImageAdapter(this));
}
private List <String> getSD()
{
List <String> it = new ArrayList <String>();
String string = "/mnt/sdcard/Pictures/Images/";
File f = new File (string+ keytitle+ "/");
File[] files = f.listFiles ();
for (int i = 0; i <files.length; i++)
{
File file = files[i];
it.add (file.getPath());
}
return it;
}
public class ImageAdapter extends BaseAdapter
{
private Context context;
public ImageAdapter(Context c)
{
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) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.activity_column, null);
}
// ColImgName
txtName = (TextView) convertView.findViewById(R.id.ColImgName);
Log.d("OldUploadActivity", "txtName" + txtName);
strPath = ImageList.get(position).toString();
Log.d("OldUploadActivity", "strPath" + strPath);
name = txtName.getText().toString();
// Get File Name
fileName = strPath.substring(strPath.lastIndexOf('/')+1, strPath.length());
Log.d("OldUploadActivity", "fileName" + fileName);
file = new File(strPath);
Log.d("OldUploadActivity", "file" + file);
#SuppressWarnings("unused")
long length = file.length();
txtName.setPadding(3, 0, 0, 0);
txtName.setText(fileName);
// txtName.setText(fileName + " ("+length/1024+" KB.)");
// Image Resource
ImageView imageView = (ImageView) convertView.findViewById(R.id.ColImgPath);
imageView.getLayoutParams().height = 110;
imageView.getLayoutParams().width = 110;
imageView.setPadding(10, 10, 2, 10);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
Bitmap bm = BitmapFactory.decodeFile(strPath);
imageView.setImageBitmap(bm);
// ColStatus
final TextView txtStatus = (TextView) convertView.findViewById(R.id.ColStatus);
txtStatus.setPadding(3, 0, 0, 0);
txtStatus.setText("...");
// progressBar
final ProgressBar progress = (ProgressBar) convertView.findViewById(R.id.progressBar);
progress.setVisibility(View.GONE);
progress.setPadding(0, 0, 0, 0);
// btnUpload
final Button btnUpload = (Button) convertView.findViewById(R.id.btnUpload);
btnUpload.setTextColor(Color.BLACK);
btnUpload.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("deprecation")
public void onClick(View v) {
// Upload
//Created by farrukh
selectedFileName=ImageList.get(position).toString().substring(strPath.lastIndexOf('/')+1, strPath.length());
showDialog(DIALOG_LOGIN);
}
});
// btnPrint
final Button btnPrint = (Button) convertView.findViewById(R.id.btnPrint);
btnPrint.setTextColor(Color.BLACK);
btnPrint.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Print
Toast.makeText(getApplicationContext(), "Print Image via Bluetooth", Toast.LENGTH_SHORT).show();
}
});
return convertView;
}
}
#Override
protected Dialog onCreateDialog(int id) {
AlertDialog dialogDetails = null;
switch (id) {
case DIALOG_LOGIN:
LayoutInflater inflater = LayoutInflater.from(this);
View dialogview = inflater.inflate(R.layout.dialog_layout, null);
AlertDialog.Builder dialogbuilder = new AlertDialog.Builder(this);
dialogbuilder.setTitle("Image Information");
dialogbuilder.setView(dialogview);
dialogDetails = dialogbuilder.create();
break;
}
return dialogDetails;
}
#Override
protected void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case DIALOG_LOGIN:
final AlertDialog alertDialog = (AlertDialog) dialog;
Button loginbutton = (Button) alertDialog
.findViewById(R.id.btn_login);
Button cancelbutton = (Button) alertDialog
.findViewById(R.id.btn_cancel);
file_name = (EditText) alertDialog
.findViewById(R.id.edit_file_name);
/*image_name = (EditText) alertDialog
.findViewById(R.id.edit_image_name);
person_name = (EditText) alertDialog
.findViewById(R.id.edit_person_name);
person_email = (EditText) alertDialog
.findViewById(R.id.edit_person_email);*/
file_name.setText(selectedFileName);
loginbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SaveData();
alertDialog.dismiss();
}
private boolean SaveData() {
final AlertDialog.Builder ad = new AlertDialog.Builder(OldUploadActivity.this);
ad.setTitle("Error! ");
ad.setIcon(android.R.drawable.btn_star_big_on);
ad.setPositiveButton("Close", null);
String url = "http://10.0.2.2/res/uploadImage.php";
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("sFilesName", file_name.getText().toString()));
params.add(new BasicNameValuePair("sImageName", image_name.getText().toString()));
params.add(new BasicNameValuePair("sPersonName", person_name.getText().toString()));
params.add(new BasicNameValuePair("sPersonEmail", person_email.getText().toString()));
String resultServer = getHttpPost(url,params);
Log.d("Entire string::", " " + resultServer);
/*** Default Value ***/
String strStatusID = "0";
String strError = "Cannot upload Image";
JSONObject c;
try {
c = new JSONObject(resultServer);
strStatusID = c.getString("StatusID");
strError = c.getString("Message");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Prepare Save Data
if(strStatusID.equals("0"))
{
ad.setMessage(strError);
ad.show();
}
else
{
Toast.makeText(getApplicationContext(), "Image uploaded Successfully!", Toast.LENGTH_LONG).show();
}
return true;
}
private String getHttpPost(String url,
List<NameValuePair> params) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Status OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download result..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
});
cancelbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
break;
}
}
//Upload
public void startUpload(final int position) {
Runnable runnable = new Runnable() {
public void run() {
handler.post(new Runnable() {
public void run() {
View v = lstView.getChildAt(position - lstView.getFirstVisiblePosition());
// Show ProgressBar
ProgressBar progress = (ProgressBar)v.findViewById(R.id.progressBar);
progress.setVisibility(View.VISIBLE);
// Status
TextView status = (TextView)v.findViewById(R.id.ColStatus);
status.setText("Uploading..");
new UploadFileAsync().execute(String.valueOf(position));
}
});
}
};
new Thread(runnable).start();
}
// Async Upload
public class UploadFileAsync extends AsyncTask<String, Void, Void> {
String resServer;
int position;
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
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
strSDPath = ImageList.get(position).toString();
// Upload to PHP Script
String strUrlServer = "http://10.0.2.2/res/uploadFile.php";
try {
/** Check file on SD Card ***/
File file = new File(strSDPath);
if(!file.exists())
{
resServer = "{\"StatusID\":\"0\",\"Error\":\"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) {
// Exception handling
return null;
}
return null;
}
protected void onPostExecute(Void unused) {
statusWhenFinish(position,resServer);
}
}
// when upload finish
protected void statusWhenFinish(int position, String resServer) {
View v = lstView.getChildAt(position - lstView.getFirstVisiblePosition());
// Show ProgressBar
ProgressBar progress = (ProgressBar)v.findViewById(R.id.progressBar);
progress.setVisibility(View.GONE);
// Status
TextView status = (TextView)v.findViewById(R.id.ColStatus);
/*** Default Value ***/
String strStatusID = "0";
String strMessage = "Unknow Status!";
try {
JSONObject c = new JSONObject(resServer);
strStatusID = c.getString("StatusID");
strMessage = c.getString("Message");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Prepare Status
if(strStatusID.equals("0"))
{
// When update Failed
status.setText( strMessage );
status.setTextColor(Color.RED);
// Enabled Button again
Button btnUpload = (Button) v.findViewById(R.id.btnUpload);
btnUpload.setText("Already Uploaded");
btnUpload.setTextColor(Color.RED);
btnUpload.setEnabled(true);
}
else
{
status.setText("Upload Completed.");
status.setTextColor(Color.GREEN);
}
}
You have to pass filenames for each of the data
btnUpload.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("deprecation")
public void onClick(View v) {
// Upload
Bundle bundle = new Bundle();
bundle.putString("filename", fileName );
showDialog(DIALOG_LOGIN, bundle);
}
});
And then you have to change your onPrepareDialog method to following
#Override
protected void onPrepareDialog(int id, Dialog dialog, Bundle bundle) {
super.onPrepareDialog(id, dialog, bundle);
switch(id) {
case DIALOG_LOGIN:
...
...
file_name.setText(bundle.getString("filename"));
break;
}
}