2

I want to implement a feature that if a user clicks the button backup the app automatically take all images from gallery and then send it to a server. At the moment what I have done is user is clicking on the button then he selects the image and then I am sending photo to a server but what I want to do is, I want to take all the images stored in memory card or phone.

How can I do this ?

Here is my working code of picking a photo and then sending to server

MainActivity

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) {
                // To open up a gallery browser
                  Intent intent = new Intent();
                  intent.setType("image/*");
                  intent.setAction(Intent.ACTION_GET_CONTENT);
                  startActivityForResult(Intent.createChooser(intent, "Select Picture"),1);
                }});



    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
            // currImageURI is the global variable I’m using to hold the content:
                currImageURI = data.getData();
                System.out.println("Current image Path is ----->" +                          getRealPathFromURI(currImageURI));
                HttpUploader uploader = new HttpUploader();

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

  //Convert the image URI to the direct file system path of the image file
    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);
    }

}

HttpUploader

    public  class HttpUploader extends AsyncTask<String, Void, String> {

    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("httppath");
                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;
    }
}
Lucifer
  • 29,392
  • 25
  • 90
  • 143
hellosheikh
  • 2,929
  • 8
  • 49
  • 115
  • @Snicolas yeah you are right. i am getting memory leak issue because of that. i am new to android can you please recommend me some good file uploading tutorial – hellosheikh Feb 20 '14 at 18:50
  • Follow the thread I mentionned, I also mention a solution. There is no good tutorial but some libs can help. Go to RoboSpice README page on github, at the bottom you can find most of them. – Snicolas Feb 21 '14 at 08:34
  • @hellosheikh did u get output?i am struck –  Dec 18 '14 at 09:42
  • @user4078066 yes.. sorry do you need still help ? – hellosheikh Jan 06 '15 at 12:59

1 Answers1

1

You can use following method to get all files list in an ArrayList.

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

Then you can run a for loop which upload file one by one.

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);       // a pause of 1 sec befor uploading next image.
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
}
Lucifer
  • 29,392
  • 25
  • 90
  • 143
  • thanks for your answer .. i was wondering that shouldn't i have to removed my method "getRealPathFromURI" because you have written the code of this method into your method. and i dont know why you are calling my method .. and also i want to know i dont want to choose the photos – hellosheikh Feb 20 '14 at 12:42
  • which of your method I am calling ? – Lucifer Feb 20 '14 at 12:43
  • here in the try block uploader.execute(getRealPathFromURI(fileName.get(i))).get(); – hellosheikh Feb 20 '14 at 12:49
  • Yes I use your code to make simplify for your understanding. The actual logic for your requirement is to get a file's path and pass it to uploader. Here my method returns an arraylist that contains path of all the images from a device. And then I write a for loop to demonstrate it. – Lucifer Feb 20 '14 at 12:51
  • @Kedarnath i need your help, will you help me? check this: http://stackoverflow.com/questions/24731838/upload-multiple-images-but-one-by-one – Sun Jul 14 '14 at 09:32