经过身份验证的用户使用Firebase for Android访问其数据

时间:2018-03-14 16:03:34

标签: java android firebase firebase-authentication

我正在努力在Firebase中的用户与我希望将其链接到的数据之间建立联系。

目前,我可以创建用户并使用用户凭据登录。此外,我可以使用MaintenanceActivity创建维护问题。

但是,当我使用任意用户登录时,将始终显示相同的维护问题。

我不确定如何将每个用户的用户ID与维护问题相关联,这样当用户只登录 时,就会显示维护问题。

完全不确定从哪里开始,所以任何帮助都会非常感激。几天来一直在努力。

SignUpActivity

这会在我的Firebase数据库的“用户”表格中创建用户,但我还希望它包含可以与维护问题相关联的用户ID。

mDatabase = FirebaseDatabase.getInstance().getReference().child("users");
final DatabaseReference[] ref = new DatabaseReference[1];
final FirebaseUser[] mCurrentUser = new FirebaseUser[1];
mAuth.createUserWithEmailAndPassword(email, password)
  .addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() {
    @Override
    public void onComplete(@NonNull Task<AuthResult> task) {
        Toasty.info(getApplicationContext(), "creation of account was: " + task.isSuccessful(), Toast.LENGTH_SHORT).show();
        if (task.isSuccessful()) {
            mCurrentUser[0] = task.getResult().getUser();
            ref[0] =mDatabase.child(mCurrentUser[0].getUid());
            ref[0].child("email").setValue(email);

            Intent intent = new Intent(SignUpActivity.this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
    }
});

MaintenanceActvity

public class MaintenanceActivity extends AppCompatActivity {    
    EditText editTextTitle;
    EditText editTextDesc;
    Spinner spinnerPrimary;
    Spinner spinnerSecondary;
    Spinner spinnerProperty;
    Button buttonSubmit;

    DatabaseReference databaseMaintenance;

    ListView listViewIssues;

    List<Maintenance> maintenanceList;

    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference fDatabaseRoot = database.getReference();

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.actionBar);
        setSupportActionBar(toolbar);

        ActionBar ab = getSupportActionBar();
        ab.setDisplayHomeAsUpEnabled(true);

        databaseMaintenance = FirebaseDatabase.getInstance().getReference("maintenance");

        editTextTitle = (EditText) findViewById(R.id.editTextTitle);
        editTextDesc = (EditText) findViewById(R.id.editTextDesc);
        buttonSubmit = (Button) findViewById(R.id.buttonSubmit);
        spinnerPrimary = (Spinner) findViewById(R.id.spinnerPrimary);
        spinnerSecondary = (Spinner) findViewById(R.id.spinnerSecondary);
        spinnerProperty = (Spinner) findViewById(R.id.spinnerProperty);

        listViewIssues = (ListView) findViewById(R.id.listViewIssues);

        maintenanceList = new ArrayList<>();

        buttonSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {    
                addMaintenance();
            }
        });

        listViewIssues.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {    
                Maintenance maintenance = maintenanceList.get(position);

                showMoreInfoDialog(maintenance.getMaintenanceId(), maintenance.getMaintenanceTitle(), maintenance.getMaintenanceDescription(), maintenance.getMaintenancePrimary(), maintenance.getMaintenanceSecondary(), maintenance.getMaintenanceProperty());
                return false;
            }
        });
    }

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

        databaseMaintenance.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {    
                maintenanceList.clear();

                for(DataSnapshot maintenanceSnapshot : dataSnapshot.getChildren()){
                    Maintenance maintenance = maintenanceSnapshot.getValue(Maintenance.class);

                    maintenanceList.add(maintenance);    
                }

                MaintenanceList adapter = new MaintenanceList (MaintenanceActivity.this, maintenanceList);
                listViewIssues.setAdapter(adapter);    
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {    
            }    
        });

        fDatabaseRoot.child("properties").addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                // Is better to use a List, because you don't know the size
                // of the iterator returned by dataSnapshot.getChildren() to
                // initialize the array
                final List<String> propertyAddressList = new ArrayList<String>();

                for (DataSnapshot addressSnapshot: dataSnapshot.getChildren()) {
                    String propertyAddress = addressSnapshot.child("propertyAddress").getValue(String.class);
                    if (propertyAddress!=null){
                        propertyAddressList.add(propertyAddress);
                    }
                }

                Spinner spinnerProperty = (Spinner) findViewById(R.id.spinnerProperty);
                ArrayAdapter<String> addressAdapter = new ArrayAdapter<String>(MaintenanceActivity.this, android.R.layout.simple_spinner_item, propertyAddressList);
                addressAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                spinnerProperty.setAdapter(addressAdapter);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {    
            }
        });
    }

    private void showMoreInfoDialog(final String id, String maintenanceTitle, String maintenanceDescription, String maintenancePrimary, String maintenanceSecondary, String maintenanceProperty) {    
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);

        LayoutInflater inflater = getLayoutInflater();

        final View dialogView = inflater.inflate(R.layout.more_info_dialog, null);

        dialogBuilder.setView(dialogView);

        final EditText editTextTitle = (EditText) dialogView.findViewById(R.id.editTextTitle);
        final EditText editTextDesc = (EditText) dialogView.findViewById(R.id.editTextDesc);
        final Button buttonUpdate = (Button) dialogView.findViewById(R.id.buttonUpdate);
        final Spinner spinnerPrimary = (Spinner) dialogView.findViewById(R.id.spinnerPrimary);
        final Spinner spinnerSecondary = (Spinner) dialogView.findViewById(R.id.spinnerSecondary);
        final Spinner spinnerProperty = (Spinner) dialogView.findViewById(R.id.spinnerProperty);
        final Button buttonDelete = (Button) dialogView.findViewById(R.id.buttonDelete);

        dialogBuilder.setTitle("Updating Maintenance " + maintenanceTitle);

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

        buttonUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {    
                String title = editTextTitle.getText().toString().trim();
                String desc = editTextDesc.getText().toString().trim();
                String primary = spinnerPrimary.getSelectedItem().toString();
                String secondary = spinnerSecondary.getSelectedItem().toString();
                String property = spinnerProperty.getSelectedItem().toString();

                if(TextUtils.isEmpty(title)){    
                    editTextTitle.setError("Title Required");
                    return;
                }

                updateMaintenance(title, desc, id, primary, secondary, property);

                alertDialog.dismiss();
            }
        });

    private boolean updateMaintenance(String title, String desc, String id, String primary, String secondary, String property) {    
        DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("maintenance").child(id);
        Maintenance maintenance = new Maintenance (id, title, desc, primary, secondary, property);

        databaseReference.setValue(maintenance);

        Toast.makeText(this, "Maintenance Updated Updated Successfully", Toast.LENGTH_LONG).show();

        return true;
    }

    private void addMaintenance(){    
        String title = editTextTitle.getText().toString().trim();
        String desc = editTextDesc.getText().toString().trim();
        String primary = spinnerPrimary.getSelectedItem().toString();
        String secondary = spinnerSecondary.getSelectedItem().toString();
        String property = spinnerProperty.getSelectedItem().toString();

        if(!TextUtils.isEmpty(title)){    
            String id = databaseMaintenance.push().getKey();

            Maintenance maintenance = new Maintenance (id, title, desc, primary, secondary, property);

            databaseMaintenance.child(id).setValue(maintenance);

            Toast.makeText(this, "Maintenance Added", Toast.LENGTH_LONG).show();

        } else {    
            Toast.makeText(this, "You must enter a maintenance record", Toast.LENGTH_LONG).show();
        }    
    }
}

Firebase数据库

Firebase Database

数据库规则如下:

{
  "rules": {
    "users": {
      "$uid": {
        ".write": "$uid === auth.uid",
        ".read": "$uid === auth.uid"
      }
    }
  }
}

1 个答案:

答案 0 :(得分:0)

您可以采取的基本方法是为您推送的每个维护节点都有一个用户ID。

因此,根据您的firebase数据库,您拥有一个用户ID&#34; bfPG ....&#34; 此id可以是每个维护记录的父节点。

如果您将此行更改为此

String id = databaseMaintenance.push().getKey();

String id = FirebaseAuth.getInstance().getCurrentUser().getUID(); //Check Syntax

您将在用户ID下推送维护记录,然后您可以将维护记录与不同用户区分开来。

因此,为了获取特定用户的记录,您必须更改firebase查询。

databaseMaintenance = FirebaseDatabase.getInstance().getReference("maintenance").orderByKey().equalTo(id); 

https://firebase.google.com/docs/database/android/lists-of-data

检查有关如何过滤记录的链接。

另一种方法是您有一个适配器,您要添加维护记录,因此在添加记录之前,您可以检查它是否属于当前用户,并相应地添加记录。