适配器中显示的空值+添加到数据库中的项目,但适配器中的单个项目

时间:2019-04-10 20:25:02

标签: java android firebase firebase-realtime-database

所以我的问题是,当我添加新项目时,它会添加到单个用户下的firebase数据库中,但是当我尝试在同一用户下添加新项目时,它将添加到数据库中,但不会显示在适配器由于某种原因 另外,它说user.getUid,这意味着它应该对用户是私有的,只有该用户才能看到它,但是当我尝试与另一个用户一起输入时,即使不是他的项目,我仍然可以看到该项目。 我的目标是:我希望每个用户都有自己的私人物品,而其他用户则不应看到这些物品,而只能看到自己的私人物品。

以下是数据在数据库中的显示方式:

users
    user
        jnMqdr8iLAXSrv9xfsmW7E8WmLS2
            -Lc7aYrmqc9EiXCL6F1V
                color: key
                "1"    value
                model: key
                "2o17" value
                price: key
                1      value
                version: key
                "1"      value
            -Lc7aa9nCWcFVkGETFKW
                color: key
                "1"    value
                model: key
                "2o17" value
                price: key
                1      value
                version: key
                "1"      value

因此您可以看到这些值已实现,但在适配器内部始终为null。

    public class AddActivity extends AppCompatActivity{


    private static final Integer Array = 0;
    private Spinner spModel;
    private EditText etPrice, etVersion, etColor;
    private String key;
    private FirebaseDatabase database;
    private FirebaseUser user;
    private FirebaseAuth auth;
    private SpecificAdapterManager sam;
    private RecyclerView rv;
    private DatabaseReference reference;

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

        spModel = (Spinner) findViewById(R.id.spModel);
        etVersion = findViewById(R.id.etVersion);
        etColor = findViewById(R.id.etColor);
        etPrice = findViewById(R.id.etPrice);
        rv = findViewById(R.id.rvCars);
        database = FirebaseDatabase.getInstance();
        reference = database.getReference("users");
        auth = FirebaseAuth.getInstance();
        key = getIntent().getStringExtra("key");
        String model = getIntent().getStringExtra("model");
        String version = getIntent().getStringExtra("version");
        String color = getIntent().getStringExtra("color");
        String price = getIntent().getStringExtra("price");






    }


    public void onAddClick(View view)
    {

            String version = etVersion.getText().toString();
            final String model = spModel.getSelectedItem().toString();
            String color = etColor.getText().toString();
            int price = Integer.parseInt(etPrice.getText().toString());


            user = auth.getCurrentUser();
            final Specific specific = new Specific(version, model, color, price);

        String key = reference.push().getKey();
        assert key != null;
        reference.child("user").child(user.getUid()).child(key).setValue(specific).addOnSuccessListener(new OnSuccessListener<Void>()
        {
            @Override
            public void onSuccess(Void aVoid)
            {
                Toast.makeText(AddActivity.this, "Car Added Successfully!",
                        Toast.LENGTH_SHORT).show();
            }
        });}}




  public class FirebaseDBAccess2{

    private FirebaseDatabase database;
    private DatabaseReference reference;
    public FirebaseDBAccess2()
    {
            database = FirebaseDatabase.getInstance();
            reference = database.getReference("users");
    }

    // Get dataChangeListener to get an object of that type
    public void readData(final FirebaseDBAccess2.DataChangeListener dataChangeListener)
    {
        reference.addValueEventListener(new ValueEventListener()
        {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot)
            {


                List<String> keys = new ArrayList<>();
                List<Specific> specifics = new ArrayList<>();

                for (DataSnapshot ds : dataSnapshot.getChildren()) {



                        String key = ds.getKey();
                        Specific specific = ds.getValue(Specific.class);

                        keys.add(key);
                        specifics.add(specific);



                    }

                dataChangeListener.dataChanged(keys, specifics);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError)
            {

            }
        });


    }


    public void addCar(String key, Specific specific, final FirebaseDBAccess2.DataChangeListener dataChangeListener)
    {
        reference.child(key).setValue(specific).addOnSuccessListener(new OnSuccessListener<Void>()
        {
            @Override
            public void onSuccess(Void aVoid)
            {
                dataChangeListener.onAddSuccess();
            }
        });
    }

    public void updateCar(String key, Specific specific, final FirebaseDBAccess2.DataChangeListener dataChangeListener)
    {
        reference.child(key).setValue(specific).addOnSuccessListener(new OnSuccessListener<Void>()
        {
            @Override
            public void onSuccess(Void aVoid)
            {
                dataChangeListener.onUpdateSuccess();
            }
        });
    }

    public void deleteCar(String key, final FirebaseDBAccess2.DataChangeListener dataChangeListener)
    {
        reference.child(key).setValue(null).addOnSuccessListener(new OnSuccessListener<Void>()
        {
            @Override
            public void onSuccess(Void aVoid)
            {
                dataChangeListener.onDeleteSuccess();
            }
        });
    }




    public interface DataChangeListener
    {
        void dataChanged(List<String> keys, List<Specific> specifics);
        void onUpdateSuccess();
        void onDeleteSuccess();
        void onAddSuccess();
    }
}















public class SpecificCar extends AppCompatActivity
{




    private RecyclerView rvCars;
    private TextView getBrand;
    private FirebaseAuth auth;

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

        rvCars = findViewById(R.id.rvCars);
        getBrand = findViewById(R.id.getBrand);



        final SpecificAdapterManager specificAdapterManager = new SpecificAdapterManager(this, rvCars);

        new FirebaseDBAccess2().readData(new FirebaseDBAccess2.DataChangeListener()
        {
            @Override
            public void dataChanged(List<String> keys, List<Specific> specifics)
            {


                specificAdapterManager.notifyDataSetChanged(keys, specifics);
            }

            @Override
            public void onUpdateSuccess()
            {

            }

            @Override
            public void onDeleteSuccess()
            {

            }

            @Override
            public void onAddSuccess()
            {

            }
        });

        auth = FirebaseAuth.getInstance();

        //get items for a specific brand from the database
        //connect the recycler view with the adapter and send the lists
        //if the lists are empty the linear layout will be visible
        // else invisible
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        getMenuInflater().inflate(R.menu.menu_main, menu);

        FirebaseUser user = auth.getCurrentUser();
        if(user != null)
        {
            menu.getItem(0).setVisible(true); // new car
            menu.getItem(1).setVisible(false); // login / register
            menu.getItem(2).setVisible(true); // logoout
        }

        else
        {
            menu.getItem(0).setVisible(false); // new car
            menu.getItem(1).setVisible(true); // login / register
            menu.getItem(2).setVisible(false); // logoout
        }

        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu)
    {
        FirebaseUser user = auth.getCurrentUser();
        if(user != null)
        {
            menu.getItem(0).setVisible(true); // new car
            menu.getItem(1).setVisible(false); // login / register
            menu.getItem(2).setVisible(true); // logoout
        }

        else
        {
            menu.getItem(0).setVisible(false); // new car
            menu.getItem(1).setVisible(true); // login / register
            menu.getItem(2).setVisible(false); // logoout
        }
        return super.onPrepareOptionsMenu(menu);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {

            switch (item.getItemId())
            {

                case R.id.menuNewCar:
                    Intent newCar = new Intent(this, AddActivity.class);
                    startActivity(newCar);
                    return true;

//                case R.id.menuLogin_Register:
//                    Intent signInIntent = new Intent(this, SignInUpActivity.class);
//                    startActivity(signInIntent);
//                    return true;

                case R.id.menuLogout:
                    // logout functionality
                    auth.signOut();

                    Intent i = new Intent(SpecificCar.this, MainActivity.class);
                    startActivity(i);
                    invalidateOptionsMenu();
                    return true;
            }
            return super.onOptionsItemSelected(item);
        }




}















public class SpecificAdapterManager
{




    private Context context;
    private List<String> keys = new ArrayList<>();
    private List<Specific> specifics = new ArrayList<>();

    private SpecificAdapterManager.CarAdapter adapter = new SpecificAdapterManager.CarAdapter();
    private ProgressBar pb;

    private FirebaseAuth auth;

    public SpecificAdapterManager(Context context, RecyclerView recyclerView)
    {
        this.context = context;
        recyclerView.setAdapter(adapter);

        auth = FirebaseAuth.getInstance();
    }


    public void notifyDataSetChanged(List<String> keys, List<Specific> specifics)
    {

        this.keys = keys;
        this.specifics = specifics;
        adapter.notifyDataSetChanged();
    }


    private class CarAdapter extends RecyclerView.Adapter<CarViewHolder>
    {

        @NonNull
        @Override
        public SpecificAdapterManager.CarViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
        {
            LayoutInflater inflater = LayoutInflater.from(context);
            View v = inflater.inflate(R.layout.specific_category_list, parent, false);

            SpecificAdapterManager.CarViewHolder holder = new SpecificAdapterManager.CarViewHolder(v);
            return holder;
        }

        @Override
        public void onBindViewHolder(@NonNull SpecificAdapterManager.CarViewHolder holder, int position)
        {
            String key = keys.get(position);
            Specific specific = specifics.get(position);

            holder.bind(specific, key);


        }

        @Override
        public int getItemCount()
        {
            return specifics.size();

        }

    }

    private class CarViewHolder extends RecyclerView.ViewHolder
    {

        private String key;

        private TextView tvVersion, tvModel, tvColor, tvPrice, getBrand;
        private ImageView ivCar;
        private ProgressBar pb;
        private Button buttonOptions;
        private String key1;






        public CarViewHolder(@NonNull View v)
        {
            super(v);

            tvVersion = v.findViewById(R.id.tvVersion);
            tvModel = v.findViewById(R.id.tvModel);
            tvColor = v.findViewById(R.id.tvColor);
            tvPrice = v.findViewById(R.id.tvPrice);
            ivCar = v.findViewById(R.id.ivCar);
            pb = v.findViewById(R.id.progressBar);
            getBrand = v.findViewById(R.id.getBrand);





            buttonOptions = (Button)itemView.findViewById(R.id.buttonOptions);



            buttonOptions.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(auth != null)
                    {
                    try {
                        final PopupMenu popupMenu = new PopupMenu(context, buttonOptions);
                        popupMenu.getMenuInflater().inflate(R.menu.menu_button, popupMenu.getMenu());
                        popupMenu.setOnMenuItemClickListener( new PopupMenu.OnMenuItemClickListener() {
                            @Override
                            public boolean onMenuItemClick(MenuItem item) {


                                switch (item.getItemId())
                                {

                                    case R.id.remove:
                                new FirebaseDBAccess2().deleteCar(key, new FirebaseDBAccess2.DataChangeListener()
                                {
                                    @Override
                                    public void dataChanged(List<String> keys, List<Specific> specifics)
                                    {

                                    }

                                    @Override
                                    public void onUpdateSuccess()
                                    {
                                        Toast.makeText(context, "Car Updated successfully", Toast.LENGTH_SHORT).show();
                                    }

                                    @Override
                                    public void onDeleteSuccess()
                                    {
                                        Toast.makeText(context, "Car Deleted",
                                                Toast.LENGTH_SHORT).show();
                                    }

                                    @Override
                                    public void onAddSuccess()
                                    {
                                        Toast.makeText(context, "Car Added", Toast.LENGTH_SHORT).show();
                                    }
                                });
                                return true;


                                    case R.id.update:
                                        Intent updateIntent = new Intent(context, AddUpdateActivity.class);
                                        updateIntent.putExtra("key", key);
                                        updateIntent.putExtra("version", tvVersion.getText().toString());
                                        updateIntent.putExtra("model", tvModel.getText().toString());
                                        updateIntent.putExtra("color", tvColor.getText().toString());
                                        updateIntent.putExtra("price", tvPrice.getText().toString());
                                        context.startActivity(updateIntent);

                                        return true;

}



                                return true;
                            }
                        });
                        popupMenu.show();
                    }catch(Exception e)
                    {
                        e.printStackTrace();
                    }
                }
                }
            });










        }

        public void bind(final Specific specific, final String key)
        {

            this.key = key;





                tvVersion.setText(specific.getVersion());
                tvModel.setText(specific.getModel());
                tvColor.setText(specific.getColor());
                tvPrice.setText(specific.getPrice() + "");





               boolean image = new android.os.Handler().postDelayed(
                        new Runnable()
                        {
                            public void run()
                            {
                                Picasso.with(context).load(R.drawable.sayarati_logo).into(ivCar);
                                pb.setVisibility(View.GONE);




                            }
                        }, 3000);

               if(image == false)
                new android.os.Handler().postDelayed(
                        new Runnable()
                        {
                            public void run()
                            {
                                Picasso.with(context).load(R.drawable.sayarati_logo).into(ivCar);
                                        pb.setVisibility(View.GONE);
                            }
                        }, 3000);



                }

            }


        }

0 个答案:

没有答案