首页 > 解决方案 > Firebase 数据库 + ArrayAdapter 在我的 Android 应用程序中没有突然更新

问题描述

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

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

这是我的主要活动-

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

标签: androidfirebaselistviewfirebase-realtime-databasecustom-arrayadapter

解决方案


推荐阅读