【问题标题】:How to write Shared preference Code that uses firebase for User authentication?如何编写使用 firebase 进行用户身份验证的共享偏好代码?
【发布时间】:2019-06-06 15:58:41
【问题描述】:

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

家庭活动:

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;
    }
}

【问题讨论】:

  • 为什么要存储在SharedPreferences而不是直接存储在数据库中?
  • 我存储在 Fire-base 实时数据库中,但该信息对特定用户来说不是私有的,每个登录的用户都可以看到,所以我问我的先生谁建议我使用共享偏好并对用户点头,但我不知道如何
  • 如果您不保护它,它就不是私有的。您应该为此使用Firebase security rules,一切都会正常工作。
  • 感谢您的解决方案,我会实施并告诉您进展如何。
  • 我只有一张桌子注意这会影响访问吗?

标签: android firebase sharedpreferences


【解决方案1】:

在 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();

目前,您正在使用基于时间戳生成的推送键,除非您在存储当前用户名的笔记对象中添加一个键,否则您将无法与用户关联,然后找到所有子节点包含该用户名,但在这种情况下,您的数据将根本不会被组织。

然后,在您在主数据库下使用 userId 创建节点后,您可以使用 push() 函数将用户创建的新笔记推送到 userId 中。所以你的数据库结构如下所示。

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

下次当您想要获取用户创建的笔记时,您登录用户,获取他的 ID,然后找到与该 ID 对应的笔记。

我不知道你怎么能把SharedPreferences放在那里,在Firebase还具有离线缓存数据加载后的功能之前。

保护笔记:

如果您像我上面所说的那样实现数据库,您将能够非常轻松地保护您的数据库。

Common Database Rules.

如果您按照我所说的正确实施一切,您将能够使用上述规则中的第四组规则来保护您的数据库。

【讨论】:

  • 感谢您的解决方案。那么我需要重做我的代码吗?我不知道如何制作子节点。我的数据库中只有一个名为 Private Note 的单个表,它存储一个唯一的 id 和 note 。
  • 不要在 addNote() 函数中生成随机推送键,而是创建一个具有唯一用户 ID 的子笔记,然后在该用户 ID 下推送新笔记
【解决方案2】:

由于您使用的是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() {...} 

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

【讨论】:

    猜你喜欢
    • 2016-04-08
    • 1970-01-01
    • 1970-01-01
    • 2012-08-11
    • 2016-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    相关资源
    最近更新 更多