如何在带有Firebase的android studio中创建类似“编辑个人头像”页面的火种/大爆炸?

时间:2019-04-01 22:22:22

标签: java android html firebase

我正在尝试创建一个应用,您可以在其中添加移动设备中的个人资料图片,然后将其保存到firebase,并尽可能高效地从firebase检索它。

几个问题:

1:这些大的约会应用程序(如bumble / tinder)如何创建编辑个人资料图像UI,您可以在其中上传个人资料图像并重新排列它们?他们是否将卡片视图放置到网格视图中,以查看这些卡片如何被拖动以重新排列位置?此外,他们通常会附加一个小的x按钮来删除图片,因此它是Cardview,对吧?

我目前正在使用ImageViews进行测试,并希望合并添加更多内容的功能,但是我的代码很糟糕,如果我返回页面并添加新图像,它将覆盖Firebase DB中的图像。

LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SettingsActivity"
    android:orientation="vertical">

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/back"
    android:text="Back"
    android:layout_marginBottom="20sp"/>
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="20sp"
    android:orientation="horizontal">
    <ImageView

        android:layout_width="100sp"
        android:layout_height="100sp"
        android:id="@+id/image1"
        android:src="@mipmap/ic_launcher"
        android:layout_margin="20sp"
        android:layout_gravity="start"
        />
    <ImageView
        android:layout_width="100sp"
        android:layout_height="100sp"
        android:id="@+id/image2"
        android:src="@mipmap/ic_launcher"
        android:layout_margin="20sp"
        android:layout_gravity="center_horizontal"

        />
    <ImageView
        android:layout_width="100sp"
        android:layout_height="100sp"
        android:id="@+id/image3"
        android:src="@mipmap/ic_launcher"
        android:layout_margin="20sp"
        android:layout_gravity="end"
        />

</LinearLayout>



public class SettingsActivity extends AppCompatActivity {
    private Button mBack;
    private ImageView mImage1, mImage2, mImage3;
    private FirebaseAuth mAuth;
    private DatabaseReference mUserDb, mTagsDb;
    private String userId, phone, image1Url, image2Url, image3Url, userSex;
    private Uri resultUri1, resultUri2, resultUri3;
    private ArrayList<Uri> resultUri = new ArrayList<Uri>();
    private ArrayList<ImageView> imageViewsList = new ArrayList<ImageView>();
    final int MaxTags = 5;
    final int MaxImages = 3;

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

        mImage1 = findViewById(R.id.image1);
        mImage2 = findViewById(R.id.image2);
        mImage3 = findViewById(R.id.image3);
        mBack = findViewById(R.id.back);

        mAuth = FirebaseAuth.getInstance();
        userId = mAuth.getCurrentUser().getUid();
        mUserDb = FirebaseDatabase.getInstance().getReference().child("Users").child(userId);
        getUserInfo();

        mImage1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent, 1);
            }
        });
        mImage2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent, 2);
            }
        });
        mImage3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent, 3);
            }
        });

        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveUserInformation();
                finish();

            }
        });

private void saveUserInformation() {
        phone = mPhoneField.getText().toString();

        Map userInfo = new HashMap();
        userInfo.put("phone", phone);
        mUserDb.updateChildren(userInfo);
        if(resultUri != null){
            for(int i = 0; i < resultUri.size(); i++)
            {   String num = String.valueOf(i);
                final StorageReference filePath = FirebaseStorage.getInstance().getReference().child("profileImages").child(userId).child(num);
                Bitmap bitmap = null;

                try {
                    bitmap = MediaStore.Images.Media.getBitmap(getApplication().getContentResolver(), resultUri.get(i));
                } catch (IOException e) {
                    e.printStackTrace();
                }

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
                byte[] data = baos.toByteArray();
                UploadTask uploadTask = filePath.putBytes(data);
                uploadTask.addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        finish();
                    }
                });
                final int finalI = i+1;
                uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                            @Override
                            public void onSuccess(Uri uri) {
                                Map newImage = new HashMap();
                                newImage.put("image"+ finalI +"Url", uri.toString());
                                mUserDb.updateChildren(newImage);

                                finish();
                                return;
                            }
                        }).addOnFailureListener(new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception exception) {
                                finish();
                                return;
                            }
                        });
                    }
                });
            }



        }else{
            finish();
        }
    }


    ArrayAdapter<String> values;
    private void getUserInfo() {

        mUserDb.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if(dataSnapshot.exists() && dataSnapshot.getChildrenCount()>0){


                    Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
                    if(map.get("phone") != null){
                        phone = map.get("phone").toString();
                        mPhoneField.setText(phone);
                    }
                    if(map.get("sex") != null){
                        userSex = map.get("sex").toString();
                    }

                    Glide.clear(mImage1);
                    Glide.clear(mImage2);
                    Glide.clear(mImage3);
                    if(MaxImages == 3) {
                        imageViewsList.add(mImage1);
                        imageViewsList.add(mImage2);
                        imageViewsList.add(mImage3);
                    }
                    for(int i = 0; i < MaxImages; i ++)
                    {
                        int b = i+1;
                        if(map.get("image"+b+"Url") != null){
                            String url = map.get("image"+b+"Url").toString();
                            switch(url){
                                case "default":
                                    imageViewsList.get(i).setImageResource(R.mipmap.ic_launcher);
                                    //Glide.with(getApplication()).load(R.mipmap.ic_launcher).into(mImage1);
                                    break;
                                default:
                                    Glide.with(getApplication()).load(url).into(imageViewsList.get(i));
                                    break;
                            }
                        }
                    }


                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }

 @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 1 && resultCode == Activity.RESULT_OK){
            final Uri imageUri = data.getData();
            resultUri1 = imageUri;
            mImage1.setImageURI(resultUri1);
            resultUri.add(resultUri1);
        }
        if(requestCode == 2 && resultCode == Activity.RESULT_OK){
            final Uri imageUri = data.getData();
            resultUri2 = imageUri;
            mImage2.setImageURI(resultUri2);
            resultUri.add(resultUri2);
        }
        if(requestCode == 3 && resultCode == Activity.RESULT_OK){
            final Uri imageUri = data.getData();
            resultUri3 = imageUri;
            mImage3.setImageURI(resultUri3);
            resultUri.add(resultUri3);
        }
    }
}

当前,我可以将图像上载到imageviews并将其保存到firebase,但是例如,如果我上载2张图像,然后保存并返回以上传第3张图像,则该图像会覆盖图像1。这样吗?

1 个答案:

答案 0 :(得分:0)

因此,在再次查看我可以使用的其他应用程序之后,我意识到,似乎在您选择了手机图片库的onResultActivity之后,它们会将图像上传到了Firebase。因此,我简化了代码以实现相同效果,并且效果更好。代码现在可以使用,但是我只需要调整图像大小以适合图像视图即可,除此之外,没有任何抱怨。

如果您有更好,更高效的代码编写方式,请发表评论,效率是关键,我将不胜感激。

 protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);

        mImage1 = findViewById(R.id.image1);
        mImage2 = findViewById(R.id.image2);
        mImage3 = findViewById(R.id.image3);

        mAuth = FirebaseAuth.getInstance();
        userId = mAuth.getCurrentUser().getUid();
        mUserDb = FirebaseDatabase.getInstance().getReference().child("Users").child(userId);

        getUserInfo();
        getUserTags();

            mImage1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(Intent.ACTION_PICK);
                    intent.setType("image/*");
                    startActivityForResult(intent, 1);
                }
            });
            mImage2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(Intent.ACTION_PICK);
                    intent.setType("image/*");
                    startActivityForResult(intent, 2);
                }
            });
            mImage3.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(Intent.ACTION_PICK);
                    intent.setType("image/*");
                    startActivityForResult(intent, 3);
                }
            });

    private void getUserInfo() {

            mUserDb.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    if(dataSnapshot.exists() && dataSnapshot.getChildrenCount()>0){

                        Glide.clear(mImage1);
                        if(map.get("image1Url") != null){
                            image1Url = map.get("image1Url").toString();
                            switch(image1Url){
                                case "default":
                                    mImage1.setImageResource(R.mipmap.ic_launcher);
                                    //Glide.with(getApplication()).load(R.mipmap.ic_launcher).into(mImage1);
                                    break;
                                default:
                                    Glide.with(getApplication()).load(image1Url).into(mImage1);
                                    break;
                            }
                        }
                        if(map.get("image2Url") != null){
                            image2Url = map.get("image2Url").toString();
                            switch(image2Url){
                                case "default":
                                    mImage2.setImageResource(R.mipmap.ic_launcher);
                                    //Glide.with(getApplication()).load(R.mipmap.ic_launcher).into(mImage1);
                                    break;
                                default:
                                    Glide.with(getApplication()).load(image2Url).into(mImage2);
                                    break;
                            }
                        }
                        if(map.get("image3Url") != null){
                            image3Url = map.get("image3Url").toString();
                            switch(image3Url){
                                case "default":
                                    mImage3.setImageResource(R.mipmap.ic_launcher);
                                    //Glide.with(getApplication()).load(R.mipmap.ic_launcher).into(mImage1);
                                    break;
                                default:
                                    Glide.with(getApplication()).load(image3Url).into(mImage3);
                                    break;
                            }
                        }
                    }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }
            });
        }

    @Override
        protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if(requestCode == 1 && resultCode == Activity.RESULT_OK){
                final Uri imageUri = data.getData();
                final Uri resultUri = imageUri;
                if(resultUri != null){
                    final StorageReference filePath = FirebaseStorage.getInstance().getReference().child("profileImages").child(userId).child("image1");
                    Bitmap bitmap = null;

                    try {
                        bitmap = MediaStore.Images.Media.getBitmap(getApplication().getContentResolver(), resultUri);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
                    byte[] databytes = baos.toByteArray();
                    UploadTask uploadTask = filePath.putBytes(databytes);
                    uploadTask.addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Toast toast = Toast.makeText(SettingsActivity.this, "Upload Failed! Please try again", Toast.LENGTH_LONG);
                            toast.setGravity(Gravity.CENTER, 0, 0);
                            toast.show();
                        }
                    });
                    uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                                @Override
                                public void onSuccess(Uri uri) {
                                    Map newImage = new HashMap();
                                    newImage.put("image1Url", uri.toString());
                                    mUserDb.updateChildren(newImage);
                                    mImage1.setImageURI(resultUri);
                                    Toast toast = Toast.makeText(SettingsActivity.this, "Upload Successful!", Toast.LENGTH_LONG);
                                    toast.setGravity(Gravity.CENTER, 0, 0);
                                    toast.show();
                                }
                            }).addOnFailureListener(new OnFailureListener() {
                                @Override
                                public void onFailure(@NonNull Exception exception) {
                                    Toast toast = Toast.makeText(SettingsActivity.this, "Upload Failed! Please try again", Toast.LENGTH_LONG);
                                    toast.setGravity(Gravity.CENTER, 0, 0);
                                    toast.show();
                                }
                            });
                        }
                    });

                }else{
                    finish();
                }

            }
            if(requestCode == 2 && resultCode == Activity.RESULT_OK){
                final Uri imageUri = data.getData();
                final Uri resultUri = imageUri;
                if(resultUri != null){
                    final StorageReference filePath = FirebaseStorage.getInstance().getReference().child("profileImages").child(userId).child("image2");
                    Bitmap bitmap = null;

                    try {
                        bitmap = MediaStore.Images.Media.getBitmap(getApplication().getContentResolver(), resultUri);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
                    byte[] databytes = baos.toByteArray();
                    UploadTask uploadTask = filePath.putBytes(databytes);
                    uploadTask.addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Toast toast = Toast.makeText(SettingsActivity.this, "Upload Failed! Please try again", Toast.LENGTH_LONG);
                            toast.setGravity(Gravity.CENTER, 0, 0);
                            toast.show();
                        }
                    });
                    uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                                @Override
                                public void onSuccess(Uri uri) {
                                    Map newImage = new HashMap();
                                    newImage.put("image2Url", uri.toString());
                                    mUserDb.updateChildren(newImage);
                                    mImage2.setImageURI(resultUri);
                                    Toast toast = Toast.makeText(SettingsActivity.this, "Upload Successful!", Toast.LENGTH_LONG);
                                    toast.setGravity(Gravity.CENTER, 0, 0);
                                    toast.show();
                                }
                            }).addOnFailureListener(new OnFailureListener() {
                                @Override
                                public void onFailure(@NonNull Exception exception) {
                                    Toast toast = Toast.makeText(SettingsActivity.this, "Upload Failed! Please try again", Toast.LENGTH_LONG);
                                    toast.setGravity(Gravity.CENTER, 0, 0);
                                    toast.show();
                                }
                            });
                        }
                    });

                }else{
                    finish();
                }
            }
            if(requestCode == 3 && resultCode == Activity.RESULT_OK){
                final Uri imageUri = data.getData();
                final Uri resultUri = imageUri;
                if(resultUri != null){
                    final StorageReference filePath = FirebaseStorage.getInstance().getReference().child("profileImages").child(userId).child("image3");
                    Bitmap bitmap = null;

                    try {
                        bitmap = MediaStore.Images.Media.getBitmap(getApplication().getContentResolver(), resultUri);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
                    byte[] databytes = baos.toByteArray();
                    UploadTask uploadTask = filePath.putBytes(databytes);
                    uploadTask.addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Toast toast = Toast.makeText(SettingsActivity.this, "Upload Failed! Please try again", Toast.LENGTH_LONG);
                            toast.setGravity(Gravity.CENTER, 0, 0);
                            toast.show();
                        }
                    });
                    uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                                @Override
                                public void onSuccess(Uri uri) {
                                    Map newImage = new HashMap();
                                    newImage.put("image3Url", uri.toString());
                                    mUserDb.updateChildren(newImage);
                                    mImage3.setImageURI(resultUri);
                                    Toast toast = Toast.makeText(SettingsActivity.this, "Upload Successful!", Toast.LENGTH_LONG);
                                    toast.setGravity(Gravity.CENTER, 0, 0);
                                    toast.show();
                                }
                            }).addOnFailureListener(new OnFailureListener() {
                                @Override
                                public void onFailure(@NonNull Exception exception) {
                                    Toast toast = Toast.makeText(SettingsActivity.this, "Upload Failed! Please try again", Toast.LENGTH_LONG);
                                    toast.setGravity(Gravity.CENTER, 0, 0);
                                    toast.show();
                                }
                            });
                        }
                    });

                }else{
                    finish();
                }
            }
        }