如何从Firebase实时数据库中检索最新条目?

时间:2020-04-30 22:01:49

标签: java android firebase firebase-realtime-database

我正在尝试从一个用户那里获取输入并将相同的数据发送给另一个用户。我不确定将什么作为参数放在child中,以便它引用相同的数据,并且我可以检索数据并将其显示给另一个用户以供批准。我可以发送图片,但是对于visitor,mobile和flat这样的数据字段,我不确定该怎么做。

我的代码如下。

数据输入文件代码

this.updateportsService.getPorts().pipe(
 tap(ports => console.log(ports),
 tap(ports => this.ports = ports),
 catchError(e => console.log(e)) // I suspect you'll catch some kind of error
).subscribe()

供其他用户批准的代码

public class Main4Activity extends AppCompatActivity {
    private static final int PERMISSION_CODE = 1000;
    private static final int IMAGE_CAPTURE_CODE = 1001;

    Button btn;
    ImageView imageView;
    static Uri image_uri;
    ImageView mImageView;
    TextView mCaptureBtn;
    Button uploadbtn;
    static String downloadurl;


    public static String Dvisitor;
    public static String Dmobile;

    static DatabaseReference reff;
    //for upload
    private Uri filePath;
    private final int PICK_IMAGE_REQUEST = 71;
    FirebaseStorage storage;
    StorageReference storageReference;
    //for upload

    static String URL;

    //Data store of Visitor
    static EditText visitor;
    static EditText mbnumber;
    EditText bnmbr;
    static EditText fnmbr;
    EditText emal;
    EditText pswrd;

    HashMap<String,Object> map = new HashMap<>();





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









        //for upload
        storage = FirebaseStorage.getInstance();
        storageReference = storage.getReference();
        //for upload

        mImageView = (ImageView) findViewById(R.id.imageView2);
        mCaptureBtn = (TextView) findViewById(R.id.textView4);

        //Data for Visitor
        visitor = (EditText) findViewById(R.id.vname);
        mbnumber = (EditText) findViewById(R.id.mnumber);
        bnmbr = (EditText) findViewById(R.id.blknmbr);
        fnmbr = (EditText) findViewById(R.id.fltnmbr);
        emal = (EditText) findViewById(R.id.emailId);
        pswrd = (EditText) findViewById(R.id.passwordfield2);




        btn = (Button) findViewById(R.id.button);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                upload();


                FirebaseDatabase.getInstance().getReference().child("Image").push().setValue(map)

                        .addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull Task<Void> task) {
                                map.put("visitor",visitor.getText().toString());
                                map.put("mobile",mbnumber.getText().toString());
                                map.put("block",bnmbr.getText().toString());
                                map.put("flat",fnmbr.getText().toString());
                                map.put("email",emal.getText().toString());
                                map.put("password",pswrd.getText().toString());
                                Toast.makeText(Main4Activity.this, "Successful data registration", Toast.LENGTH_SHORT).show();

                            }
                        }).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(Main4Activity.this, "Failed data registration", Toast.LENGTH_SHORT).show();
                    }
                });




            }


        });



















        //Camera functionality click and upload starts





        mCaptureBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED || checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
                        String[] permission = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
                        requestPermissions(permission, PERMISSION_CODE);
                    } else {

                        openCamera();

                    }
                } else {

                    openCamera();

                }

            }
        });


        imageView = (ImageView) findViewById(R.id.imageView);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Main4Activity.this, MainActivity.class);
                startActivity(intent);

            }
        });






    }




    private void openCamera() {

        ContentValues values = new ContentValues();
        values.put(MediaStore.Images.Media.TITLE, "New Picture");
        values.put(MediaStore.Images.Media.DESCRIPTION, "From the Camera");

        image_uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
        startActivityForResult(cameraIntent, IMAGE_CAPTURE_CODE);

        {




        }


    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case PERMISSION_CODE: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openCamera();
                } else {
                    Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {


        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            mImageView.setImageURI(image_uri);
        }

    }






    private void upload(){



            if(image_uri != null)
            {
                final ProgressDialog progressDialog = new ProgressDialog(this);
                progressDialog.setTitle("Uploading...");
                progressDialog.show();

                final StorageReference ref = storageReference.child("images/"+ UUID.randomUUID().toString());
                ref.putFile(image_uri)
                        .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                            @Override
                            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                                progressDialog.dismiss();

                                Toast.makeText(Main4Activity.this, "Uploaded", Toast.LENGTH_SHORT).show();
                                ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                                    @Override
                                    public void onSuccess(Uri uri) {
                                        DatabaseReference imagestore = FirebaseDatabase.getInstance().getReference().child("Image").push();
                                        //HashMap<String, String> hasmap = new HashMap<>();

                                        URL = uri.toString();

                                        map.put("imgurl",URL);





                                        //map.put("imageurl", String.valueOf(uri));
                                        imagestore.setValue(map).addOnSuccessListener(new OnSuccessListener<Void>() {
                                            @Override
                                            public void onSuccess(Void aVoid) {
                                                Intent intent= new Intent(Main4Activity.this,Main5Activity.class);
                                                startActivity(intent);



                                            }


                                        });


                                        //This is your image url do whatever you want with it.
                                    }
                                });


                            }
                        })
                        .addOnFailureListener(new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                                progressDialog.dismiss();
                                Toast.makeText(Main4Activity.this, "Failed "+e.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        })
                        .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                            @Override
                            public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                                double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot
                                        .getTotalByteCount());
                                progressDialog.setMessage("Uploaded " + (int) progress + "%");

                            }
                        });

        }




    }


}

//Camera functionality click and upload starts

1 个答案:

答案 0 :(得分:1)

在您的Main5Activity中,我认为:

此:

for(DataSnapshot child: dataSnapshot.getChildren()) {
    String post = dataSnapshot.child("visitor").getValue(String.class);
    String post1 = dataSnapshot.child("mobile").getValue(String.class);
    String post2 = dataSnapshot.child("flat").getValue(String.class);
    textView.setText("Mr. "+post+"with mobile number: " + post1+"wants to visit your flat: " + post2);
}

必须是这样的:

for(DataSnapshot ds: dataSnapshot.getChildren()) {
    String post = ds.child("visitor").getValue(String.class);
    String post1 = ds.child("mobile").getValue(String.class);
    String post2 = ds.child("flat").getValue(String.class);
    textView.setText("Mr. "+post+"with mobile number: " + post1+"wants to visit your flat: " + post2);
}