如何创建一个允许用户上传/更改个人资料图片的应用程序?

11
我一直在寻找一个实现应用内个人资料图片更改的例子。我希望使用Parse.com允许用户添加/更改其个人资料图片(与今天的所有社交媒体应用程序类似)。
例如:Twitter、Facebook、Instagram等,它们都允许您拍摄/上传个人资料图片,并保存该图片以便稍后查看。
我没有找到任何涵盖如何做这件事的材料,也没有其他人似乎理解我在这里试图实现什么: 从Parse下载的图像即使在退出并重新打开应用程序后仍停留在屏幕上? 到目前为止,在我的应用程序中,用户可以使用相机意图拍照或从图库上传图片,并且该图片完美地显示在ImageView中。
问题是:当我退出并重新打开应用程序时,ImageView中的图片不再显示(消失了)。
我该如何解决这个问题?
MainActivity:
     public class MainActivity extends AppCompatActivity {

        public static final int TAKE_PIC_REQUEST_CODE = 0;
        public static final int CHOOSE_PIC_REQUEST_CODE = 1;
        public static final int MEDIA_TYPE_IMAGE = 2;

        private Uri mMediaUri;

        private TextView mChangeProfilePic;
        protected ImageView mPreviewImageView;
        private Button mSaveChangesBtn;
        public ImageView mProfilePic;


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);


            FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
            fab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                            .setAction("Action", null).show();
                }
            });


            //Initialize variables
            mChangeProfilePic = (TextView) findViewById(R.id.changeProfileImageTxt);
            mPreviewImageView = (ImageView) findViewById(R.id.profileImage);
            mSaveChangesBtn = (Button) findViewById(R.id.saveProfileChangesBtn);
            mSaveChangesBtn.setEnabled(false);

            final Button mNextBtn = (Button) findViewById(R.id.NextBtn);
            mNextBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intentNext = new Intent(MainActivity.this, SecondActivity.class);
                    startActivity(intentNext);
                }
            });


            //Change profile image
            //set onlClick to TextView
            mChangeProfilePic.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(getApplicationContext(), "Change Pic Pressed", Toast.LENGTH_SHORT).show();

                    //show dialog
                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setTitle("Upload or Take a photo");
                    builder.setPositiveButton("Upload", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //upload image
                            Intent choosePictureIntent = new Intent(Intent.ACTION_GET_CONTENT);
                            choosePictureIntent.setType("image/*");
                            startActivityForResult(choosePictureIntent, CHOOSE_PIC_REQUEST_CODE);

                            mSaveChangesBtn.setEnabled(true);

                        }
                    });
                    builder.setNegativeButton("Take Photo", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //take photo
                            Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            mMediaUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
                            if (mMediaUri == null) {
                                //display error
                                Toast.makeText(getApplicationContext(), "Sorry there was an error! Try again.", Toast.LENGTH_LONG).show();

                                mSaveChangesBtn.setEnabled(false);

                            } else {
                                takePicture.putExtra(MediaStore.EXTRA_OUTPUT, mMediaUri);
                                startActivityForResult(takePicture, TAKE_PIC_REQUEST_CODE);

                                mSaveChangesBtn.setEnabled(true);
                            }
                        }
                    });
                    AlertDialog dialog = builder.create();
                    dialog.show();
                }
            });//End change profile image onClick Listener


            //Save profile changes button
            //Also uploads content to parse and pulls it back same time
            mSaveChangesBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    //create parse object for image to upload
                    final ParseObject imageUpload = new ParseObject("ImageUploads");
                    try {
                        //convert image to bytes for upload.
                        byte[] fileBytes = FileHelper.getByteArrayFromFile(MainActivity.this, mMediaUri);
                        if (fileBytes == null) {
                            //there was an error
                            Toast.makeText(getApplicationContext(), "There was an error. Try again!", Toast.LENGTH_LONG).show();

                            mSaveChangesBtn.setEnabled(false);
                        } else {

                            fileBytes = FileHelper.reduceImageForUpload(fileBytes);
                            String fileName = FileHelper.getFileName(MainActivity.this, mMediaUri, "image");
                            final ParseFile file = new ParseFile(fileName, fileBytes);
                            imageUpload.saveEventually(new SaveCallback() {
                                @Override
                                public void done(ParseException e) {
                                    if (e == null) {

                                        imageUpload.put("imageContent", file);
                                        imageUpload.saveInBackground(new SaveCallback() {
                                                                         @Override
                                                                         public void done(ParseException e) {
                                                                             Toast.makeText(getApplicationContext(), "Success Uploading iMage!", Toast.LENGTH_LONG).show();

                                                                             //Retrieve the recently saved image from Parse
                                                                             queryParseProfileImages(imageUpload);

                                                                             mSaveChangesBtn.setEnabled(false);
                                                                         }
                                                                     }

                                        );
                                    } else {
                                        //there was an error
                                        Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();

                                        mSaveChangesBtn.setEnabled(false);
                                    }
                                }
                            });

                        }

                    } catch (Exception e1) {
                        Toast.makeText(getApplicationContext(), e1.getMessage(), Toast.LENGTH_LONG).show();
                    }
                }//End onClick(View v)

            });//End onClick Listener


//This method queries for the most recent picture taken
ParseQuery<ParseObject> imagesQuery = new ParseQuery<>("ImageUploads");
            imagesQuery.orderByDescending("createdAt");
            imagesQuery.findInBackground(new FindCallback<ParseObject>() {
                @Override
                public void done(List<ParseObject> images, ParseException e) {
                    if(e == null){

                        //for (int i = 0; i < images.size(); i++) {

                            final String imgUrl = images.get(0).getParseFile("imageContent").getUrl();


                            mProfilePic = (ImageView) findViewById(R.id.profileImage);
                            Picasso.with(MainActivity.this).load(imgUrl).into(mProfilePic);

                        //}
                        //images.pinInBackground();

                        //profileImageId = profImgObj.getObjectId();
                        //Log.d(TAG, "The object id is: " + profileImageId);
                    }else{
                        Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
                    }
                }
            });



        }//End onCreate


        //Method containing ParseQuery to download/pull back the image that was uploaded to Parse
        //Inside the Image View
        private void queryParseProfileImages(final ParseObject imageUploadPassed) {

            ParseFile userImageRetrievedObj = (ParseFile) imageUploadPassed.get("imageContent");
            userImageRetrievedObj.getDataInBackground(new GetDataCallback() {
                public void done(byte[] data, ParseException e) {
                    if (e == null) {


                        final String imgUrl = imageUploadPassed.getParseFile("imageContent").getUrl();


                        mProfilePic = (ImageView) findViewById(R.id.profileImage);
                        Picasso.with(MainActivity.this).load(imgUrl).into(mProfilePic);

                        imageUploadPassed.pinInBackground();


                    } else {
                        // something went wrong
                    }
                }
            });


        }


        //inner helper method
        private Uri getOutputMediaFileUri(int mediaTypeImage) {

            if (isExternalStorageAvailable()) {
                //get the URI
                //get external storage dir
                File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "UPLOADIMAGES");
                //create subdirectore if it does not exist
                if (!mediaStorageDir.exists()) {
                    //create dir
                    if (!mediaStorageDir.mkdirs()) {

                        return null;
                    }
                }
                //create a file name
                //create file
                File mediaFile = null;
                Date now = new Date();
                String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(now);

                String path = mediaStorageDir.getPath() + File.separator;
                if (mediaTypeImage == MEDIA_TYPE_IMAGE) {
                    mediaFile = new File(path + "IMG_" + timestamp + ".jpg");
                }
                //return file uri
                Log.d("UPLOADIMAGE", "FILE: " + Uri.fromFile(mediaFile));

                return Uri.fromFile(mediaFile);
            } else {

                return null;
            }

        }

        //check if external storage is mounted. helper method
        private boolean isExternalStorageAvailable() {
            String state = Environment.getExternalStorageState();
            if (state.equals(Environment.MEDIA_MOUNTED)) {
                return true;
            } else {
                return false;
            }
        }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if (resultCode == RESULT_OK) {
                if (requestCode == CHOOSE_PIC_REQUEST_CODE) {
                    if (data == null) {
                        Toast.makeText(getApplicationContext(), "Image cannot be null!", Toast.LENGTH_LONG).show();
                    } else {
                        mMediaUri = data.getData();
                        //set previews
                        mPreviewImageView.setImageURI(mMediaUri);

                        //Bundle extras = data.getExtras();

                        //Log.e("URI", mMediaUri.toString());

                        //Bitmap bmp = (Bitmap) extras.get("data");


                    }
                } else {

                    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                    mediaScanIntent.setData(mMediaUri);
                    sendBroadcast(mediaScanIntent);
                    //set previews

                    mPreviewImageView.setImageURI(mMediaUri);

                }

            } else if (resultCode != RESULT_CANCELED) {
                Toast.makeText(getApplicationContext(), "Cancelled!", Toast.LENGTH_LONG).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_main, 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
            if (id == R.id.action_settings) {
                return true;
            }

            return super.onOptionsItemSelected(item);
        }
    }

1
很棒的问题,格式良好。 - wesley franks
1个回答

9
首先,我必须说这是一个非常精心制作的问题,我很高兴每个有些声望的人都能提出如此好的问题。
你遇到的问题基本上是Android Activity生命周期的一个问题。我想,问题实际上是非常简单的:我在你的Activity的onCreate()方法中看不到从Parse检索图像的地方:你的下载方法只在onClickListener中调用。
所以,我建议你将它提取到一个私有方法中,就像这样: 编辑:
   private void queryImagesFromParse(){
        ParseQuery<ParseObject> imagesQuery = new ParseQuery<>("User");
        imagesQuery.findInBackground(new FindCallback<ParseObject>() {
            @Override
            public void done(List<ParseObject> imagesItems, ParseException e) {
                if(e == null){

                    ParseUser userCurrentOfParse = ParseUser.getCurrentUser();
                    if(userCurrentOfParse != null) {
                        //final String imgUrl = imageUploadPassed.getParseFile("imageContent").getUrl();
                        final String imgUrl = userCurrentOfParse.getParseFile("userProfilePics").getUrl();


                        mHomeProfilePic = (ImageView) findViewById(R.id.userHomeProfilePicImageView);
                        Picasso.with(HomeActivity.this).load(imgUrl).into(mHomeProfilePic);

                        //imageUploadPassed.pinInBackground();

                       // profileImageId = imageUploadPassed.getObjectId();
                        //Log.d(TAG, "The object id is: " + profileImageId);
                    }

                }else{
                    Toast.makeText(HomeActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
        });
    }

上面的代码只是为了给你一个大概的想法,如果它能编译通过,我会很惊讶。

然后,在onCreate()方法的末尾调用这个方法(onStart也可以,但我更喜欢onCreate())。当然,你也可以从之前的位置调用这个方法(如果你字面上地提取方法右键单击>重构>提取方法,实际上就是这样做的)。

顺便说一下,你使用Picasso很好,但最好使用你ActivityContext来初始化它,所以应该写成Picasso.with(MainActivity.this).load(imgUrl).into(mProfilePic);而不是Picasso.with(getApplicationContext()).load(imgUrl).into(mProfilePic);(应该快1ns!)

编辑:还要确保图片是从Parse的用户表上传和查询的,这将确保每个用户只看到自己的图片(当前登录用户的图片),而不是其他用户上传的下一张图片。

希望对你有所帮助!


2
非常感谢您的回复和赞美。我原本以为自己会被这个问题困扰而无法得到任何帮助,所以您的帮助非常受欢迎。等我回家后,我会尝试您的方法,如果遇到任何进一步的问题,我会告诉您。 - Equivocal
我已经对代码进行了更改,但仍然无法正常工作。我可能没有按照您的指示正确执行,但我不确定。我的做法是在onCreate之外创建一个方法,并将查询的内容放置在该方法中,然后在onCreate中的onClick中调用该方法。 - Equivocal
没错,但是您忘记在“onCreate”中调用它了,不是吗? 您需要在“onCreate”中调用它以使其在第一次加载时加载。 - Laurent Meyer
我又做了一些更改(尽管仍有问题)。请检查我的编辑代码并查看您看到的注释“//此方法查询最近拍摄的图片”,该查询能够使图像在我退出并重新打开应用程序时显示在图像视图中。所以这很好,但是新问题已经发生了,我已经知道会发生,即如果我作为第二个用户登录应用程序并拍摄照片,然后注销第一个用户并重新登录,则第一个用户的照片现在将更改为与第二个用户相同的照片。 - Equivocal
1
哈哈哈,我懂了。抱歉,你肯定漏掉了什么。在您的 Parse 数据库中扩展用户类,使每个用户包含一个文件(在数据浏览器中添加一个 ParseFile 类型的列)。然后调用 getCurrentUser.getParseFile(file),假设 getCurrentUser 不为空,因为您已经登录了,它会起作用。 - Laurent Meyer
显示剩余10条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接