在FirebaseAdapter中从Listview删除或隐藏列表项

时间:2018-11-24 22:59:24

标签: java android firebase firebase-realtime-database android-adapter

我正在开发一个用于查找附近捐助者的应用程序。如果有用户需要血液,则可以张贴血液。在通知片段中,用户将看到谁需要哪种血液?我想使用firebaseAdapter从通知表中创建列表视图,但是我希望用户不会收到他/她的通知。这就是为什么在populateView()中我检查了finder(谁在张贴血液)的ID和当前用户的ID是否匹配..如果匹配,我将用于listview VIEW.GONE的布局的父布局...这有助于隐藏当前用户的通知,但列表中的项目仍为空...这就是为什么在之后添加下一个项目的原因空项目..如何删除空项目或隐藏当前用户的通知

  

通知片段

package com.blz.prisoner.lifeshare;


import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.firebase.client.Firebase;
import com.firebase.ui.database.FirebaseListAdapter;
import com.firebase.ui.database.FirebaseListOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


/**
 * A simple {@link Fragment} subclass.
 */
public class NotificationsFragment extends Fragment {

    SwipeMenuListView listView;
    FirebaseListAdapter adapter;
    TextView notif_text,time_text,address_text,distance_text,phone;

    LinearLayout notification_linear;
    Query query;
    View rootView;

    FirebaseListOptions<NotificationData> options;

   /* List<Integer> list_position = new ArrayList<Integer>();*/

    FirebaseAuth firebaseAuth;
    GPSTracker gps;
    String lattitude,longtitude,phoneCall;
    double latt1,longt1,latt2,longt2;


    public NotificationsFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setHasOptionsMenu(true);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment


        rootView =inflater.inflate(R.layout.fragment_donors, container, false);

        listView = rootView.findViewById(R.id.listview);

        firebaseAuth = FirebaseAuth.getInstance();
        gps = new GPSTracker(getActivity());

        latt1 = gps.getLatitude();
        longt1 = gps.getLongitude();

        query =FirebaseDatabase.getInstance().getReference().child("Notifications");

        setQuery(query);




        SwipeMenuCreator creator = new SwipeMenuCreator() {

            @Override
            public void create(SwipeMenu menu) {

                // create "delete" item
                SwipeMenuItem deleteItem = new SwipeMenuItem(getActivity());
                // set item background
                deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
                        0x3F, 0x25)));
                // set item width
                deleteItem.setWidth(170);
                // set a icon
                deleteItem.setIcon(R.drawable.ic_phone);
                // add to menu
                menu.addMenuItem(deleteItem);
            }
        };

        listView.setMenuCreator(creator);


        listView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
                switch (index) {
                    case 0:
                        // open
                        String s ="tel:"+phoneCall;

                        Intent intent = new Intent(Intent.ACTION_DIAL);
                        intent.setData(Uri.parse(s));
                        startActivity(intent);



                        break;
                }
                // false : close the menu; true : not close the menu
                return false;
            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView txt = view.findViewById(R.id.phone);

                phoneCall = txt.getText().toString();
                Toast.makeText(getActivity(),listView.getItemAtPosition(position).toString(),Toast.LENGTH_SHORT).show();
            }
        });

        /*
        }*/



        //
        return rootView;
    }


    @Override
    public void onStart() {
        super.onStart();
        adapter.startListening();
    }

    @Override
    public void onStop() {
        super.onStop();
        adapter.stopListening();
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.blood_group_menu,menu);
    }

    public void setQuery(Query query){
        /*list_position.clear();*/



        options = new FirebaseListOptions.Builder<NotificationData>()
                .setLayout(R.layout.notificatiion_list)
                .setQuery(query,NotificationData.class)
                .build();

        adapter = new FirebaseListAdapter(options) {

            @Override
            protected void populateView(@NonNull View v, @NonNull Object model, int position) {
                NotificationData notif = (NotificationData) model;

                notification_linear = v.findViewById(R.id.notification_linear);





                if (notif.getUserid().toString().equals(firebaseAuth.getUid())){
                    notification_linear.setVisibility(View.GONE);
                    /*list_position.add(position);*/
                    /*Toast.makeText(getActivity(),Integer.toString(position),Toast.LENGTH_SHORT).show();*/
                }



                else if(!notif.getUserid().toString().equals(firebaseAuth.getUid())){
                    listView.setVisibility(View.VISIBLE);

                    notif_text = v.findViewById(R.id.notif_text);
                    time_text = v.findViewById(R.id.time_text);
                    address_text = v.findViewById(R.id.address_text);
                    distance_text = v.findViewById(R.id.distance_text);

                    phone = v.findViewById(R.id.phone_text);


                    String txt;
                    txt = notif.getFullName() + " Needs " + notif.getBloodGroup() + "Blood";



                    notif_text.setText(txt);
                    address_text.setText(notif.getAddress().toString());


                    phone.setText(notif.getPhone().toString());

                    lattitude = notif.getLattitude();
                    longtitude = notif.getLongitude();

                    latt2 = Double.parseDouble(lattitude);
                    longt2 = Double.parseDouble(longtitude);

                    float dist;
                    float[] result = new float[1];

                    android.location.Location.distanceBetween(latt1,longt1,latt2,longt2, result);

                    if(result.length>=1){

                        DecimalFormat df = new DecimalFormat();
                        df.setMaximumFractionDigits(2);
                        dist = result[0]/1000;
                        /*Toast.makeText(MainActivity.this,Float.toString(dist),Toast.LENGTH_LONG).show();*/
                        distance_text.setText(df.format(dist) + " Km");
                    }

                    Calendar calendar = Calendar.getInstance();
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yy HH:mm:ss");

                    String dateStop = simpleDateFormat.format(calendar.getTime());
                    String dateStart = notif.getDateTime();

                    Date d1 = null;
                    Date d2 = null;

                    try {
                        d1 = simpleDateFormat.parse(dateStart);
                        d2 = simpleDateFormat.parse(dateStop);

                        //in milliseconds
                        long diff = d2.getTime() - d1.getTime();

                       /* long diffSeconds = diff / 1000 % 60;*/
                        long diffMinutes = diff / (60 * 1000) % 60;
                        long diffHours = diff / (60 * 60 * 1000) % 24;
                        long diffDays = diff / (24 * 60 * 60 * 1000);

                        if(diffMinutes<1){
                            time_text.setText("Now");
                        }

                        else if(diffMinutes>=1 && diffMinutes<60){
                            time_text.setText(Long.toString(diffMinutes) + " Minutes Ago");

                        }

                        else if(diffMinutes>=60 && diffHours<24){
                            time_text.setText(Long.toString(diffHours) + " Hours Ago");
                        }

                        else if(diffHours>=24){
                            time_text.setText(Long.toString(diffDays) + " Days Ago");
                        }


                    } catch (Exception e) {
                        e.printStackTrace();
                    }



                }

            }
        };

        listView.setAdapter(adapter);
        adapter.startListening();




    }


}
  

notification_fragment XML

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".NotificationsFragment">

    <com.baoyz.swipemenulistview.SwipeMenuListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="invisible">

    </com.baoyz.swipemenulistview.SwipeMenuListView>

</FrameLayout>

notificatiion_list布局用于创建列表视图

  

notificatiion_list XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingStart="15dp"
    android:paddingLeft="15dp"
    android:paddingEnd="10dp"
    android:paddingRight="10dp"
    android:paddingBottom="15dp"
    android:background="@drawable/profile_backgroud"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Bishal Imtiaz Needs AB+ Blood"
            android:layout_weight="8"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="20 minutes"
            android:layout_weight="1"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Ago"
            android:layout_weight="1"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="20 minutes"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Ago"/>
    </LinearLayout>


</LinearLayout>

NotificationData类用于存储Firebase数据

  

NotificationData类JAVA

package com.blz.prisoner.lifeshare;

public class NotificationData {

    String fullName;
    String dateTime;
    String bloodGroup;
    String phone;
    String lattitude;
    String longitude;
    String address;

    public String getUserid() {
        return userid;
    }

    public void setUserid(String userid) {
        this.userid = userid;
    }

    String userid;

    public String getLattitude() {
        return lattitude;
    }

    public void setLattitude(String lattitude) {
        this.lattitude = lattitude;
    }

    public String getLongitude() {
        return longitude;
    }

    public void setLongitude(String longitude) {
        this.longitude = longitude;
    }

    public NotificationData(String fullName, String dateTime, String bloodGroup, String phone, String address, String lattitude, String longitude,String userid) {
        this.fullName = fullName;
        this.dateTime = dateTime;
        this.bloodGroup = bloodGroup;
        this.phone = phone;
        this.lattitude = lattitude;

        this.longitude = longitude;
        this.address = address;
        this.userid = userid;
    }

    public NotificationData(){
        //empty constructor
    }



    public String getFullName() {
        return fullName;
    }

    public void setFullName(String fullName) {
        this.fullName = fullName;
    }

    public String getDateTime() {
        return dateTime;
    }

    public void setDateTime(String dateTime) {
        this.dateTime = dateTime;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getBloodGroup() {
        return bloodGroup;

    }

    public void setBloodGroup(String bloodGroup) {
        this.bloodGroup = bloodGroup;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }
}

这是输出的屏幕截图 enter image description here

我不希望上面有这些空项目。.我需要解决方案..如果您有其他选择,请告诉我,因为我是noob开发人员:(

1 个答案:

答案 0 :(得分:0)

使用FirebaseListAdapter时,将为该位置的每个孩子调用populateView()方法。这意味着您正在查看每个孩子。不幸的是,您无法选择是否为该项目显示视图。

您似乎假设您在if方法中使用的populateView()语句将跳过这些项目,但实际上发生的是您只是在允许空白视图占据列表中的那个位置。

要解决此问题,您可以做的是创建一个查询,该查询只生成列表中感兴趣的项目。这意味着您必须告诉Firebase filter for children符合您的条件。

还有另一种方法,您必须阅读该位置的全部内容,手动过滤掉列表中不需要的项目,并建立一个新的项目列表。然后,您可以使用该列表构建一个Adapter,然后它就可以成为ListView(或更好的RecyclerView)的输入。