2017-08-23 4 views
1

MainActivityl'image Récupération de firebase montre même image plusieurs fois

public class MainActivity extends AppCompatActivity { 

    private static final String TAG = "MainActivity"; 

    public static final String ANONYMOUS = "anonymous"; 
    public static final int RC_SIGN_IN = 1; 
    private static final int RC_PHOTO_PICKER = 2; 
    private String mUsername; 

    // Firebase instance variables 
    private FirebaseDatabase mFirebaseDatabase; 
    private DatabaseReference mMessagesDatabaseReference; 
    private ChildEventListener mChildEventListener; 
    private FirebaseAuth mFirebaseAuth; 
    private FirebaseAuth.AuthStateListener mAuthStateListener; 
    private FirebaseStorage mFirebaseStorage; 
    private StorageReference mChatPhotosStorageReference; 
    private FirebaseRemoteConfig mFirebaseRemoteConfig; 
    private ProgressBar progressBar; 

    private RecyclerView recyclerView; 
    private FloatingActionButton floatingActionButton; 

    PhotosAdapter contactsAdapter; 
    List<Photos> contactList; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     progressBar=(ProgressBar)findViewById(R.id.progressbar); 
     mUsername = ANONYMOUS; 
     recyclerView=(RecyclerView)findViewById(R.id.recyclerview); 
     floatingActionButton=(FloatingActionButton)findViewById(R.id.floatingactionbutton); 
     contactList = new ArrayList(); 
     progressBar.setVisibility(View.GONE); 
     // Initialize Firebase components 
     mFirebaseDatabase = FirebaseDatabase.getInstance(); 
     mFirebaseAuth = FirebaseAuth.getInstance(); 
     mFirebaseStorage = FirebaseStorage.getInstance(); 
     mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance(); 


     mMessagesDatabaseReference = mFirebaseDatabase.getReference().child("messages"); 
     mChatPhotosStorageReference = mFirebaseStorage.getReference().child("chat_photos"); 

     mAuthStateListener = new FirebaseAuth.AuthStateListener() { 
      @Override 
      public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { 
       FirebaseUser user = firebaseAuth.getCurrentUser(); 
       if (user != null) { 
        // User is signed in 
        onSignedInInitialize(user.getDisplayName()); 
       } else { 
        // User is signed out 
        onSignedOutCleanup(); 
        startActivityForResult(
          AuthUI.getInstance() 
            .createSignInIntentBuilder() 
            .setIsSmartLockEnabled(false) 
            .setProviders(
              AuthUI.EMAIL_PROVIDER, 
              AuthUI.GOOGLE_PROVIDER) 
            .build(), 
          RC_SIGN_IN); 
       } 
      } 
     }; 




     floatingActionButton.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
       intent.setType("image/jpeg"); 
       intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true); 
       startActivityForResult(Intent.createChooser(intent, "Complete action using"), RC_PHOTO_PICKER); 

      } 
     }); 


     mMessagesDatabaseReference.addValueEventListener(new ValueEventListener() { 
      @Override 
      public void onDataChange(DataSnapshot snapshot) { 

       for (DataSnapshot postSnapshot : snapshot.getChildren()) { 

        Photos imageUploadInfo = postSnapshot.getValue(Photos.class); 
        if(!contactList.contains(imageUploadInfo)){ 
         contactList.add(imageUploadInfo); 
         Log.i(TAG, "onDataChange: "+contactList); 
        } 

       } 

       contactsAdapter=new PhotosAdapter(contactList,getApplicationContext()); 
       progressBar.setVisibility(View.GONE); 

       recyclerView.setAdapter(contactsAdapter); 

      } 

      @Override 
      public void onCancelled(DatabaseError databaseError) { 



      } 
     }); 

     recyclerView.setLayoutManager(new GridLayoutManager(getApplicationContext(),5)); 
    } 


    @Override 
    public void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 
     if (requestCode == RC_SIGN_IN) { 
      if (resultCode == RESULT_OK) { 
       // Sign-in succeeded, set up the UI 
       Toast.makeText(this, "Signed in!", Toast.LENGTH_SHORT).show(); 
      } else if (resultCode == RESULT_CANCELED) { 
       // Sign in was canceled by the user, finish the activity 
       Toast.makeText(this, "Sign in canceled", Toast.LENGTH_SHORT).show(); 
       finish(); 
      } 
     }else if (requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK) { 
      Uri selectedImageUri = data.getData(); 

      // Get a reference to store file at chat_photos/<FILENAME> 
      StorageReference photoRef = mChatPhotosStorageReference.child(selectedImageUri.getLastPathSegment()); 

      // Upload file to Firebase Storage 
      photoRef.putFile(selectedImageUri) 
        .addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() { 
         public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { 
          // When the image has successfully uploaded, we get its download URL 
          // progressBar.setVisibility(View.VISIBLE); 
          Uri downloadUrl = taskSnapshot.getDownloadUrl(); 

          // Set the download URL to the message box, so that the user can send it to the database 
          Photos friendlyMessage = new Photos(downloadUrl.toString()); 
          mMessagesDatabaseReference.push().setValue(friendlyMessage); 
         } 
        }); 
     } 
    } 
    @Override 
    protected void onResume() { 
     super.onResume(); 
     mFirebaseAuth.addAuthStateListener(mAuthStateListener); 
    } 

    @Override 
    protected void onPause() { 
     super.onPause(); 
     if (mAuthStateListener != null) { 
      mFirebaseAuth.removeAuthStateListener(mAuthStateListener); 
     } 
    } 

    private void onSignedInInitialize(String username) { 
     mUsername = username; 

    } 

    private void onSignedOutCleanup() { 
     mUsername = ANONYMOUS; 

    } 
} 

Supposons que je télécharger une image pour le stockage Firebase, il obtient récupéré dans mon imageview de recyclerview en application. Lorsque je télécharge une deuxième image, la première image s'affiche deux fois et la deuxième image une fois dans mon application. Lorsque je télécharge une troisième image, la première image s'affiche trois fois, la deuxième image deux fois et la troisième image une fois. Je sais que le problème est dans mMessagesDatabaseReference.addValueEventListener mais je ne suis pas capable de le comprendre. S'il vous plaît aidez-moi ..

Répondre

1

Je suppose que onDataChange sera appelé avec toutes les données à chaque nouveau téléchargement. Donc, vous devez effacer contactList avant d'ajouter des éléments, comme:

public void onDataChange(DataSnapshot snapshot) { 
    contactList.clear() 

    for (DataSnapshot postSnapshot : snapshot.getChildren()) { 
     Photos imageUploadInfo = postSnapshot.getValue(Photos.class); 
     if(!contactList.contains(imageUploadInfo)){ 
      contactList.add(imageUploadInfo); 
      Log.i(TAG, "onDataChange: "+contactList); 
     } 
    } 

    contactsAdapter=new PhotosAdapter(contactList,getApplicationContext()); 
    progressBar.setVisibility(View.GONE); 

    recyclerView.setAdapter(contactsAdapter); 
} 
0

utilisation ChildEventListener au lieu de value event listener. L'écouteur d'événements de valeur récupère à nouveau toutes les données sur une seule modification, de sorte que pour l'ajout de l'image 2, l'image 1 sera également reçue en cas d'événement de valeur. Dans ChildEventListener il y a la méthode onChildAdded() où vous ajoutez à votre recycleur.

Utilisez l'écouteur d'événement enfant comme celui-ci, pas besoin de boucle, elle sera appelée quand un enfant est ajouté, en évitant le besoin de faire une boucle

également après avoir ajouté l'article n'oubliez pas d'appeler informer sur recyclerAdapter pour montrer les changements sur vue

Déplacer ces dans la méthode onCreate et intialize là:

contactList = new ArrayList(); 
contactsAdapter=new PhotosAdapter(contactList,getApplicationContext()); 

recyclerView.setAdapter(contactsAdapter); 

code pour obtenir de l'enfant firebase

private void attachDatabaseReadListener() { 
     if (mChildEventListener == null) { 
      mChildEventListener = new ChildEventListener() { 
       @Override 
       public void onChildAdded(DataSnapshot dataSnapshot, String s) { 
         Photos imageUploadInfo = dataSnapshot.getValue(Photos.class); 
         if (!contactList.contains(imageUploadInfo)) { 
          contactList.add(imageUploadInfo); 
         } 

       } 

       @Override 
       public void onChildChanged(DataSnapshot dataSnapshot, String s) { 

       } 

       @Override 
       public void onChildRemoved(DataSnapshot dataSnapshot) { 

       } 

       @Override 
       public void onChildMoved(DataSnapshot dataSnapshot, String s) { 

       } 

       @Override 
       public void onCancelled(DatabaseError databaseError) { 

       } 
      } 
      mMessagesDatabaseReference.addChildEventListener(mChildEvent‌​Listener); 
     } 
    } 
+0

attachDatabaseReadListener private void() {if (mChildEventListener == null) {mChildEventListener = new ChildEventListener() { @Override public void onChildAdded (DataSnapshot dataSnapshot, String s) { pour (DataSnapshot postSnapshot: dataSnapshot.getChildren()) { Photos imageUploadInfo = postSnapshot.getValue (Photos.class); if (! ContactList.contains (imageUploadInfo)) { contactList.add (imageUploadInfo);} }} mMessagesDatabaseReference.addChildEventListener (mChildEventListener); }} –

+0

L'image ne sera pas ajoutée dans mon application –

+0

voir mes modifications dans la réponse –