java - 上传图片时出现问题

标签 java android android-layout android-activity parse-platform

我已经成功地将用户输入的信息存储到解析中,但我一直很难将图像存储到解析中,以便以后能够检索。

为了澄清这一点,下面是我用于个人资料创建 Activity 的代码,该 Activity 是在用户使用社交媒体签名并回答一系列问题(例如年龄、首选名称以及这些信息的位置)后提示的 Activity 稍后在解析数据库中更新并添加到当前用户。

此外,在 Activity 中,用户已经能够从他们的设备上传图片,我的问题现在解决了获取上传的图片并将其存储在解析中,以及将图像与使用其社交媒体签名的当前用户相关联媒体帐户 - 社交媒体集成是通过解析完成的。

我已经查看了以下指南,但仍然很困惑。 https://www.parse.com/docs/android_guide#files

现在我已经尝试完成此任务,并在下面的代码中留下了我的评论。

任何帮助将不胜感激。提前致谢。

public class ProfileCreation extends Activity {

    private static final int RESULT_LOAD_IMAGE = 1;
    FrameLayout layout;
    Button save;
    protected EditText mName;
    protected EditText mAge;
    protected EditText mHeadline;
    protected ImageView mprofilePicture;

    protected Button mConfirm;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile_creation);

        RelativeLayout v = (RelativeLayout) findViewById(R.id.main); 

        v.requestFocus();

        Parse.initialize(this, "ID", "ID");

        mName = (EditText)findViewById(R.id.etxtname);
        mAge = (EditText)findViewById(R.id.etxtage);
        mHeadline = (EditText)findViewById(R.id.etxtheadline);
        mprofilePicture = (ImageView)findViewById(R.id.profilePicturePreview);

        mConfirm = (Button)findViewById(R.id.btnConfirm);
        mConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String name = mName.getText().toString();
                String age = mAge.getText().toString();
                String headline = mHeadline.getText().toString();



                age = age.trim();
                name = name.trim();
                headline = headline.trim();

                if (age.isEmpty() || name.isEmpty() || headline.isEmpty()) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(ProfileCreation.this);
                    builder.setMessage(R.string.signup_error_message)
                        .setTitle(R.string.signup_error_title)
                        .setPositiveButton(android.R.string.ok, null);
                    AlertDialog dialog = builder.create();
                    dialog.show();
                }
                else {
                    // create the new user!
                    setProgressBarIndeterminateVisibility(true);

                    ParseUser currentUser = ParseUser.getCurrentUser();

                     /* This is the section where the images is converted, saved, and uploaded. I have not been able Locate the image from the ImageView, where the user uploads the picture to imageview from either their gallery and later on from facebook */ 
                    Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
                            /*fron image view */);
                    // Convert it to byte
                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    // Compress image to lower quality scale 1 - 100
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
                    byte[] image = stream.toByteArray();

                    // Create the ParseFile
                    ParseFile file = new ParseFile("profilePicture.png", image);
                    // Upload the image into Parse Cloud
                    file.saveInBackground();

                    // Create a column named "ImageName" and set the string
                    currentUser.put("ImageName", "AndroidBegin Logo");

                    // Create a column named "ImageFile" and insert the image
                    currentUser.put("ProfilePicture", file);

                    // Create the class and the columns
                    currentUser.saveInBackground();

                    currentUser.put("name", name); 
                    currentUser.put("age", age); 
                    currentUser.put("headline", headline); 
                    currentUser.saveInBackground(new SaveCallback() {
                        @Override
                        public void done(ParseException e) {
                            setProgressBarIndeterminateVisibility(false);

                            if (e == null) {
                                // Success!
                                Intent intent = new Intent(ProfileCreation.this, MoodActivity.class);
                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                startActivity(intent);
                            }
                            else {
                                AlertDialog.Builder builder = new AlertDialog.Builder(ProfileCreation.this);
                                builder.setMessage(e.getMessage())
                                    .setTitle(R.string.signup_error_title)
                                    .setPositiveButton(android.R.string.ok, null);
                                AlertDialog dialog = builder.create();
                                dialog.show();
                            }
                        }
                    });
                }
            }
        });



        SeekBar seekBar = (SeekBar) findViewById(R.id.seekBarDistance);
        final TextView seekBarValue = (TextView) findViewById(R.id.seekBarDistanceValue);

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                    boolean fromUser) {
                // TODO Auto-generated method stub 
                seekBarValue.setText(String.valueOf(progress));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub 
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub 
            }

        }); // Add this

        Button mcancel = (Button)findViewById(R.id.btnBack);
        mcancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                ProfileCreation.this.startActivity(new Intent(ProfileCreation.this, LoginActivity.class));
            }
        });




        SeekBar seekBarMinimum = (SeekBar) findViewById(R.id.seekBarMinimumAge);
        final TextView txtMinimum = (TextView) findViewById(R.id.tMinAge);

        seekBarMinimum.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                    boolean fromUser) {
                // TODO Auto-generated method stub 
                txtMinimum.setText(String.valueOf(progress));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub 
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub 
            }

        }); // Add this

        SeekBar seekBarMaximum = (SeekBar) findViewById(R.id.seekBarMaximumAge);
        final TextView txtMaximum = (TextView) findViewById(R.id.tMaxAge);

        seekBarMaximum.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                    boolean fromUser) {
                // TODO Auto-generated method stub 
                txtMaximum.setText(String.valueOf(progress));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub 
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub 
            }

        }); // Add this




        Button buttonLoadImage = (Button) findViewById(R.id.btnPictureSelect);
        buttonLoadImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Intent i = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(i, RESULT_LOAD_IMAGE);
            }
        });

    } 

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

            if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
                    && 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]);
                String picturePath = cursor.getString(columnIndex);
                cursor.close();

                ImageView imageView = (ImageView) findViewById(R.id.profilePicturePreview);
                imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));

            }

        }

        private byte[] readInFile(String path) throws IOException {
            // TODO Auto-generated method stub
            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();

        }
    }

最佳答案

您需要等待文件保存完成,然后才能将其添加到用户。

尝试向 file.saveInBackground() 调用添加一个完成 block ,并将所有 currentUser 操作移至该完成 block 中。

关于java - 上传图片时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25234610/

相关文章:

android - 在 Android 应用程序中显示拍摄的照片

java - 有没有办法让查询在 eclipselink 中触发

android - 广播接收器不影响 Android 4.0(可能是 3.1+)中的共享首选项

具有 flavor 的 Android 主题模块

android - 获取 RelativeLayout 尺寸

android - SlidingPaneLayout 上的点击事件

java - 在 AES 加密中,迭代次数真的会增加安全性吗?

java - 为什么同时声明读写资源会抛出异常?

java - 使用 JSON 模式在 Java 中创建和序列化数据

c# - 构建项目后无法旋转相机和 Head Unity 3D