Firebase数据库+ ArrayAdapter无法在我的Android应用中突然更新

时间:2018-10-30 09:13:09

标签: android firebase listview firebase-realtime-database custom-arrayadapter

我是新手,最近了解了 Firebase 。实际上,我有 ListView + ArrayAdapter ,我在其中显示候选列表。启动应用程序时,当前用户的默认数据(图像+名称)将输入到ListView中,并显示为名称+图像(空白,因为我尚未应用)。因此,当我单击“浮动动作”按钮时,它将更新当前用户的图像,并返回到主活动(实现了ListView + ArrayAdapter的活动)。另外,在 Firebase数据库中也正确更新了该Uri之后。

但是问题是图像仍为空白(图像-https://i.stack.imgur.com/8nywY.jpg),当我按下主页按钮并返回或退出并再次登录时,图像显示为(图片-https://i.stack.imgur.com/3X39v.jpg)。它不是同步或突然更改。甚至我正在使用ChildEventListenerarrayAdapter.notifyDataSetChanged(),但是突然发生了变化。

这是我的MainActivity-

    public class MainActivity extends AppCompatActivity {
    private String currentUserId;
    private ArrayList<EachPerson> mEachPersonList;
    private ArrayAdapter<EachPerson> arrayAdapter;
    private FloatingActionButton fab_addImage;
    public static final int RC_SIGN_IN = 1;
    private static final int RC_PHOTO_PICKER =  2;
    static final int RC_IMAGE_CAPTURE = 3;

    private ImageView cardImage;
    private FirebaseAuth mFirebaseAuth;
    private FirebaseDatabase mFirebaseDatabase;
    private DatabaseReference mDatabaseReference;
    private ChildEventListener mChildEventListener;
    private FirebaseAuth.AuthStateListener mAuthStateListener;
    private FirebaseStorage mFirebaseStorage;
    private StorageReference mStorageReference;
    private SwipeFlingAdapterView flingContainer;
    private String mUsername;

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

        mFirebaseAuth = FirebaseAuth.getInstance();
        currentUserId = mFirebaseAuth.getCurrentUser().getUid();
        mFirebaseDatabase = FirebaseDatabase.getInstance();
        mDatabaseReference = mFirebaseDatabase.getReference().child("Users");
        mFirebaseStorage = FirebaseStorage.getInstance();
        mStorageReference = mFirebaseStorage.getReference().child("poll_images");

        cardImage = findViewById(R.id.img_person_cardview);
        onSignedInInitialize();
        fab_addImage = findViewById(R.id.fab_add);
        mEachPersonList = new ArrayList<EachPerson>();
        arrayAdapter = new CustomArrayAdapter(this, R.layout.item, mEachPersonList );
        flingContainer = (SwipeFlingAdapterView)findViewById(R.id.frame);
        flingContainer.setAdapter(arrayAdapter);
        flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
            @Override
            public void removeFirstObjectInAdapter() {}

            @Override
            public void onLeftCardExit(Object dataObject) {}

            @Override
            public void onRightCardExit(Object dataObject) {}

            @Override
            public void onAdapterAboutToEmpty(int itemsInAdapter) {}

            @Override
            public void onScroll(float scrollProgressPercent) {}});

        fab_addImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(Intent.createChooser(intent,"Complete Action Using"),RC_PHOTO_PICKER);}
        });}

    private void onSignedInInitialize() {
        attachDatabaseReadListener();}

    private void attachDatabaseReadListener() {
        if (mChildEventListener == null) {
            mChildEventListener = new ChildEventListener() {
                @Override
                public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                    String pollImageUrl = "default";
                    if (!dataSnapshot.child("pollImages").getValue().equals("default")) {
                        pollImageUrl =dataSnapshot.child("pollImages").getValue().toString();
                    }
                    EachPerson eachPerson = new EachPerson(dataSnapshot.getKey(), dataSnapshot.child("name").getValue().toString(), pollImageUrl,0);
                    mEachPersonList.add(eachPerson);
                    arrayAdapter.notifyDataSetChanged();
                }
                public void onChildChanged(DataSnapshot dataSnapshot, String s) {}
                public void onChildRemoved(DataSnapshot dataSnapshot) {}
                public void onChildMoved(DataSnapshot dataSnapshot, String s) {}
                public void onCancelled(DatabaseError databaseError) {}
            };
            mDatabaseReference.addChildEventListener(mChildEventListener);
        }
}

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RC_SIGN_IN) {
            if (resultCode == RESULT_OK) {
                Toast.makeText(this, "Signed in!", Toast.LENGTH_SHORT).show();
            } else if (resultCode == RESULT_CANCELED) {
                Toast.makeText(this, "Sign in canceled", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
        else if(requestCode==RC_PHOTO_PICKER && resultCode==RESULT_OK){
            Uri imageUri = data.getData(); //image will be return back as the uri
            final StorageReference photoRef = mStorageReference.child(imageUri.getLastPathSegment());
            UploadTask uploadTask = photoRef.putFile(imageUri);
            uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
                @Override
               public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
                    if (!task.isSuccessful()) {
                        throw task.getException();
                   }
                   return photoRef.getDownloadUrl();
               }
            }).addOnCompleteListener(new OnCompleteListener<Uri>() {
               @Override
               public void onComplete(@NonNull Task<Uri> task) {
                   if (task.isSuccessful()) {
                       Uri downloadUri = task.getResult();

                       mDatabaseReference = mFirebaseDatabase.getReference().child("Users").child(currentUserId).child("pollImages");
                       mDatabaseReference.setValue(downloadUri.toString());
                       arrayAdapter.notifyDataSetChanged();
                    } else {// Handle failures}
                }
            });
        }
        attachDatabaseReadListener();
    }

    private void onSignedOutCleanup() {
        arrayAdapter.clear();
        detachDatabaseReadListener();}

    private void detachDatabaseReadListener() {
        if (mChildEventListener != null) {
            mDatabaseReference.removeEventListener(mChildEventListener);
            mChildEventListener = null;
        }}
}

0 个答案:

没有答案