如何创建一个应用程序,允许用户照片上传/更改? [英] How To Create An App That Allows For Profile Picture Upload/Change?

查看:294
本文介绍了如何创建一个应用程序,允许用户照片上传/更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找高和低找到如何实现我的应用程序中的个人资料图片变化的例子。我想允许的人添加/使用Parse.com(到所有的社会媒体应用类似今天)改变自己的个人资料图片。

例如:的Twitter,Facebook,Instagram的等等,都可以让您拍摄/上传个人资料图片和影像被保存,并可以在以后上观看

我有没有运气找到,讨论了如何做这样的事情的任何材料,并没有else似乎了解我想要在这里实现:

<一个href=\"http://stackoverflow.com/questions/34561551/an-image-downloaded-from-parse-stay-on-screen-even-after-you-exit-and-reopen-app\">An图片下载从parse停留在屏幕上即使您退出并重新打开应用程序?

因此​​,在我的应用程序远远用户可以使用相机拍摄意图图片或上传从画廊的图像,并且图像显示在图像视图完美。

的问题是:当我退出并重新打开应用程序图像视图内的图像不再显示(就消失了)

我该如何解决这个问题?

MainActivity:

 公共类MainActivity扩展AppCompatActivity {        公共静态最终诠释TAKE_PIC_REQUEST_ code = 0;
        公共静态最终诠释CHOOSE_PIC_REQUEST_ code = 1;
        公共静态最终诠释MEDIA_TYPE_IMAGE = 2;        私人乌里mMediaUri;        私人TextView的mChangeProfilePic;
        受保护的ImageView米previewImageView;
        私人按钮mSaveChangesBtn;
        公共ImageView的mProfilePic;
        @覆盖
        保护无效的onCreate(捆绑savedInstanceState){
            super.onCreate(savedInstanceState);
            的setContentView(R.layout.activity_main);
            工具条工具栏=(栏)findViewById(R.id.toolbar);
            setSupportActionBar(工具栏);
            FloatingActionButton FAB =(FloatingActionButton)findViewById(R.id.fab);
            fab.setOnClickListener(新View.OnClickListener(){
                @覆盖
                公共无效的onClick(查看视图){
                    Snackbar.make(看来,用自己的行动替换,Snackbar.LENGTH_LONG)
                            .setAction(动作,NULL).show();
                }
            });
            //初始化变量
            mChangeProfilePic =(的TextView)findViewById(R.id.changeProfileImageTxt);
            米previewImageView =(ImageView的)findViewById(R.id.profileImage);
            mSaveChangesBtn =(按钮)findViewById(R.id.saveProfileChangesBtn);
            mSaveChangesBtn.setEnabled(假);            最终按钮mNextBtn =(按钮)findViewById(R.id.NextBtn);
            mNextBtn.setOnClickListener(新View.OnClickListener(){
                @覆盖
                公共无效的onClick(视图v){
                    意图int​​entNext =新意图(MainActivity.this,SecondActivity.class);
                    startActivity(intentNext);
                }
            });
            //更改个人资料图片
            //设置onlClick到的TextView
            mChangeProfilePic.setOnClickListener(新View.OnClickListener(){
                @覆盖
                公共无效的onClick(视图v){
                    Toast.makeText(getApplicationContext(),更改产品图pressed,Toast.LENGTH_SHORT).show();                    //显示对话框
                    AlertDialog.Builder建设者=新AlertDialog.Builder(MainActivity.this);
                    builder.setTitle(上传或拍照);
                    builder.setPositiveButton(上传,新DialogInterface.OnClickListener(){
                        @覆盖
                        公共无效的onClick(DialogInterface对话,诠释它){
                            //上传图片
                            意图choosePictureIntent =新意图(Intent.ACTION_GET_CONTENT);
                            choosePictureIntent.setType(图像/ *);
                            startActivityForResult(choosePictureIntent,CHOOSE_PIC_REQUEST_ code);                            mSaveChangesBtn.setEnabled(真);                        }
                    });
                    builder.setNegativeButton(拍摄照片,新DialogInterface.OnClickListener(){
                        @覆盖
                        公共无效的onClick(DialogInterface对话,诠释它){
                            //照相
                            意图takePicture =新意图(MediaStore.ACTION_IM​​AGE_CAPTURE);
                            mMediaUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
                            如果(mMediaUri == NULL){
                                //显示错误
                                Toast.makeText(getApplicationContext()!对不起有一个错误重试,Toast.LENGTH_LONG).show();                                mSaveChangesBtn.setEnabled(假);                            }其他{
                                takePicture.putExtra(MediaStore.EXTRA_OUTPUT,mMediaUri);
                                startActivityForResult(takePicture,TAKE_PIC_REQUEST_ code);                                mSaveChangesBtn.setEnabled(真);
                            }
                        }
                    });
                    AlertDialog对话框= builder.create();
                    dialog.show();
                }
            }); //结束更改个人资料图片的onClick监听器
            //保存个人资料更改按钮
            //还上传的内容解析和将其拉回同一时间
            mSaveChangesBtn.setOnClickListener(新View.OnClickListener(){
                @覆盖
                公共无效的onClick(视图v){                    //创建解析对象要上传的图片
                    最终的parseObject imageUpload =新的parseObject(ImageUploads);
                    尝试{
                        //图像转换为字节上传。
                        字节[] = fileBytes FileHelper.getByteArrayFromFile(MainActivity.this,mMediaUri);
                        如果(fileBytes == NULL){
                            //有一个错误
                            Toast.makeText(getApplicationContext()!有一个错误重试,Toast.LENGTH_LONG).show();                            mSaveChangesBtn.setEnabled(假);
                        }其他{                            fileBytes = FileHelper.reduceImageForUpload(fileBytes);
                            字符串文件名= FileHelper.getFileName(MainActivity.this,mMediaUri,图像);
                            最后ParseFile文件=新ParseFile(文件名,fileBytes);
                            imageUpload.saveEventually(新SaveCallback(){
                                @覆盖
                                公共无效完成(ParseException的E){
                                    如果(E == NULL){                                        imageUpload.put(imageContent文件);
                                        imageUpload.saveInBackground(新SaveCallback(){
                                                                         @覆盖
                                                                         公共无效完成(ParseException的E){
                                                                             Toast.makeText(getApplicationContext(),成功上传图片!,Toast.LENGTH_LONG).show();                                                                             //从解析最近保存的图像
                                                                             queryParseProfileImages(imageUpload);                                                                             mSaveChangesBtn.setEnabled(假);
                                                                         }
                                                                     }                                        );
                                    }其他{
                                        //有一个错误
                                        Toast.makeText(getApplicationContext(),e.​​getMessage(),Toast.LENGTH_LONG).show();                                        mSaveChangesBtn.setEnabled(假);
                                    }
                                }
                            });                        }                    }赶上(例外E1){
                        Toast.makeText(getApplicationContext(),e1.getMessage(),Toast.LENGTH_LONG).show();
                    }
                } //结束的onClick(视图v)            }); //结束的onClick监听器
//取本作的最新画面方式查询
ParseQuery&LT;&的parseObject GT; imagesQuery =新ParseQuery&LT;&GT;(ImageUploads);
            imagesQuery.orderByDescending(createdAt);
            imagesQuery.findInBackground(新FindCallback&LT;&的parseObject GT;(){
                @覆盖
                公共无效完成(列表&LT;&的parseObject GT;的图像,ParseException的E){
                    如果(E == NULL){                        //的for(int i = 0; I&LT; images.size();我++){                            。最后弦乐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的对象ID为:+ profileImageId);
                    }其他{
                        Toast.makeText(MainActivity.this,e.getMessage(),Toast.LENGTH_LONG).show();
                    }
                }
            });        } //结束的onCreate
        //方法包含ParseQuery下载/拉回来已上载到解析图像
        //里面的图片浏览
        私人无效queryParseProfileImages(最终的parseObject imageUploadPassed){            ParseFile userImageRetrievedObj =(ParseFile)imageUploadPassed.get(imageContent);
            userImageRetrievedObj.getDataInBackground(新GetDataCallback(){
                公共无效完成(字节[]数据,ParseException的E){
                    如果(E == NULL){
                        最后弦乐imgUrl的= imageUploadPassed.getParseFile(imageContent)的getURL()。
                        mProfilePic =(ImageView的)findViewById(R.id.profileImage);
                        Picasso.with(MainActivity.this).load(imgUrl的).into(mProfilePic);                        imageUploadPassed.pinInBackground();
                    }其他{
                        // 出了些问题
                    }
                }
            });
        }
        //内助方法
        私人乌里getOutputMediaFileUri(INT mediaTypeImage){            如果(isExternalStorageAvailable()){
                //获取URI
                //获取外部存储目录
                文件mediaStorageDir =新的文件(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),UPLOADIMAGES);
                如果它不存在//创建subdirectore
                如果(!mediaStorageDir.exists()){
                    //创建目录
                    如果(!mediaStorageDir.mkdirs()){                        返回null;
                    }
                }
                //创建一个文件名
                //创建文件
                文件媒体文件= NULL;
                现在日期=新的日期();
                字符串时间戳=新的SimpleDateFormat(YYYYMMDD_HHMMSS,Locale.US).format(现在的);                字符串路径= mediaStorageDir.getPath()+文件分割符;
                如果(mediaTypeImage == MEDIA_TYPE_IMAGE){
                    媒体文件=新的文件(路径+IMG_+时间戳+.JPG);
                }
                //返回文件URI
                Log.d(UPLOADIMAGE,FILE:+ Uri.fromFile(媒体文件));                返回Uri.fromFile(媒体文件);
            }其他{                返回null;
            }        }        //检查外部存储安装。 helper方法
        私人布尔isExternalStorageAvailable(){
            字符串状态= Environment.getExternalStorageState();
            如果(state.equals(Environment.MEDIA_MOUNTED)){
                返回true;
            }其他{
                返回false;
            }
        }        @覆盖
        保护无效的onActivityResult(INT申请code,INT结果code,意图数据){
            super.onActivityResult(要求code,结果code,数据);
            如果(结果code == RESULT_OK){
                如果(要求code == CHOOSE_PIC_REQUEST_ code){
                    如果(数据== NULL){
                        Toast.makeText(getApplicationContext(),图像不能为空!,Toast.LENGTH_LONG).show();
                    }其他{
                        mMediaUri = data.getData();
                        //设置previews
                        米previewImageView.setImageURI(mMediaUri);                        //捆绑额外= data.getExtras();                        //Log.e(\"URI,mMediaUri.toString());                        // BMP位=(位图)extras.get(数据);
                    }
                }其他{                    意图mediaScanIntent =新意图(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                    mediaScanIntent.setData(mMediaUri);
                    sendBroadcast(mediaScanIntent);
                    //设置previews                    米previewImageView.setImageURI(mMediaUri);                }            }否则如果(结果code!= RESULT_CANCELED){
                Toast.makeText(getApplicationContext(),!已取消,Toast.LENGTH_LONG).show();
            }
        }
        @覆盖
        公共布尔onCreateOptionsMenu(菜单菜单){
            //充气菜单;如果是present这增加了项目操作栏。
            。getMenuInflater()膨胀(R.menu.menu_main,菜单);
            返回true;
        }
        @覆盖
        公共布尔onOptionsItemSelected(菜单项项){
            //处理动作栏项目点击这里。操作栏会
            //自动处理上点击主页/向上按钮,只要
            //你在AndroidManifest.xml中指定一个父活动。
            INT ID = item.getItemId();            // noinspection SimplifiableIfStatement
            如果(ID == R.id.action_settings){
                返回true;
            }            返回super.onOptionsItemSelected(项目);
        }
    }


解决方案

首先,我不得不说,这是一个很好制定的问题,我会很乐意与一些信誉每一个家伙问这么好的配方的问题。

您遇到的问题基本上是与Android活动的生命周期的问题。我想,这个问题真是小巫见大巫:我看到无处你的活动的onCreate()您检索解析图像的地方:您的下载方法只叫了 onClickListener

因此​​,与其在这里有它,我想它解压到一个私人方法,一种是这样的:

编辑:

 私人无效queryImagesFromParse(){
        ParseQuery&LT;&的parseObject GT; imagesQuery =新ParseQuery&LT;&GT;(用户);
        imagesQuery.findInBackground(新FindCallback&LT;&的parseObject GT;(){
            @覆盖
            公共无效完成(列表&LT;&的parseObject GT; imagesItems,ParseException的E){
                如果(E == NULL){                    ParseUser userCurrentOfParse = ParseUser.getCurrentUser();
                    如果(userCurrentOfParse!= NULL){
                        //最后弦乐imgUrl的= imageUploadPassed.getParseFile(imageContent)的getURL();
                        最后弦乐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的对象ID为:+ profileImageId);
                    }                }其他{
                    Toast.makeText(HomeActivity.this,e.getMessage(),Toast.LENGTH_LONG).show();
                }
            }
        });
    }

(上面的code是只给一个粗略的想法,我会感到惊讶,如果它编译)。

然后,你在年底调用此方法的的onCreate()在onStart 可以工作,以及,但我preFER 的onCreate())。当然,你也可以调用此方法从那里从前的地方(即如果你从字面上提取物方法右键单击实际上发生了什么> 折射> 提取方法

顺便说一下,很不错,你使用毕加索但它可以更好地与背景来初始化它你活动所以 Picasso.with(MainActivity.this).load(imgUrl的).into(mProfilePic); 而不是 Picasso.with(getApplicationContext())负载(imgUrl的).into(mProfilePic); (!应该是1纳秒更快)。

编辑:同时确保图像被上载,并从用户表上的解析,这将确保每个用户将看到自己的形象(当前登录用户的图像)查询并不算那上传下一个图像的每个其它用户。

希望它帮助!

I have been searching high and low to find an example of how to implement profile picture changes within my app. I want to allow persons to add/change their profile image using Parse.com (Similar to all social media apps today).

For example: Twitter, Facebook, Instagram and so on, they all allow you to take/upload a profile image and that image is saved and can be viewed later on.

I have had no luck finding any material that covers how to do such a thing and no else seems to be understanding what I'm trying to achieve here:

An Image Downloaded From Parse Stay On Screen Even After You Exit And Reopen App?

So far in my app the user can take a picture with the camera intent or upload an image from gallery and that image is displayed in an Image View perfectly.

The problem is: when I exit and re-open the app the image inside of the Image View is no longer displayed (it is gone).

How can I solve this problem?

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

解决方案

First, I have to say that this a really well formulated question and I would be happy that every guy with few reputation asks so good formulated questions.

The problem you encounter is basically an issue with the Android Activity lifecycle. I guess, the problem is really trivial: I see nowhere in your Activity onCreate() a place where you retrieve the image from Parse: your download method is only called in a onClickListener.

So instead of having it here, I would extract it to a private method, kind of something like this:

Edit:

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

(The code above is just to give an rough idea, I would be surprised if it compiles).

And then, you call this method at the end of the onCreate() (onStart could work as well, but I'd prefer onCreate()). Of course, you can call this method also from the place where it was before (that is actually what happens if you literally extract the method Right-Click > Refractor > Extract Method)

Btw, very good that you use Picasso but it could be better to initialise it with the Context of your Activity so Picasso.with(MainActivity.this).load(imgUrl).into(mProfilePic); instead of Picasso.with(getApplicationContext()).load(imgUrl).into(mProfilePic); (should be 1 ns faster!)

Edit: Also be sure that the image is being upload and queried from the User table on Parse this will ensure that each user will see their own image(currently logged in user's image) and not that of every other user that uploads the next image.

Hope it helps!

这篇关于如何创建一个应用程序,允许用户照片上传/更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆