0

i am new to android. I'm trying to display a progress bar in aysnc Task while sending photos to the server, I want to make as many progressbar as files and those progressbar will change states according to percent of byttes sent to the server. I made search, i find some questions related to this but not able to modified my code, the problem is progress bar is not displaying after the button is pressed.

here is my code

public  class HttpUploader extends AsyncTask<String, Void, String> {
    /*----------------------
    i followed some questions and here i have tried something but caused me an error

   private ProgressDialog dialog;
     private Context context;

    @Override
    protected void onPreExecute() {
        dialog = new ProgressDialog(context);
        dialog.setMessage("Uploading...");
        dialog.setIndeterminate(false);
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setProgress(0);
        dialog.show();
    }

    protected void onPostExecute(final Boolean success) {
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
    }-------------------------*/ 
    protected String doInBackground(String... path) {

        String outPut = null;

        for (String sdPath:path) {

            Bitmap bitmapOrg = BitmapFactory.decodeFile(sdPath);
            ByteArrayOutputStream bao = new ByteArrayOutputStream();

            //Resize the image
            double width = bitmapOrg.getWidth();
            double height = bitmapOrg.getHeight();
            double ratio = 400/width;
            int newheight = (int)(ratio*height);

           // System.out.println("———-width" + width);
            //System.out.println("———-height" + height);

            bitmapOrg = Bitmap.createScaledBitmap(bitmapOrg, 400, newheight, true);

            //Here you can define .PNG as well
            bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 95, bao);
            byte[] ba = bao.toByteArray();
            String ba1 = Base64.encodeToString(ba, 0);

            //System.out.println("uploading image now ——–" + ba1);

            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("image", ba1));

            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://imageuplaod");
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();                

                // print responce
                outPut = EntityUtils.toString(entity);
                Log.i("GET RESPONSE—-", outPut);

                //is = entity.getContent();
                Log.e("log_tag ******", "good connection");

                bitmapOrg.recycle();

            } catch (Exception e) {
                Log.e("log_tag ******", "Error in http connection " + e.toString());
            }
        }
        return outPut;
    }


  }

my MainActivity class

 public class MainActivity extends Activity{

    Uri currImageURI;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
      Button upload_btn = (Button) this.findViewById(R.id.uploadButton);
        upload_btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {


                upload();
                }});

    }

    public void upload(){         

                ArrayList<Uri> fileName = getFileList();
                for ( int i = 0 ; i < fileName.size() ; i++ )
                {
                HttpUploader uploader = new HttpUploader();

                try {

                      uploader.execute(getRealPathFromURI(fileName.get(i))).get();
                      Thread.sleep(1000);   
                } catch (InterruptedException e) {
                      e.printStackTrace();
                    } catch (ExecutionException e) {
                      e.printStackTrace();
                    }
                }
                TextView tv_path = (TextView) findViewById(R.id.path);
                tv_path.setText(getRealPathFromURI(currImageURI));
            }



    public String getRealPathFromURI(Uri contentUri) {

        String [] proj={MediaStore.Images.Media.DATA};
        android.database.Cursor cursor = managedQuery( contentUri,
        proj,     // Which columns to return
        null,     // WHERE clause; which rows to return (all rows)
        null,     // WHERE clause selection arguments (none)
        null);     // Order-by clause (ascending by name)
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }


    private ArrayList<Uri> getFileList()
    {
        ArrayList<Uri> fileList = new ArrayList<Uri>();
        try
        {
            String[] proj = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
            Cursor actualimagecursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, proj,
                    null, null, MediaStore.Images.Media.DEFAULT_SORT_ORDER);

            int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);

            for ( int i = 0 ; i < actualimagecursor.getCount() ; i++ )
            {
                actualimagecursor.moveToPosition(i);
                String fileName = actualimagecursor.getString(actual_image_column_index);
                fileList.add(( Uri.withAppendedPath( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, fileName )));
                //fileName = ( Uri.withAppendedPath( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, fileName ).toString() );
            }
            return fileList;
        }
        catch ( Exception e )
        {
            return null;
        }
    }

}
hellosheikh
  • 2,929
  • 8
  • 49
  • 115
  • What is the problem with this? WHAT is not working? – Merlevede Feb 21 '14 at 18:06
  • So whats your question about it?? Please be clear with your questions – Atish Agrawal Feb 21 '14 at 18:13
  • i want to show progress bar .. i have updated my question. – hellosheikh Feb 21 '14 at 18:14
  • means when all files sent to the server the progress bar finished . but at the moment the progress bar isn't displaying – hellosheikh Feb 21 '14 at 18:15
  • I updated my answer 2nd time. With the information provided I still think its the missing context. – tritop Feb 21 '14 at 19:14
  • @tritop ok i followed your advice what i did is . in my main activity class i did this HttpUploader uploader = new HttpUploader(MainActivity.this); and in my uploader class i have done this public HttpUploader(Context context) { this.context = context; } and then in preexcute method i done this pd = new ProgressDialog(this.context); but again not working ' – hellosheikh Feb 21 '14 at 19:33
  • Sorry, I had to go yesterday. If you are still struggeling with it, please update with the logcat error you are getting. – tritop Feb 22 '14 at 10:49
  • @tritop no problem . there are no errors in Logcat – hellosheikh Feb 23 '14 at 04:43

4 Answers4

0

Try running the asyncTask asynchronously. Don't use the "get()" function. Instead, get the result via the "onPostExecute" callback.

ibit
  • 316
  • 1
  • 6
0

Progressbar with progress number/percentage/whatever:

        pg = new ProgressDialog(this);
        pg.setCancelable(false);
        pg.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pg.setProgress(0);
        pg.setMax(100);
        pg.setMessage("Loading...");
        pg.show();


private class someAsyncClass extends AsyncTask<String, String, Void> {

    @Override
    protected Void doInBackground(String... params) {
            int percent = calchowfaryouare;
            publishProgress("Loading... "+percent+"%");

    }

    @Override
    protected void onProgressUpdate(String... progress) {
        super.onProgressUpdate(progress);
        if (pg != null) {
            pg.setMessage(progress[0]);
            pg.show();
        }
    }

}

Edit: Your problem is that in your commented code you used context, but in your case that would be null. You never assign something to that. If you call your async task in your Activity, just use something like MainActivity.this or getApplication().

Edit 2:

So am I getting it right that HttpUploader is in a separate file? If so, for the most easy approach, copy it in your MainActivity. Just insert it before your last '}'. Just change the 'Context context' to 'Context context = MainActivity.this'.

You could also just insert a constructor to that class and make HttpUploader nested in its own file, but that probably would be more complicated.

tritop
  • 1,655
  • 2
  • 18
  • 30
  • but the problem is i am not able to show a progress bar in the first place when i pressed the button.. do i post my MainActivity class code too ? – hellosheikh Feb 21 '14 at 18:26
  • You can edit your first post to add code. Please see my edit about your context. I think thats your problem, you used context without assigning context to it. – tritop Feb 21 '14 at 18:41
  • well i am getting an error when i write this instead of context pg = new ProgressDialog(this); let me post my MainActivity code – hellosheikh Feb 21 '14 at 18:47
  • Yes, you would probably have to use something like MainActivity.this, depending on where you do it. However, focus on that context. You need to get a valid context to call that Dialog in first place. – tritop Feb 21 '14 at 18:50
  • i have updated my question. can you please look at it and modified it . sorry to say i am not very good in android. i just recently start learning it – hellosheikh Feb 21 '14 at 18:51
0
@Override
protected void onProgressUpdate(Integer... values) {
  super.onProgressUpdate(values);
  dialog.setProgress(values[0]);
}

And in doInBackground:

publishProgress(someValue);
Artem
  • 1,566
  • 1
  • 10
  • 15
0

use this code to show progress bar in onPreExecute() of aysnc Task.

 pDialog = new ProgressDialog(XMPPChatDemoActivity.this);
        pDialog.setMessage("Downloading file. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setMax(100);
        pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pDialog.setCancelable(true);
        pDialog.show();

and in onPostExecute() method called it dissmiss as pDialog.dissmiss(); set ProgressDialog style and setCancelable() acc to you.

John smith
  • 1,781
  • 17
  • 27