53
    int globalPosition ;

    ..............

    buttonAllData.setOnClickListener(new OnClickListener() { 

    @Override 
    public void onClick(View arg0) { 
    // TODO Auto-generated method stub 
        new UploadBulkData(globalPosition).execute();

        } 
    });

   ........

   class UploadBulkData extends AsyncTask<String, String, String> {
    private ProgressDialog pDialog;
    int dataPosition;

    public UploadBulkData(int position){
     this.dataPosition = position;
    }

    @Override
    protected void onPreExecute() {
      super.onPreExecute();
      pDialog = new ProgressDialog(UploadActivity.this);
      pDialog.setMessage("Uploading...");
      pDialog.setIndeterminate(false);
      pDialog.setCancelable(true);
      pDialog.show();
    }

    @Override
    protected String doInBackground(String... args) {
       .......
       String url = "http://web/uploadBulk.php";
       List<NameValuePair> params = new ArrayList<NameValuePair>();
       params.add(new BasicNameValuePair("UserData", st));

       String resultServer = getHttpPost(url,params); 
       Log.d("Entire string::", " " + resultServer); 

       /*** Default Value ***/
       strStatusID = "0"; 
       strError = ""; 

      JSONObject jsonObject;
      try { 
        jsonObject = new JSONObject(resultServer); 
        strStatusID = jsonObject.getString("StatusID"); 
        strError = jsonObject.getString("Message"); 
      } catch (JSONException e) { 
        e.printStackTrace();
      } 
   }

   return null;

   }

   protected void onPostExecute(String file_url) {

         pDialog.dismiss();
         fileNameDB=ImageList.get(globalPosition).toString().substring
            (strPath.lastIndexOf('/')+1, strPath.length());

         if(strStatusID.equals("1"))
           {
             Toast.makeText(UploadActivity.this, "Data Uploaded Successfully", Toast.LENGTH_SHORT).show();

            long saveImge = myDbbv.InsertData(fileNameDB);
            Log.d("fileNameDB:UP", String.valueOf(saveImge));
           }
           else
           {   
             Toast.makeText(UploadActivity.this, "Unable to upload Data", Toast.LENGTH_SHORT).show();                                   
           }

           if (file_url != null){
               Toast.makeText(UploadActivity.this, file_url, Toast.LENGTH_LONG).show();
            }
       }
}

And in getView i am using something like this:

public View getView(final int position, View convertView, ViewGroup parent) {

holder.dataImageView.setImageResource(R.drawable.bullet_button);

try {
    // check data exist or not
    boolean strDataExistU = myDbbv.Exists(fileNameDB);
    if(strDataExistU)
    {
      holder.dataImageView.setImageResource(R.drawable.online);
    }
    else
    {
      boolean strDataExist = myDb.Exists(fileNameDB);
      if(strDataExist)
      {
        holder.dataImageView.setImageResource(R.drawable.local);
      }
      else
      {
      holder.dataImageView.setImageResource(R.drawable.default);
      }
   }                    

   } catch (Exception e) {

   }

  }

As you can see in getView(...) method, I am using three different kind of drawables (namely:- online, local, default)

Where online shows data has been uploaded to online server, local shows this has been added to local database and default..(neither uploaded to server nor stored to local database)

Problem:

Whenever I am doing bulk upload, getting online drawable only for the last row item in a list, whereas I have uploaded whole list item data to server

I just want to show online drawable for all the list items, those I have uploaded to server, else my code works just fine...

Almost complete code:

public class UploadActivity extends Activity  { 

        int globalPosition ;

        @Override
        public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);      

        setContentView(R.layout.activity_upload);

        ImageButton buttonAllData = (ImageButton) findViewById(R.id.btnMenus); 
        buttonAllData.setOnClickListener(new OnClickListener() { 

        @Override 
        public void onClick(View arg0) { 
        // TODO Auto-generated method stub 

            new UploadBulkData(globalPosition).execute();

            } 
        });

        /*** Get Images from SDCard ***/
        ImageList = getSD();

        // ListView and imageAdapter
        lstView = (ListView) findViewById(R.id.listView1);
        lstView.setAdapter(new ImageAdapter(this));

        totalItems = ""+ lstView.getAdapter().getCount();
        }

        public static List <String> getSD()
        {
            List <String> it = new ArrayList <String>();
            String string = "/mnt/sdcard/Pictures/Joseph/";
            f = new File (string+ CameraLauncherActivity.folder+ "/");
            files = f.listFiles ();

            /***
             * to show last taken image on top using lastModified
             * to sort data
             * to refresh data after (remove or update)
             */
            Arrays.sort(files, new Comparator<Object>()
            {
                public int compare(Object o1, Object o2) {

                    if (((File)o1).lastModified() > ((File)o2).lastModified()) {
                        return -1;
                    } else if (((File)o1).lastModified() < ((File)o2).lastModified()) {
                        return +1;
                    } else {
                        return 0;
                    }
                }
            });
            // <<<<<<<<< END >>>>>>>>>>>

            for (int i = 0; i < files.length; i++)
            {
            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 imageNameTextView;
            ImageView sdCardImageView, statusImageView, dataImageView;
            ProgressBar uploadProgressBar;
            ImageButton uploadImageButton, dataImageButton;            
            boolean isUploading = false;           
        }  

         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.dataImageView = (ImageView) convertView.findViewById(R.id.dataExist);

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

                fileName=ImageList.get(position).toString().substring
            (strPath.lastIndexOf('_')+1, strPath.length());
        fileNameDB=ImageList.get(position).toString().substring
            (strPath.lastIndexOf('/')+1, strPath.length());

                final BitmapFactory.Options options = new BitmapFactory.Options();

                options.inSampleSize = 8;

                Bitmap bm = BitmapFactory.decodeFile(strPath,options);
                holder.sdCardImageView.setImageBitmap(bm);       

                if(holder.isUploading) {                    
                    holder.uploadProgressBar.setVisibility(View.VISIBLE);
                } else {
                    holder.uploadProgressBar.setVisibility(View.GONE);
                }                                                                                       
                holder.dataImageView.setImageResource(R.drawable.bullet_button);

                try {
                    // check data exist or not
                    boolean strDataExistU = myDbbv.Exists(fileNameDB);
                    if(strDataExistU)
                    {
                        holder.dataImageView.setImageResource(R.drawable.online);
                    }
                    else
                    {
                        // check data exist or not
                        boolean strDataExist = myDb.Exists(fileNameDB);
                        if(strDataExist)
                        {
                            holder.dataImageView.setImageResource(R.drawable.database);
                        }
                        else
                        {
                            holder.dataImageView.setImageResource(R.drawable.default);
                        }
                    }                   

                } catch (Exception e) {
                    // TODO: handle exception
                }

                fileName = ImageList.get(position).toString().substring
                        (strPath.lastIndexOf('/')+1, strPath.length());

                try {
                    boolean strExist = myDbb.Exists(fileName);
                    if(strExist)
                    {
                        holder.statusImageView.setImageResource(R.drawable.onl);
                    }
                    else
                    {
                        holder.statusImageView.setImageResource(R.drawable.bullet_button);
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                }


                // btnData
                holder.dataImageButton.setOnClickListener(new View.OnClickListener() {
                @SuppressWarnings("deprecation")
                public void onClick(View v) {
                    // Print
                    globalPosition = position;
                    fileName=ImageList.get(position).toString().substring
                            (strPath.lastIndexOf('_')+1, strPath.length());
                    fileNameDB=ImageList.get(position).toString().substring
                            (strPath.lastIndexOf('/')+1, strPath.length());
                    showDialog(DIALOG_LOGIN);
                    }
                });     

        return convertView;

            }   
        }


                        class UploadData extends AsyncTask<String, String, String> {
                            private ProgressDialog pDialog;

                             /**
                            * Before starting background thread Show Progress Dialog
                            * */

                           @Override
                           protected void onPreExecute() {
                               super.onPreExecute();
                               pDialog = new ProgressDialog(UploadActivity.this);
                               pDialog.setMessage("Uploading...");
                               pDialog.setIndeterminate(false);
                               pDialog.setCancelable(true);
                               pDialog.show();                     
                           }

                            @Override
                            protected String doInBackground(String... args) {

                                String url = "http://web/uploadData.php";                                       

                                List<NameValuePair> params = new ArrayList<NameValuePair>();

                                params.add(new BasicNameValuePair("sImageName", fileNameDB));
                                Log.d("sImageName::", fileNameDB);


                                String resultServer  = getHttpPost(url,params);
                                Log.d("Entire string::", " " + resultServer);

                                /*** Default Value ***/
                                strStatusID = "0";
                                strError = "";

                                JSONObject c;
                                try {
                                    c = new JSONObject(resultServer);
                                    strStatusID = c.getString("StatusID");
                                    strError = c.getString("Error");
                                } catch (JSONException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }                                          

                               return null;

                            }
                            /**
                            * After completing background task Dismiss the progress dialog
                            * **/
                           protected void onPostExecute(String file_url) {
                               // dismiss the dialog once product deleted
                               pDialog.dismiss();

                               try {

                                  fileName=ImageList.get(globalPosition).toString().substring
                                            (strPath.lastIndexOf('_')+1, strPath.length());
                                    fileNameDB=ImageList.get(globalPosition).toString().substring
                                            (strPath.lastIndexOf('/')+1, strPath.length());

                                    // prepare save data
                                    if(strStatusID.equals("0"))
                                    {
                                        Toast.makeText(getApplicationContext(), "Unable to upload Data",
                                                Toast.LENGTH_LONG).show();
                                    }
                                    else if (strStatusID.equals("1"))
                                    {
                                        Toast.makeText(getApplicationContext(), "Data Uploaded Successfully!", 
                                                Toast.LENGTH_SHORT).show();
                                        // Save Data
                                        long saveImge = myDbbv.InsertData(fileNameDB);
                                        Log.d("fileNameDB:UP", String.valueOf(saveImge));
                                    } else {
                                        Toast.makeText(getApplicationContext(), "Unable to upload Data",
                                                Toast.LENGTH_LONG).show();
                                    }

                              } catch (Exception e) {
                                    // TODO: handle exception
                                }


                           if (file_url != null){
                                Toast.makeText(UploadActivity.this, file_url, Toast.LENGTH_LONG).show();
                           }

                       }

                    }


                }); 

                cancelButton.setOnClickListener(new View.OnClickListener(){ 
                    @Override
                        public void onClick(View v) {                           
                        alertDialog.dismiss();
                        }
                });

                closeButton.setOnClickListener(new View.OnClickListener(){ 
                    @Override
                        public void onClick(View v) {                           
                        alertDialog.dismiss();
                        }
                });
            }
        }       


                        class UploadBulkData extends AsyncTask<String, String, String> {
                            private ProgressDialog pDialog;

                            int dataPosition;

                            //constructor to pass position of row, on which button was clicked to class
                            public UploadBulkData(int position){
                                this.dataPosition = position;
                            }

                             /**
                            * Before starting background thread Show Progress Dialog
                            * */

                           @Override
                           protected void onPreExecute() {
                               super.onPreExecute();
                               pDialog = new ProgressDialog(UploadActivity.this);
                               pDialog.setMessage("Uploading...");
                               pDialog.setIndeterminate(false);
                               pDialog.setCancelable(true);
                               pDialog.show();
                           }

                            @Override
                            protected String doInBackground(String... args) {

                                String url = "http://web/uploadBulk.php";

                                List<NameValuePair> params = new ArrayList<NameValuePair>();
                                params.add(new BasicNameValuePair("EventData", st));

                                String resultServer = getHttpPost(url,params); 
                                Log.d("Entire string::", " " + resultServer); 

                                /*** Default Value ***/
                                strStatusID = "0"; 
                                strError = ""; 

                                JSONObject jsonObject;
                                try { 
                                        jsonObject = new JSONObject(resultServer); 
                                        strStatusID = jsonObject.getString("StatusID"); 
                                        strError = jsonObject.getString("Message"); 
                                        } catch (JSONException e) { 
                                        // TODO Auto-generated catch block 
                                        e.printStackTrace();
                                    } 
                                }

                               return null;

                            }
                            /**
                            * After completing background task Dismiss the progress dialog
                            * **/
                           protected void onPostExecute(String file_url) {
                               // dismiss the dialog once product deleted
                               pDialog.dismiss();

                                // Prepare Save Data
                                if(strStatusID.equals("1"))
                                {
                                    Toast.makeText(UploadActivity.this, "Data Uploaded Successfully", Toast.LENGTH_SHORT).show();
                                    fileNameDB=ImageList.get(dataPosition).toString().substring
                                            (strPath.lastIndexOf('/')+1, strPath.length());

                                    // Save Data
                                    long saveImge = myDbbv.InsertData(fileNameDB);
                                    Log.d("fileNameDB:UP", String.valueOf(saveImge));
                                }
                                else
                                {
                                    Toast.makeText(UploadActivity.this, "Unable to upload Data", Toast.LENGTH_SHORT).show();                                    
                                }

                               if (file_url != null){
                                    Toast.makeText(UploadActivity.this, file_url, Toast.LENGTH_LONG).show();
                               }

                           }

            }
khelwood
  • 55,782
  • 14
  • 81
  • 108
Sun
  • 6,768
  • 25
  • 76
  • 131
  • in `onPostExecute` u suppose to use `dataPosition` instead of `globalPosition` – Bharatesh Apr 18 '15 at 11:27
  • i have tried with dataPosition as well, but getting same result – Sun Apr 20 '15 at 05:04
  • You should pass a `Holder` object to your `AsycnTask`. – Piyush Apr 21 '15 at 09:45
  • `public UploadBulkData(YourHolderClass holder , int position){` – Piyush Apr 21 '15 at 09:49
  • Where u r assigning globalPosition? in your adapter where u r getting value for fileNameDB? are you performing click for buttonAllData programmatically, as i see globalPosition is always the same inside your buttonAllData click listener, there is no loop – Rajen Raiyarela Apr 21 '15 at 09:53
  • 2
    possible duplicate of [ListView Data got cleared on scrolling](http://stackoverflow.com/questions/29257838/listview-data-got-cleared-on-scrolling) –  Apr 28 '15 at 06:37
  • Do not store anything other than views in your viewholder class I mean `boolean isUploading = false;` – mmlooloo Apr 30 '15 at 16:23
  • Use different bitmap objects for all the images .. .as per your code they are being overridden and the values of only last are uploaded. Check [this](http://stackoverflow.com/questions/29715351/listview-holder-small-issue-with-dynamic-data#comment47946104_29715351) – Maveňツ May 01 '15 at 13:12
  • public Object getItem(int position) { return position; } public long getItemId(int position) { return position; }.You are returning position int variable instead of a List Object.And also why you are wastely double checking.In the second check data exist or not.Just use the first strDataExistU – ShihabSoft May 02 '15 at 04:17
  • 2
    You code is having lots of errors you ie(in getView() you have initialized a obejct to null "holder=null" without type i know it is ViewHolder and what is flag? and where it is from?) if you provide the correct code i will try to find the issue. – Vigneshwaran Murugesan May 07 '15 at 05:37

3 Answers3

1

There could be multiple customizable ways to achieve this. One of them is already answered. Correct me if I'm wrong about your requirement, you need to be notified when the list reached its last item. Afterwards, you're going to perform an operation with the last item index.

[UPDATE]

For this solution: You have to migrate to Recycler View as it's more flexible, fast and optimised for bulk data.

int findFirstVisibleItemPosition();
int findFirstCompletelyVisibleItemPosition();
int findLastVisibleItemPosition(); // This function could be the one you're looking for.
int findLastCompletelyVisibleItemPosition();

Usage:

// In Java

GridLayoutManager layoutManager = ((GridLayoutManager)mRecyclerView.getLayoutManager());
int firstVisiblePosition = layoutManager.findFirstVisibleItemPosition();

Reference: https://stackoverflow.com/a/25053500/16176653

Puneet Verma
  • 101
  • 5
0

Issue is in holder.dataImageButton.setOnClickListener method block, position value you are assigning to globalPosition (globalPosition = position;) is the one passed to getView method (getView is called every time view is recycled). So you should set position to holder.dataImageButton tag and retrieve from it inside your setOnClickListener method block.

So set the position in holder.dataImageButton tag

holder.dataImageButton.setTag(position);

after your code line

holder.dataImageView.setImageResource(R.drawable.bullet_button);

and modify your setOnClickListener method as

holder.dataImageButton.setOnClickListener(new View.OnClickListener() {
    @SuppressWarnings("deprecation")
    public void onClick(View v) {
        // Print
        globalPosition = (Integer)v.getTag(); //modified
        fileName=ImageList.get(position).toString().substring
                            (strPath.lastIndexOf('_')+1, strPath.length());
        fileNameDB=ImageList.get(position).toString().substring
                            (strPath.lastIndexOf('/')+1, strPath.length());
        showDialog(DIALOG_LOGIN);
    }
});
Rajen Raiyarela
  • 5,526
  • 4
  • 21
  • 41
  • but i am facing issue, when i am doing bulk upload only - check UploadBulkData – Sun Apr 22 '15 at 04:58
  • While calling UploadBulkData you are passing globalPosition value i.e. a single value. Either you have to create a loop in buttonAllData.setOnClickListener method block, or else you can pass complete array of files to be uploaded to UploadBulkData asynctask and create a loop inside doInBackground method. – Rajen Raiyarela Apr 22 '15 at 06:53
  • i have tried can show me the way.. this is the only thing i have not achieved in my app, and spent around 4 days with this.. but i hope you can resolve my issue within few minutes, friend i have given my best.. help me to get it done – Sun Apr 22 '15 at 11:35
  • Still facing same issue – Sun Apr 28 '15 at 10:24
0

It appears that in both UploadData and UploadBulkData the exact same code is used for updating the uploaded database: myDbbv.InsertData(fileNameDB). This would have the effect of only marking the last file of UploadBulkData as being uploaded, which is consistent with the problematic behavior you are seeing.

Try updating myDbbv for each file being uploaded in UploadData and see if it helps.

Kai
  • 15,284
  • 6
  • 51
  • 82