Authenticated users accessing their data using Firebase for Android

五迷三道 提交于 2019-12-13 03:31:47

问题


I am struggling to make a tie between my users in Firebase, and data that I want it to be linked to.

At the moment I am able to create users and log in with users credentials. Additionally, I am able to create Maintenance Issues using my MaintenanceActivity.

However, when I log in with an arbitrary user, the same maintenance issues will always show.

I am unsure how to link the User ID of each user to a maintenance issue, so that when a user logs in only their maintenance issues will show.

Totally unsure on where to start here, so any help would be much appreciated. Been struggling with this for a few days.

SignUpActivity

This creates users in the 'Users' table in my Firebase database, but I also want it to contain the User ID which can be linked to maintenance issues.

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 Database

Database Rules are as follows:

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

回答1:


A basic approach that u can take is have a User Id for every maintenance node that you push.

So as per your firebase database you have a user ID "bfPG...." This id can be the parent node for every maintenance record.

If you change this line to this

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

this

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

you'll be pushing a maintenance record under a user ID and you can then differentiate maintenance records with different users.

Thus in order to get the records for a specific user you have to change your firebase query.

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

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

check the link about how to filter records.


Another approach is you have an adapter to which you are adding maintenance records so before you add a record you can check if it belongs to the current user or not and add records accordingly.



来源:https://stackoverflow.com/questions/49282509/authenticated-users-accessing-their-data-using-firebase-for-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!