从Firebase删除值导致应用崩溃并重新启动

时间:2017-03-18 11:42:23

标签: android firebase firebase-realtime-database firebase-storage

有一个FloatingActionButton可以让你改变你的imageView。设置图像视图后,它会立即将Firebase数据库中的imageUrl键更改为已添加的新图像。这工作正常,我试图从我的Firebase存储中删除以前的图像,因为我不希望存在不必要的图像。

当前图像uri存储在“已保存的首选项”中,然后在按下按钮进行更改时使用。 每次我按下此按钮并从我的图库中选择一个图像,

1)我的应用程序崩溃,我必须再次登录。

再次登录后,会显示新图像,

2)但是它不会从我的FirebaseStorage中删除。

我想解决这两个问题。

Moi_Frag.java

package com.example.admin.college20;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;

import java.util.HashMap;
import java.util.Map;

import static android.app.Activity.RESULT_OK;

public class Moi_Frag extends Fragment {
    ImageView imageView;
    FloatingActionButton floatingActionButton;
    private static final int GALLERY_INTENT = 1;
    private Uri imageUri = null;
    TextView text_name, text_email;
    ProgressDialog progressDialog;

    private String uid;
    StorageReference storageReference;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View mView = inflater.inflate(R.layout.activity_moi__frag, container, false);

        imageView = (ImageView) mView.findViewById(R.id.profile_image);
        floatingActionButton = (FloatingActionButton) mView.findViewById(R.id.floatingActionButton);
        text_name = (TextView) mView.findViewById(R.id.moi_name);
        text_email = (TextView) mView.findViewById(R.id.moi_email);

        progressDialog = new ProgressDialog(getContext());

        storageReference = FirebaseStorage.getInstance().getReference();

            uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
            final FirebaseDatabase database = FirebaseDatabase.getInstance();
            DatabaseReference ref = database.getReference().child("Users").child(uid);

            ref.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    User user = dataSnapshot.getValue(User.class);

                    final String name = user.getName();
                    final String email  = user.getEmail();
                    final String imageUrl = user.getImageUrl();
                    Uri uri = Uri.parse(imageUrl.toString());

                    SharedPreferences moiPref =  getActivity().getPreferences(Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = moiPref.edit();
                    editor.putString("uriLastSeg", uri.getLastPathSegment());
                    editor.commit();

                    text_name.setText(name);
                    text_email.setText(email);
                    Picasso.with(getContext()).load(imageUrl).into(imageView);
                }
                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("image/*");
                startActivityForResult(intent, GALLERY_INTENT);
            }
        });
        return mView;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == GALLERY_INTENT && resultCode == RESULT_OK) {
            imageUri = data.getData();
            if(imageUri!=null){
                imageUploading();
            }
        }
    }
    private void imageUploading() {
        progressDialog.setMessage("Changing Yo Pic");
        progressDialog.show();
        final SharedPreferences pref = getActivity().getPreferences(Context.MODE_PRIVATE);
        final String id = pref.getString("uriLastSeg", "");
        final StorageReference prevFilepath = storageReference.child("Images").child(id);
        StorageReference filepath = storageReference.child("Images").child(imageUri.getLastPathSegment());
        filepath.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                prevFilepath.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {

                    }
                }).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        progressDialog.dismiss();
                    Toast.makeText(getContext(), "Try Again", Toast.LENGTH_SHORT).show();
                    }
                });
                Uri uri = taskSnapshot.getDownloadUrl();
                final String uid1 = FirebaseAuth.getInstance().getCurrentUser().getUid();
                Map<String,Object> taskMap = new HashMap<String,Object>();
                DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users").child(uid1);

                taskMap.put("imageUrl", uri.toString());

                databaseReference.updateChildren(taskMap);
                progressDialog.dismiss();
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                progressDialog.dismiss();
                Toast.makeText(getContext(), "Try Again!", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

activity_moi__frag.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <android.support.design.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <android.support.design.widget.FloatingActionButton
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/floatingActionButton"
            android:layout_marginTop="150dp"
            android:clickable="true"
            android:backgroundTint="#ffffff"
            android:src="@drawable/ic_mode_edit_black_24dp"
            android:layout_marginStart="230dp"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
            <ImageView
                android:layout_width="match_parent"
                android:layout_height="200dp"
                android:id="@+id/background_image"
                android:src="@drawable/moibackground"
                android:layout_alignParentTop="true"
                android:layout_alignParentStart="true" />

            <de.hdodenhof.circleimageview.CircleImageView
                android:id="@+id/profile_image"
                android:layout_width="150dp"
                android:layout_height="150dp"
                android:src="@drawable/error"
                app:civ_border_width="2dp"
                app:civ_border_color="#FF000000"
                android:layout_marginTop="-50dp"
                android:layout_gravity="center"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Name here"
                android:padding="4dp"
                android:textSize="25dp"
                android:id="@+id/moi_name"
                android:layout_gravity="center"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/moi_email"
                android:textSize="20dp"
                android:padding="4dp"
                android:layout_gravity="center"
                android:text="Email"
                />
        </LinearLayout>
    </android.support.design.widget.CoordinatorLayout>

</ScrollView>

User.java

package com.example.admin.college20;


public class User {
    private String imageUrl, name, email;

    public User() {
    }

    public User(String imageUrl, String name, String email) {
        this.imageUrl = imageUrl;
        this.name = name;
        this.email = email;
    }

    public String getImageUrl() {
        return imageUrl;
    }

    public void setImageUrl(String imageUrl) {
        this.imageUrl = imageUrl;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {this.email = email;}
}

0 个答案:

没有答案