22

I want to upload an image in parse cloud server in android. But I am unable to do so.

I have tried the following code:

Drawable drawable = getResources().getDrawable(R.drawable.profilepic) ;
Bitmap bitmap = (Bitmap)(Bitmap)drawable()
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] data = stream.toByteArray();                

ParseFile imageFile = new ParseFile("image.png", data);
imageFile.saveInBackground();

Please let me know how can I do it.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
pujitav
  • 528
  • 1
  • 5
  • 17

6 Answers6

18

After struggling for several hours here is code segment works for me.

1. Data Member of activity class

Bitmap bmp;
Intent i;
Uri BmpFileName = null;

2. Starting the camera. Goal is to start camera activity and BmpFileName to store the referrence to file

String storageState = Environment.getExternalStorageState();
if (storageState.equals(Environment.MEDIA_MOUNTED)) {

String path = Environment.getExternalStorageDirectory().getName() + File.separatorChar + "Android/data/" + this.getPackageName() + "/files/" + "Doc1" + ".jpg";

File photoFile = new File(path);
try {
if (photoFile.exists() == false) { 
photoFile.getParentFile().mkdirs();
photoFile.createNewFile();
}
} 
catch (IOException e) 
{
Log.e("DocumentActivity", "Could not create file.", e);
}
Log.i("DocumentActivity", path);
BmpFileName = Uri.fromFile(photoFile);
i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, BmpFileName);
startActivityForResult(i, 0);

3. Reading contents from Camera output by overriding onActivityResult. Goal is to get bmp variable valuated.

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
try {
bmp = MediaStore.Images.Media.getBitmap( this.getContentResolver(), BmpFileName);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {

// TODO Auto-generated catch block
e.printStackTrace();
}
// Myocode to display image on UI - You can ignore
if (bmp != null)
IV.setImageBitmap(bmp);
}
}

4. On Save event

// MUST ENSURE THAT YOU INITIALIZE PARSE
Parse.initialize(mContext, "Key1", "Key2");

ParseObject pObj = null;
ParseFile pFile = null ;
pObj = new ParseObject ("Document");
pObj.put("Notes", "Some Value");

// Ensure bmp has value
if (bmp == null || BmpFileName == null) {
Log.d ("Error" , "Problem with image"
return;
}

ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(CompressFormat.PNG, 100, stream);
pFile = new ParseFile("DocImage.jpg", stream.toByteArray());
try 
{
pFile.save();
pObj.put("FileName", pFile);
pObj.save();
_mParse.DisplayMessage("Image Saved");
} 
catch (ParseException e) 
{
// TODO Auto-generated catch block
_mParse.DisplayMessage("Error in saving image");
e.printStackTrace();
}

// Finish activity in my case . you may choose some thing else finish();

So here are key difference from others

  • I called initialize parse. You may laugh about it but folks have spent hour's debugging code without realize that parse was not initialized
  • Use Save instead of SaveInBackground. I understand that it may hold the activity but that is desired behavior for me and more importantly it works

Let me know if it does not work

Namit
  • 331
  • 3
  • 7
8

Save ParseObject in the background

// ParseObject
  ParseObject pObject = new ParseObject("ExampleObject");
  pObject.put("myNumber", number);
  pObject.put("myString", name);
  pObject.saveInBackground(); // asynchronous, no callback

Save in the background with callback

pObject.saveInBackground(new SaveCallback () {
   @Override
   public void done(ParseException ex) {
    if (ex == null) {
        isSaved = true;
    } else {
        // Failed
        isSaved = false;
    }
  }
});

Variations of the save...() method include the following:

    saveAllinBackground() saves a ParseObject with or without a callback.
    saveAll(List<ParseObject> objects) saves a list of ParseObjects.
    saveAllinBackground(List<ParseObject> objects) saves a list of ParseObjects in the 
    background.
    saveEventually() lets you save a data object to the server at some point in the future; use 
    this method if the Parse cloud is not currently accessible.

Once a ParseObject has been successfully saved on the Cloud, it is assigned a unique Object-ID. This Object-ID is very important as it uniquely identifies that ParseObject instance. You would use the Object-ID, for example, to determine if the object was successfully saved on the cloud, for retrieving and refreshing a given Parse object instance, and for deleting a particular ParseObject.

I hope you will solve your problem..

Make it Simple
  • 1,832
  • 5
  • 32
  • 57
  • hey thanks for the reply,but i want to upload an image,should i consider that image as a file?how to approach for it? – pujitav Apr 30 '13 at 06:08
  • 2
    Yes, treat the image as a file. but the Parse guide at parse.com says **It's important that you give a name to the file that has a file extension. This lets Parse figure out the file type and handle it accordingly. So, if you're storing PNG images, make sure your filename ends with .png.** – Abdullah Shoaib Apr 30 '13 at 06:14
  • This doesn't even answer the question. – grantespo Jun 04 '17 at 23:25
1
Parse.initialize(this, "applicationId", "clientKey");

     byte[] data = "Sample".getBytes();    //data of your image file comes here

     final ParseFile file = new ParseFile(data);
     try {
        file.save();
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
     if (file.isDirty()){
                     //exception or error message etc 
     }
     else{

         try {
            ParseUser.logIn("username", "password");    //skip this if already logged in
        } catch (ParseException e2) {
            e2.printStackTrace();
        }
         ParseObject userDisplayImage = new ParseObject("UserDisplayImage");
            user = ParseUser.getCurrentUser();
            userDisplayImage.put("user", user);     //The logged in User
            userDisplayImage.put("displayImage", file); //The image saved previously
            try {
                userDisplayImage.save();      //image and user object saved in a new table. Check data browser
            } catch (ParseException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

         //See how to retrieve

         ParseQuery query = new ParseQuery("UserDisplayImage");
         query.whereEqualTo("user", user);
         try {
            parseObject = query.getFirst();
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
         ParseFile imageFile = null;
          imageFile = parseObject.getParseFile("displayImage");
          try {
            byte[] imgData = imageFile.getData(); //your image data!!
        } catch (ParseException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

     }
Abdullah Shoaib
  • 2,065
  • 2
  • 18
  • 26
  • hey it has not worked for me..,i want to save image as file,what can i do with the url..i will capture the image from camera and will assign to imageview in signup process,for each user the image is different.,so how can i upload the image for the different users? – pujitav Apr 30 '13 at 07:08
  • hey thanks..will try this,can u let me know where the image is saved bcoz we didnt create any column for it right – pujitav Apr 30 '13 at 10:47
  • Yes. There is no column for file neither it should exist in the data browser but still the file is available for download using the relationship table in the data browser.( Table/Class UserDisplayImage in the above code). Other than that, the file can be accessed directly from it's URL too. – Abdullah Shoaib Apr 30 '13 at 11:44
  • can i save the image for the same class,lets say when i'm signing up it is creating on class(User) and saving the field values like wise when i'm saving the image we are creating one more class like UserDisplayImage,instead of creating another can i use the same class using parse object?? – pujitav May 02 '13 at 09:38
  • Yes you can save in the same User class when creating that user or even after the user has been created: `user = ParseUser.getCurrentUser(); user.put("displayImage", file); user.save(); //handle exception here` – Abdullah Shoaib May 02 '13 at 15:20
1

Use it like this

 //Convert Bitmap to Byte array --For Saving Image to Parse Db. */

 Bitmap profileImage= "your bitmap";

 ByteArrayOutputStream blob = new ByteArrayOutputStream();

 profileImage.compress(CompressFormat.PNG, 0 /* ignored for PNG */,blob);

 imgArray = blob.toByteArray();

 //Assign Byte array to ParseFile
 parseImagefile = new ParseFile("profile_pic.png", imgArray);

 parseUser.getCurrentUser().put("columname in parse db", parseImagefile);
 parseUser.getCurrentUser().saveInBackground();

I hope this will help you..

Fattie
  • 27,874
  • 70
  • 431
  • 719
KP_
  • 1,854
  • 25
  • 43
1

Simple code of Imageupload and retriving using Glide to parse.

Image Upload

destination_profile is File object of you want to upload image path.

    ParseUser currentUser = ParseUser.getCurrentUser();
    if (destination_profile != null) {
            Glide.with(getActivity()).load(destination_profile.getAbsolutePath()).asBitmap().toBytes().centerCrop().into(new SimpleTarget<byte[]>() {
                @Override
                public void onResourceReady(byte[] resource, GlideAnimation<? super byte[]> glideAnimation) {


                    final ParseFile parseFile = new ParseFile(destination_profile.getName(), resource);
                    parseFile.saveInBackground(new SaveCallback() {
                        @Override
                        public void done(ParseException e) {
                            currentUser.put("picture", parseFile);
                            currentUser.saveInBackground(new SaveCallback() {
                                @Override
                                public void done(ParseException e) {
                                    showToast("Profile image upload success");
                                }
                            });
                        }
                    });


                }
            });
        }

Image Retriving

img_userProfilePicture_bg is boject of ImageView where you want to set image.

    ParseUser currentUser = ParseUser.getCurrentUser();
    if (currentUser.has("picture")) {
        ParseFile imageFile = (ParseFile) currentUser.get("picture");
        imageFile.getDataInBackground(new GetDataCallback() {
            public void done(final byte[] data, ParseException e) {
                if (e == null) {

                    Glide.with(getActivity()).load(data).centerCrop().into(img_userProfilePicture_bg);

                } else {
                    // something went wrong
                }
            }
        });
    }
Amit Prajapati
  • 13,525
  • 8
  • 62
  • 84
0

Assuming you have your bitmap file bitmap.

    ParseObject object = new ParseObject("NameOfClass");

    ByteArrayOutputStream stream = new ByteArrayOutputStream();

    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
    byte[] scaledData = stream.toByteArray();

    ParseFile image = new ParseFile("image.jpeg",scaledData);
    image.saveInBackground(new SaveCallback() {
        @Override
        public void done(ParseException e) {
            if (e==null)
                //Image has been saved as a parse file.
            else
                //Failed to save the image as parse file.
        }
    });

    object.put("images",image);
    object.saveInBackground(new SaveCallback() {
        @Override
        public void done(ParseException e) {
            if (e==null)
                //Image has been successfuly uploaded to Parse Server.
            else
                //Error Occured.
        }
    });

It is important to convert the Bitmap into byte[] and then uploading the Parse File before associating it with the Parse Object.

Utkarsh Gupta
  • 111
  • 1
  • 2
  • 8