如何编写使用Firebase进行用户身份验证的共享首选项代码?

时间:2019-06-06 15:58:41

标签: android firebase sharedpreferences

如何编写使用Firebase进行用户身份验证的共享首选项代码,并且用户只能访问用户保存的数据? 我当前的应用程序保存并显示了便笺,这是我项目中最需要的内容,但是当用户注销并新用户登录时,他/她还可以查看数据,因此数据不是私有的。先生建议使用共享首选项为用户创建节点,但我找不到任何解决方案

HomeActivity:

public class HomeActivity extends AppCompatActivity {

    EditText Descriptionholder;
    Button Savebtn;
    DatabaseReference DatabaseNote;
    ListView listViewNotes;

    List<PrivateNote> privateNoteList;


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

        DatabaseNote = FirebaseDatabase.getInstance().getReference("privatenote");
        Descriptionholder = findViewById(R.id.description2);

        Savebtn = findViewById(R.id.buttonsave);

        listViewNotes= findViewById(R.id.listViewPrivate);

        privateNoteList = new ArrayList<>();
        Savebtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                addnote();
            }

        });

        listViewNotes.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                PrivateNote privateNote = privateNoteList.get(i); //confusion

                showUpdateDialog(privateNote.getNoteId(),privateNote.getNoteDescription());
                return false;
            }
        });

    }
        public boolean onCreateOptionsMenu (Menu menu){
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.side, menu);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected (MenuItem item){
            switch (item.getItemId()) {
                case R.id.item1:

                    FirebaseAuth.getInstance().signOut();
                    finish();

                    startActivity(new Intent(new Intent(this, MainActivity.class)));
                    Toast.makeText(this, "Logged out ", Toast.LENGTH_SHORT).show();

                    return true;
                default:
                    return super.onOptionsItemSelected(item);
            }
        }

    @Override
    protected void onStart() {
        super.onStart();

        DatabaseNote.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                        privateNoteList.clear();
                for (DataSnapshot privateSnapshot: dataSnapshot.getChildren() ){

                    PrivateNote privateNote = privateSnapshot.getValue(PrivateNote.class);

                    privateNoteList.add(privateNote);
                }
             PrivateList adapter = new PrivateList(HomeActivity.this,privateNoteList);
                listViewNotes.setAdapter(adapter);
            }

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

            }
        });
    }

    private void showUpdateDialog(final String noteId, String noteDescription){

        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);

        LayoutInflater inflater = getLayoutInflater();

        final View dialogview = inflater.inflate(R.layout.update_dialouge,null);

        dialogBuilder.setView(dialogview);

        final  EditText editDescription = dialogview.findViewById(R.id.editDescription);
        final Button buttonUpdate = dialogview.findViewById(R.id.buttonUpdate);
        final Button buttonDelete = dialogview.findViewById(R.id.buttonDelete);

        dialogBuilder.setTitle("Updating Note: " +noteDescription);

        final AlertDialog alertDialog = dialogBuilder.create();
        alertDialog.show();

        buttonUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String description = editDescription.getText().toString().trim();

                if (TextUtils.isEmpty(description)){
                    editDescription.setError(" New information required");
                    return;
                }
                    updatePrivateNote(noteId,description);

                    alertDialog.dismiss();
            }
        });

        buttonDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                deletePrivateNote(noteId);
            }
        });
    }

    private void deletePrivateNote(String noteId) {

        DatabaseReference drPrivateNote = FirebaseDatabase.getInstance().getReference("privatenote").child(noteId);

        drPrivateNote.removeValue();

        Toast.makeText(this, " Note Deleted", Toast.LENGTH_SHORT).show();

    }

    private boolean updatePrivateNote(String id,String description){

        DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("privatenote").child(id);

        PrivateNote privateNote = new PrivateNote(id,description);

        databaseReference.setValue(privateNote);

        Toast.makeText(this, " Note Updated", Toast.LENGTH_SHORT).show();
        return true;
    }
    private void addnote () {

            String description = Descriptionholder.getText().toString().trim();

            if (!TextUtils.isEmpty(description)){

                //generated unique number for id
                String id = DatabaseNote.push().getKey();

                PrivateNote pNote = new PrivateNote(id, description);

                DatabaseNote.child(id).setValue(pNote); //pNote value added in id
                Toast.makeText(this, "Note added", Toast.LENGTH_SHORT).show();

            }

            else {

                Toast.makeText(this, " Please Enter a note ", Toast.LENGTH_SHORT).show();

            }
        }


    @Override
    public void onBackPressed() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Are you sure you want to exit?")
                .setCancelable(false)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        FirebaseAuth.getInstance().signOut();
                        finish();


                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();

    }

适配器:

public class PrivateList  extends ArrayAdapter<PrivateNote> {

    private Activity context;
    private List<PrivateNote> privateNoteList;



    public PrivateList(Activity context, List<PrivateNote> privateNoteList){

                super(context, R.layout.list_layout,privateNoteList);
                this.context =context;
                this.privateNoteList=privateNoteList;

    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {

        LayoutInflater inflater = context.getLayoutInflater();
        View listViewItem = inflater.inflate(R.layout.list_layout,null,true);

        TextView textViewDescription = listViewItem.findViewById(R.id.TextViewDescription);

        PrivateNote privateNote = privateNoteList.get(position);

        textViewDescription.setText(privateNote.getNoteDescription());

        return listViewItem;

    }

}

私人提示:

public class PrivateNote {

   public String noteId;
    public String noteDescription;

    public PrivateNote(){

    }

    PrivateNote(String noteId, String noteDescription){

        this.noteId = noteId;
        this.noteDescription=noteDescription;
    }



    String getNoteId()
    {
        return noteId;
    }

    String getNoteDescription()
    {
        return noteDescription;
    }
}

2 个答案:

答案 0 :(得分:0)

在Firebase中,有两件事,

  1. FirebaseDatabase

  2. FirebaseAuth

通常,在几乎所有应用中,用户数据都存储在密钥下的FirebaseDatabase中,该数据是在Firebase应用中创建新用户时生成的。

因此,例如,您的数据库结构将如下所示。

-Your_main_database

 |____UserId_Of_FirebaseUser

      |____stuff_related_to_user

      |____More stuff related to user

因此,您在FirebaseAuth中创建了一个新用户,您可以在下面找到有关它的更多信息:

Firebase Custom Auth

然后,在创建新用户之后,使用当前登录用户的key = userId在数据库下创建子节点。

例如在您的addNote函数中,id变量将等于

String id = FirebaseAuth.getInstance().getCurrentUser().getUid();

当前,您使用的是基于Timestamp生成的Push键,除非您在存储当前用户名的note对象中添加一个key,然后找到所有子节点,否则您将无法与用户关联。包含该用户名的用户名,但是在那种情况下,您的数据将根本无法组织。

然后,在主数据库下创建一个具有userId的节点后,即可使用push()函数将用户创建的新注释推入userId内。因此您的数据库结构如下所示。

___
   |
   |__users
           |__uniqueUserId
           |              |__note1
           |              |__note2
           |__uniqueUserId2
                          |__note1
                          |__note2
                          |__note3

下一次,每当您要获取用户创建的注释时,就登录该用户,获取其ID,然后找到与该ID对应的注释。

我不知道您如何适应SharedPreferences的需求,在加载数据后,还可以在Firebase中离线缓存数据。

保护笔记:

如果您像我上面所述实现数据库,您将很容易保护数据库。

Common Database Rules

如果您按照我的指示正确地实现了所有操作,则可以使用上述规则中的第四组规则来保护数据库。

答案 1 :(得分:0)

由于您使用的是Firebase身份验证,因此您可以检索userId,并创建以下数据库:

notes
  userId
      note        : "todo"
      description : "study"

那么您可以做:

DatabaseReference ref = FirebaseDatabase.getInstance().getReference("notes");
FirebaseUser user     = FirebaseAuth.getInstance().getCurrentUser();
String userId         = user.getUid();
ref.orderByKey().equalTo(userId).addValueEventListener(new ValueEventListener() {...} 

这样,您将仅检索当前登录用户的数据。