Custom Listview scroll hiding progressbar process and ImageView - android

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

Related

lstView.getFirstVisiblePosition() with errors

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.

How to Save and Restore the Scroll Position and State of ListView

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();

Upload All List Items using single AsyncTask

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/

Image in listview ordering is not correct and download again

Here is how I set up the list view and how I get the image by downloading it.
Some variable explanation :
The PostItem is the model object that contain the data for a listview item
The ImageLoader is the async task class to download the image by getting the image url from PostItem
The problem are , the ordering of the image in the listview is incorrect , for example, the image should appear in 1st is appear in both 1st , 4th, and if I scroll , the display pattern change as well.
Also, I find the image are download again if I scroll, even I have check the imageView whether has drawable
Thanks for helping.
====================================================
Here is how I generate the listview:
static class ViewHolderItem {
TextView name;
TextView date;
ImageView img;
TextView msg;
TextView count;
ImageView likeBtn;
ImageView commentBtn;
ImageView shareBtn;
}
private class MyPostAdapter extends ArrayAdapter<PostItem> {
#Override
public boolean isEnabled(int position) {
return false;
}
public MyPostAdapter(Context context, int resource, List<PostItem> items) {
super(context, resource, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolderItem viewHolder;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.post_item, parent, false);
viewHolder = new ViewHolderItem();
viewHolder.name = (TextView) v.findViewById(R.id.postName);
viewHolder.date = (TextView) v.findViewById(R.id.postDate);
viewHolder.img = (ImageView) v.findViewById(R.id.postImg);
viewHolder.msg = (TextView) v.findViewById(R.id.postMsg);
viewHolder.count = (TextView) v.findViewById(R.id.count);
viewHolder.likeBtn = (ImageView) v.findViewById(R.id.likeBtn);
viewHolder.commentBtn = (ImageView) v.findViewById(R.id.commentBtn);
viewHolder.shareBtn = (ImageView) v.findViewById(R.id.shareBtn);
v.setTag(viewHolder);
} else {
viewHolder = (ViewHolderItem) convertView.getTag();
}
final PostItem post = getItem(position);
if (post != null) {
viewHolder.name.setText(post.name);
try {
c.setTime(sdf.parse(post.createDate));
} catch (ParseException e) {
e.printStackTrace();
}
relative_date = DateUtils.getRelativeDateTimeString (ctx, c.getTimeInMillis() , DateUtils.MINUTE_IN_MILLIS,DateUtils.WEEK_IN_MILLIS, 0).toString();
viewHolder.date.setText(relative_date);
viewHolder.msg.setText(post.txtMsg);
viewHolder.count.setText(post.likeCount + " " + getString(R.string.pro_like) + " " + post.commentCount + " " + getString(R.string.reply));
if (post.isLike) {
viewHolder.likeBtn.setImageResource(R.drawable.like);
} else {
viewHolder.likeBtn.setImageResource(R.drawable.before_like);
}
if (!post.imageURL.equals("null") && viewHolder.img.getDrawable() == null ) {
new ImageLoader(ctx).execute(viewHolder.img,Constant.comment_imageFolder + post.imageURL);
} else {
viewHolder.img.setImageDrawable(null);
}
viewHolder.likeBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new APIManager("like", ctx, Constant.likeAPI + "/"
+ post.commentID + "/" + userID, jsonListener,
getResources().getString(R.string.update_data));
}
});
viewHolder.commentBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<PostItem> filterReplyList = new ArrayList<PostItem>();
Intent i = new Intent(ctx, ReplyActivity.class);
i.putExtra("commentID", post.commentID);
// get reply list
for (PostItem reply : replyItemList) {
if (reply.postID.equals(post.commentID)
|| reply.commentID.equals(post.commentID)) {
filterReplyList.add(reply);
}
}
i.putExtra("replyItemList", filterReplyList);
startActivityForResult(i, 0);
}
});
viewHolder.shareBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
String data = "date: " + post.createDate + "\nmsg:" + post.txtMsg;
sendIntent.putExtra(Intent.EXTRA_TEXT, data);
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
});
}
return v;
}
}
And Here is the imageloader, take the imageview, url as input and put the bitmap in the imageview
public class ImageLoader extends AsyncTask<Object, Void, Bitmap> {
private static String TAG = "ImageLoader";
private InputStream input;
private ImageView view;
private ProgressBar loadingIcon;
private ListView myListView;
private String imageURL;
private Context ctx;
public ImageLoader(Context _ctx) {
ctx = _ctx;
}
#Override
protected Bitmap doInBackground(Object... params) {
try {
view = (ImageView) params[0];
// handle Chinese characters in file name
// String[] imgUrlArray = ((String) params[1]).split("/");
// String fileName = imgUrlArray[imgUrlArray.length - 1];
// String newfileName = URLEncoder.encode(fileName, "utf-8");
// imageURL = ((String) params[1]).replace(fileName, newfileName);
imageURL = ((String) params[1]);
if (params.length > 2 && (ProgressBar) params[2] != null)
loadingIcon = (ProgressBar) params[2];
URL url = new URL(imageURL);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
input = connection.getInputStream();
final BitmapFactory.Options options = new BitmapFactory.Options();
BufferedInputStream bis = new BufferedInputStream(input, 4*1024);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte)current);
}
byte[] imageData = baf.toByteArray();
BitmapFactory.decodeByteArray(imageData, 0, imageData.length, options);
options.inJustDecodeBounds = true;
options.inSampleSize = 2;
options.inJustDecodeBounds = false;
return BitmapFactory.decodeByteArray(imageData, 0, imageData.length, options);
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
try {
if (input != null)
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
protected void onPostExecute(Bitmap result) {
if (result != null && view != null) {
if (loadingIcon != null)
loadingIcon.setVisibility(View.GONE);
view.setVisibility(View.VISIBLE);
view.setImageBitmap(result);
}
}
Updated code (implement volley library):
static class ViewHolderItem {
TextView name;
TextView date;
NetworkImageView img;
TextView msg;
TextView count;
ImageView likeBtn;
ImageView commentBtn;
ImageView shareBtn;
}
private class MyPostAdapter extends ArrayAdapter<PostItem> {
#Override
public boolean isEnabled(int position) {
return false;
}
public MyPostAdapter(Context context, int resource, List<PostItem> items) {
super(context, resource, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolderItem viewHolder;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.post_item, parent, false);
viewHolder = new ViewHolderItem();
viewHolder.name = (TextView) v.findViewById(R.id.postName);
viewHolder.date = (TextView) v.findViewById(R.id.postDate);
viewHolder.img = (NetworkImageView) v.findViewById(R.id.postImg);
viewHolder.msg = (TextView) v.findViewById(R.id.postMsg);
viewHolder.count = (TextView) v.findViewById(R.id.count);
viewHolder.likeBtn = (ImageView) v.findViewById(R.id.likeBtn);
viewHolder.commentBtn = (ImageView) v.findViewById(R.id.commentBtn);
viewHolder.shareBtn = (ImageView) v.findViewById(R.id.shareBtn);
v.setTag(viewHolder);
} else {
viewHolder = (ViewHolderItem) convertView.getTag();
}
final PostItem post = getItem(position);
if (post != null) {
viewHolder.name.setText(post.name);
try {
c.setTime(sdf.parse(post.createDate));
} catch (ParseException e) {
e.printStackTrace();
}
relative_date = DateUtils.getRelativeDateTimeString (ctx, c.getTimeInMillis() , DateUtils.MINUTE_IN_MILLIS,DateUtils.WEEK_IN_MILLIS, 0).toString();
viewHolder.date.setText(relative_date);
viewHolder.msg.setText(post.txtMsg);
viewHolder.count.setText(post.likeCount + " " + getString(R.string.pro_like) + " " + post.commentCount + " " + getString(R.string.reply));
if (post.isLike) {
viewHolder.likeBtn.setImageResource(R.drawable.like);
} else {
viewHolder.likeBtn.setImageResource(R.drawable.before_like);
}
if (!post.imageURL.equals("null")) {
viewHolder.img.setImageUrl(Constant.comment_imageFolder + post.imageURL, mImageLoader);
}
viewHolder.likeBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new APIManager("like", ctx, Constant.likeAPI + "/"
+ post.commentID + "/" + userID, jsonListener,
getResources().getString(R.string.update_data));
}
});
viewHolder.commentBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<PostItem> filterReplyList = new ArrayList<PostItem>();
Intent i = new Intent(ctx, ReplyActivity.class);
i.putExtra("commentID", post.commentID);
// get reply list
for (PostItem reply : replyItemList) {
if (reply.postID.equals(post.commentID)
|| reply.commentID.equals(post.commentID)) {
filterReplyList.add(reply);
}
}
i.putExtra("replyItemList", filterReplyList);
startActivityForResult(i, 0);
}
});
viewHolder.shareBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
String data = "date: " + post.createDate + "\nmsg:" + post.txtMsg;
sendIntent.putExtra(Intent.EXTRA_TEXT, data);
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
});
}
return v;
}
For the task you are trying to do I would strongly recommend you to use Volley library.
Read from here
All you need to do is as below
mRequestQueue = Volley.newRequestQueue(context);
mImageLoader = new ImageLoader(mRequestQueue, new BitmapLruCache());
mImageView.setImageUrl(BASE_URL + item.image_url, mImageLoader);
Where mImageView is com.android.volley.NetworkImageView instead of a regular ImageView.
Volley takes care of maintaining the cache and the ordering of the images.
if you scroll the listview you will get back recycled convertview, it is not null but it has incorrect imageview. convertView is a view thats created and recycled through scrolling the list. this view makes GC be called less and also save memory for you. it first assigned by your earliest items of list. after you scroll the list, for example item one of list disappears and you see item 15 the convertView of item one is passed again to you. in this time it is not null and it holdes the reference of last imageview, the imageview of item 1.
so this is your problem, you skipped assigning correct imageview to your viewHolder.img.
Ok, what should you do?
the best thing you can do is create in memory cache that holds your downloaded imageview by their URLs as keys of the cache. in getview you check the cache, if it has your URL of current imageview position read from it and set it to viewHolder.img else download the image from internet.
Golden rule is:
ALWAYS OVERWRITE VIEWHOLDER VALUES WITH VALUES OF YOUR ITEM AT INDEX POSITON THAT
GETVIEW PASSES TO YOU
how to create cache? look at Example LRU cache at
http://developer.android.com/training/volley/request.html
and if you want you can also use volley library instead.
if (!post.imageURL.equals("null") && viewHolder.img.getDrawable() == null ) {
new ImageLoader(ctx).execute(viewHolder.img,Constant.comment_imageFolder + post.imageURL);
}
I am guessing that the problem lies here. What happens when you get a recycled view which already has an image from the previous view it was used for? That explains why the image appears in both 1st and 4th position and the change in the display pattern when you scroll.
Get the point? Remove the viewHolder.img.getDrawable() == null and try. See if that helps.

Showing Last List Item value in a Dialog not exact row's which i have clicked

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;
}
}

Categories

Resources