Parse.com & Android: How do I save Images to my parse database so that i can use them as a profile picture

若如初见. 提交于 2020-01-23 04:08:15

问题


I am new at android as well as parse.com. I need a way in which a user can click a button to take a photo or another button to choose a photo from the gallery. Then store the image in my parse.com database so that I can manipulate it with other events in the system. So far I am able to have the user update his status and save to my parse database but I do not know how to manipulate images and ImageViews. Here is my code so far:

public class UpdateActivity extends Activity {

    protected EditText mUpdateStatus;
    protected Button mUpdateStatusButton;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update);

        //initialization of variables
        mUpdateStatus=(EditText)findViewById(R.id.updateStatusUpdate);
        mUpdateStatusButton=(Button)findViewById(R.id.updateButtonUpdate);

        //code update button click event
        mUpdateStatusButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Get current user
                ParseUser currentUser=ParseUser.getCurrentUser();//Identifies current user
                String currentUserUsername=currentUser.getUsername();//stores username in variable

                //Create new variable to store strings
                String newStatus=mUpdateStatus.getText().toString();

                //Event for an empty status
                if (newStatus.isEmpty())
                        {AlertDialog.Builder builder=new AlertDialog.Builder(UpdateActivity.this);
                        builder.setMessage("STATUS SHOULD NOT BE EMPTY.");
                        builder.setTitle("OOPS!");
                        builder.setPositiveButton("OK",new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                        AlertDialog dialog=builder.create();
                        dialog.show();}
                else{
                //Save the status in Parse.com
                ParseObject statusObject = new ParseObject("Status");//Create a new parse class
                statusObject.put("newStatus",newStatus);//Creates a new attribute and adds value from newStatus
                statusObject.put("User",currentUserUsername);//Stores username in new parse class

                //Save data and initiate callback method
                statusObject.saveInBackground(new SaveCallback() {
                    @Override
                    public void done(ParseException e) {
                        if(e==null)
                            {//Event for a Successful storage
                                Toast.makeText(UpdateActivity.this,getString(R.string.succssfulUpdate),Toast.LENGTH_LONG).show();

                                //Take user back to profile
                                Intent main = new Intent(UpdateActivity.this, ProfileActivity.class);
                                UpdateActivity.this.startActivity(main);

                            }
                        else
                            {//Event for an Unsuccessful storage
                                AlertDialog.Builder builder=new AlertDialog.Builder(UpdateActivity.this);
                                builder.setMessage(e.getMessage());
                                builder.setTitle("SORRY!");
                                builder.setPositiveButton("OK",new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                });
                                AlertDialog dialog=builder.create();
                                dialog.show();
                            }
                    }
                });}

            }
        });

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_update, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        switch(id) {
            case R.id.logoutUpdateMenu:
            {//logout the user
                ParseUser.logOut();
                //Take user back to login
                Intent intent = new Intent(UpdateActivity.this, LoginActivity.class);
                UpdateActivity.this.startActivity(intent);
                UpdateActivity.this.finish();
                Toast.makeText(getApplicationContext(), getString(R.string.logout_text), Toast.LENGTH_LONG).show();
                break;}
            }

        return super.onOptionsItemSelected(item);
    }
}

回答1:


I have no experience with parse.com but If you are able to put images(bit map) into ParseObject, you just need to call take photo or pick photo action using intent and startActivityForResult. Example:

public void onClickTakePhoto(View view) {
    dispatchTakePictureIntent();
}
public void onClickPickPhoto(View view) {
    Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(i, REQUEST_SELECT_IMAGE);
}
//Code from Android documentation
private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
    }
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if ((requestCode == REQUEST_IMAGE_CAPTURE || requestCode == REQUEST_SELECT_IMAGE) && resultCode == RESULT_OK) {
        Bundle extras = data.getExtras();
        Bitmap imageBitmap = (Bitmap) extras.get("data");
        ParseObject statusObject = new ParseObject("Status");
        //I think parse has similar support If not this
        statusObject.put("profile_photo",imageBitmap);
        statusObject.saveInBackground( new Callback(){...});

    }
}



回答2:


A complete example image upload for Parse.com with option to take a photo gallery or the camera.

Activity.class

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseObject;
import com.parse.SaveCallback;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;


public class MainActivity extends ActionBarActivity {

    private static int RESULT_LOAD_CAMERA_IMAGE = 2;
    private static int RESULT_LOAD_GALLERY_IMAGE = 1;
    private String mCurrentPhotoPath;
    private ImageView imgPhoto;
    private Button btnUploadImage;
    private File cameraImageFile;
    private TextView mTextView;


    @Override
    public void onActivityResult (int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {

            if (requestCode == RESULT_LOAD_GALLERY_IMAGE && null != data) {

                Uri selectedImage = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};

                Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                mCurrentPhotoPath = cursor.getString(columnIndex);
                cursor.close();

            } else if (requestCode == RESULT_LOAD_CAMERA_IMAGE) {
                mCurrentPhotoPath = cameraImageFile.getAbsolutePath();
            }

            File image = new File(mCurrentPhotoPath);
            BitmapFactory.Options bmOptions = new BitmapFactory.Options();
            Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(), bmOptions);
            imgPhoto.setImageBitmap(bitmap);
        }
    }

    private File createImageFile () throws IOException {

        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = timeStamp + "_";

        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        File folder = new File(storageDir.getAbsolutePath() + "/PlayIOFolder");

        if (!folder.exists()) {
            folder.mkdir();
        }

        cameraImageFile = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                folder      /* directory */
        );

        return cameraImageFile;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imgPhoto = (ImageView)findViewById(R.id.imgPhoto);
        imgPhoto.setOnClickListener(chooseImageListener);
        btnUploadImage = (Button)findViewById(R.id.btnUpload);
        btnUploadImage.setOnClickListener(uploadListener);

    }

    View.OnClickListener chooseImageListener =  new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialogChooseFrom();
        }
    };

    View.OnClickListener uploadListener =  new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            byte[] image = null;

            try {
                image = readInFile(mCurrentPhotoPath);
            }
            catch(Exception e) {
                e.printStackTrace();
            }

            // Create the ParseFile
            ParseFile file = new ParseFile("picturePath", image);
            // Upload the image into Parse Cloud
            file.saveInBackground();
            // Create a New Class called "ImageUpload" in Parse
            ParseObject imgupload = new ParseObject("Image");
            // Create a column named "ImageName" and set the string
            imgupload.put("Image", "picturePath");
            // Create a column named "ImageFile" and insert the image
            imgupload.put("ImageFile", file);
            // Create the class and the columns
            imgupload.saveInBackground(new SaveCallback() {
                @Override
                public void done(ParseException e) {

                    Toast.makeText(getBaseContext(), "Done!", Toast.LENGTH_LONG).show();
                }
            });
        }
    };

    private void dialogChooseFrom(){

        final CharSequence[] items={"From Gallery","From Camera"};

        AlertDialog.Builder chooseDialog =new AlertDialog.Builder(this);
        chooseDialog.setTitle("Pick your choice").setItems(items, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

                if(items[which].equals("From Gallery")){

                    Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(galleryIntent, RESULT_LOAD_GALLERY_IMAGE);

                } else {

                    try {

                        File photoFile = createImageFile();
                        Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photoFile));
                        startActivityForResult(cameraIntent, RESULT_LOAD_CAMERA_IMAGE);

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        chooseDialog.show();
    }

    private byte[] readInFile(String path) throws IOException {

        byte[] data = null;
        File file = new File(path);
        InputStream input_stream = new BufferedInputStream(new FileInputStream(file));
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        data = new byte[16384]; // 16K
        int bytes_read;

        while ((bytes_read = input_stream.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, bytes_read);
        }

        input_stream.close();
        return buffer.toByteArray();
    }
}

Layout

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <RelativeLayout
        android:layout_marginTop="20dp"
        android:layout_centerHorizontal="true"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:background="#ccc">

        <ImageView
            android:id="@+id/imgPhoto"
            android:layout_width="200dp"
            android:layout_height="200dp"
        />

        <TextView
            android:text="Choose a image"
            android:layout_centerHorizontal="true"
            android:layout_alignParentBottom="true"
            android:layout_margin="2dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </RelativeLayout>

    <Button
        android:id="@+id/btnUpload"
        android:text="Upload Photo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"/>

</RelativeLayout>

Android Manifest

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FLASHLIGHT" />

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />



回答3:


You need to convert your Bitmap or any Object into byte[].

And then use following code.

byte[] image= your byte array
final ParseFile files = new ParseFile(image);
files.saveInBackground(new SaveCallback() {

            @Override
            public void done(ParseException exception) {
                if (exception == null) {
                    ParseUser.getCurrentUser().put("<parse-column-name>", files);
                    ParseUser.getCurrentUser().saveInBackground();
                }
            }
        });

Hope this helps.



来源:https://stackoverflow.com/questions/28852110/parse-com-android-how-do-i-save-images-to-my-parse-database-so-that-i-can-use

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!