2017-04-17 161 views
1

我有一個書籍列表視圖,我通過點擊項目和它的工作來更新列表視圖,但是我有重複的項目,舊的和新的。在我的數據庫中,我只有新的數據。我怎樣才能修改我的列表視圖?我正在使用FireBase數據庫。更新dataBase後更新listView?

更新我的性的來源:

public class ListOfMyBookActivity extends AppCompatActivity { 

//The elements are initialized here 

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

     listView = (ListView) findViewById(R.id.list_book); 

     feedItems = new ArrayList<Book>(); 
     dataBD= FirebaseDatabase.getInstance(); 
     dataBaseD=FirebaseDatabase.getInstance(); 
     updateDB=FirebaseDatabase.getInstance(); 
     ref = dataBD.getReference("books"); 
     refdelete=dataBaseD.getReference("books"); 
     refUpdate=updateDB.getReference("books"); 
     auth = FirebaseAuth.getInstance(); 
     mDatabase = FirebaseDatabase.getInstance().getReference("books"); 


      ref.orderByChild("date_creation").limitToLast(10).addValueEventListener(new ValueEventListener() { 
       @Override 
       public void onDataChange(DataSnapshot dataSnapshot) { 



        List<String> list = new ArrayList<String>(); 
        for (DataSnapshot dataSnap : dataSnapshot.getChildren()) { 

         Book valueBook = dataSnap.getValue(Book.class); 
         keyId = dataSnap.getKey(); 

         String userBd = valueBook.getId_user(); 
         if (userBd.equalsIgnoreCase(id_user)) { 
          String titreLivreToDisplay = valueBook.getNom_livre(); 
          String descLivreToDisplay = valueBook.getDesc_livre(); 
          String prixLivreToDisplay = valueBook.getPrix_livre(); 
          String timeToDisplay = valueBook.getDate_creation(); 
          String filePathToDiplay = valueBook.getChemin_image(); 
          String villeToDisplay = valueBook.getVille_livre(); 
          String typeAnnToDisplat = valueBook.getType_annonce_selected(); 
          String bookid = valueBook.getId_book(); 



          item = new Book(); 
          item.setNom_livre(titreLivreToDisplay); 
          item.setDesc_livre(descLivreToDisplay); 
          item.setPrix_livre(prixLivreToDisplay); 
          item.setDate_creation(timeToDisplay); 
          item.setChemin_image(filePathToDiplay); 
          item.setVille_livre(villeToDisplay); 
          item.setType_annonce_selected(typeAnnToDisplat); 
          item.setId_book(bookid); 
          item.setKeyIdNode(keyId); 

          feedItems.add(item); 


         } 

         Collections.reverse(feedItems); 


         listAdapter = new MyBookListAdapter(ListOfMyBookActivity.this, feedItems); 

         listView.setAdapter(listAdapter); 

         listView.setOnItemClickListener(myClickListener); 

         listAdapter.notifyDataSetChanged(); 


        }} 



      }); 


    } 


    public AdapterView.OnItemClickListener myClickListener = new AdapterView.OnItemClickListener() { 

     @Override 
     public void onItemClick(AdapterView<?> arg0, View arg1, 
           final int position, long arg3) { 
      deleteItem = position; 
      // The AlertDialog is created programmatically 
      AlertDialog.Builder alert = new AlertDialog.Builder(arg1.getContext()); 

      nameBookEdtDlg.setText(nom); 
      descBookEdtDlg.setText(desc); 
      prixBookEdtDlg.setText(prix); 

       alert.setPositiveButton("Update ", 
         new DialogInterface.OnClickListener() 

       { 
        public void onClick (DialogInterface dialog, 
        int whichButton){ 


        Query query = refUpdate.orderByChild("id_book").equalTo(bookID); 

        query.addListenerForSingleValueEvent(new ValueEventListener() { 

         @Override 
         public void onDataChange(DataSnapshot dataSnapshot) { 

          prixSt=prixBookEdtDlg.getText().toString(); 
          descSt=descBookEdtDlg.getText().toString(); 
          namSt=nameBookEdtDlg.getText().toString(); 


          Map<String, Object> result = new HashMap<String, Object>(); 
          result.put("nom_livre", namSt); 
          result.put("desc_livre", descSt); 
          result.put("prix_livre", prixSt); 
          result.put("date_creation", currentDateandTimeUpdate); 
          refUpdate.child(keyId).updateChildren(result); 

          listAdapter.notifyDataSetChanged(); 

         } }); 

      AlertDialog alertDialog = alert.create(); 

       try{alertDialog.show();} } };} 
       } 

} 

適配器:

public class MyBookListAdapter extends BaseAdapter { 


    public MyBookListAdapter(ListOfMyBookActivity listMyBooks, List<Book> feedItemsBooks) { 
     this.activity = listMyBooks; 
     this.feedItemsBooks = feedItemsBooks; 
    } 
    @Override 
    public int getCount() { 
     return feedItemsBooks.size(); 
    } 

    @Override 
    public Object getItem(int location) { 
     return feedItemsBooks.get(location); 
    } 

    @Override 
    public long getItemId(int position) { 
     return position; 
    } 

    @Override 
    public View getView(int position, View convertView, final ViewGroup parent) { 
     final int pos = position; 

     if (inflater == null) { 
      inflater = (LayoutInflater) activity 
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     } 
     if (convertView == null) { 
      convertView = inflater.inflate(R.layout.feed_list_item, null); 

     } 
     storageDisplayImg = FirebaseStorage.getInstance(); 
     auth = FirebaseAuth.getInstance(); 
     FirebaseUser userConnect = auth.getCurrentUser(); 
     String id_user = userConnect.getUid(); 
     mFirebaseInstance = FirebaseDatabase.getInstance(); 
     mFirebaseDatabase = mFirebaseInstance.getReference("books"); 


     final ImageView profilePic = (ImageView) convertView.findViewById(R.id.book_picture_display_myBook); 
     name = (TextView) convertView.findViewById(R.id.name_book_display_myBook); 
     TextView timestamp = (TextView) convertView.findViewById(R.id.timestamp_myBook); 
     statusMsg = (TextView) convertView.findViewById(R.id.desc_display_myBook); 
     prix = (TextView) convertView.findViewById(R.id.prix_display_myBook); 
     TextView ville = (TextView) convertView.findViewById(R.id.ville_display_myBook); 
     TextView typeCat = (TextView) convertView.findViewById(R.id.type_ann_to_display_myBook); 


     Book item = feedItemsBooks.get(position); 



     idLivreListAdapter=item.getId_book(); 

     name.setText(item.getNom_livre()); 

     if (!TextUtils.isEmpty(item.getDate_creation())) { 
      timestamp.setText(item.getDate_creation()); 
      timestamp.setVisibility(View.VISIBLE); 
     } else { 
      timestamp.setVisibility(View.GONE); 
     } 

     if (!TextUtils.isEmpty(item.getDesc_livre())) { 
      statusMsg.setText(item.getDesc_livre()); 
      statusMsg.setVisibility(View.VISIBLE); 
     } else { 
      statusMsg.setVisibility(View.GONE); 
     } 

     if (!TextUtils.isEmpty(item.getType_annonce_selected())) { 
      typeCat.setText(item.getType_annonce_selected()); 
      typeCat.setVisibility(View.VISIBLE); 
     } else { 
      typeCat.setVisibility(View.GONE); 
     } 


     if (item.getPrix_livre() != null) { 
      prix.setText(item.getPrix_livre() + " DH"); 
      prix.setVisibility(View.VISIBLE); 
     } else { 
      prix.setVisibility(View.GONE); 
     } 

     if (item.getVille_livre() != null) { 

      ville.setText(item.getVille_livre()); 
      ville.setVisibility(View.VISIBLE); 
     } else { 
      ville.setVisibility(View.GONE); 
     } 

     storageRef = storageDisplayImg.getReferenceFromUrl(item.getChemin_image()); 
     Log.e(" ", " storageRef " + storageRef.toString()); 

     if (item.getChemin_image() != null && id_user != null) { 


      Glide.with(convertView.getContext()) 
        .using(new FirebaseImageLoader()) 
        .load(storageRef) 
        .into(profilePic); 
      profilePic.setVisibility(View.VISIBLE); 

     } else { 
      profilePic.setVisibility(View.GONE); 
     } 


     return convertView; 
    } 



} 

我的問題不重複我想提出的解決方案,但它不工作。

+0

使用光標適配器和chnageCursor(),您可以從https://github.com/codepath/android_guides/wiki得到例如後/填充一個帶有CursorAdapter的ListView – rajahsekar

+0

嘗試製作[mcve]。你還沒有在問題中定義'lidtAdapter'。你也沒有visiblly修改列表,以便通知方法做任何事 –

+0

@raj Sqlite這裏沒有使用 –

回答

0

嘗試

feedItems.remove(position); 
    // listView.invalidateViews(); 
    arrayAdapter.notifyDataSetChanged(); 
+0

它不起作用 – Amal

+0

@Amal試試這個feedItems.remove(position); listView.invalidateViews(); –

+0

它的工作原理,但參考這個答案它不是一個好主意[鏈接](http://stackoverflow.com/a/16708283/3023772) – Amal

-1

時使用此更新列表 notifyDataSetChanged()

+0

'listAdapter.notifyDataSetChanged();'已經在問題 –

1

使用feedItems.clear()firebase獲得更新數據之前。

試試這個:

ref.orderByChild("date_creation").limitToLast(10).addValueEventListener(new ValueEventListener() { 

    @Override 
    public void onDataChange(DataSnapshot dataSnapshot) { 

     feedItems.clear(); 

     ............. 
     .................. 
    } 
}); 
2

不知道這一點,如果你的問題,但大部分火力代碼不是所有必要的...

通知你打電話getNom_livre(及其他)然後撥打setNom_livre(和其他人)具有完全相同的值?
如果您已經有一個,也可以製作一個new Book

Book valueBook = dataSnap.getValue(Book.class); // This is a Book 
keyId = dataSnap.getKey(); 

String userBd = valueBook.getId_user(); 
if (userBd.equalsIgnoreCase(id_user)) { 
    String titreLivreToDisplay = valueBook.getNom_livre(); 
    ... 

    item = new Book(); // Why do you need a new one? 
    item.setNom_livre(titreLivreToDisplay); 
    ... 

    feedItems.add(item); 
} 

首先,你應該在火力方法之前移動這一點。每次數據更新都不需要重新創建適配器。

listAdapter = new MyBookListAdapter(ListOfMyBookActivity.this, feedItems); 
listView.setAdapter(listAdapter); 
listView.setOnItemClickListener(myClickListener); 

ref.orderByChild("date_creation")... 

,但我有重複項目,舊的和新的

你只需要清除適配器刪除舊數據,並添加新的東西

ref.orderByChild("date_creation") 
    .limitToLast(10) 
    .addValueEventListener(new ValueEventListener() { 
     @Override 
     public void onDataChange(DataSnapshot dataSnapshot) { 
      // Remove old data 
      feedItems.clear(); 

      // Add new data 
      for (DataSnapshot dataSnap : dataSnapshot.getChildren()) { 

       Book valueBook = dataSnap.getValue(Book.class); 
       keyId = dataSnap.getKey(); 

        String userBd = valueBook.getId_user(); 
        if (userBd.equalsIgnoreCase(id_user)) { 
         valueBook.setKeyIdNode(keyId); 
         feedItems.add(valueBook); 
        } 
      } 
      Collections.reverse(feedItems); 
      listAdapter.notifyDataSetChanged(); // Tell adapter of new data 
+0

我第一次使用firebase,謝謝你的觀察,我會考慮一下。 – Amal

0

在您的適配器中使用它

public void dataSetChanged(ArrayList<Movie>list) 
    { 
     this.list=list; 
     this.notifyDataSetChanged(); 
    } 

,並使用它像這樣 UPADTE列表數據及以下線路在使用

customListViewAdapter.dataSetChanged(movieList);