如何从Firebase存储访问特定用户的特定图像

时间:2016-11-15 14:52:31

标签: android firebase-realtime-database firebase-storage

这是我在图像子元素中的数据库,我已经存储了Fiebase Storage中的图像下载URL。Click Check my Database screenshot 我希望当用户使用他的电子邮件和密码登录时,他可以获得他在注册时存储的图像。

public class Register extends AppCompatActivity {
//firebase auth object
private FirebaseAuth firebaseAuth;
private StorageReference mStorage;

private DatabaseReference mDatabse;

//our new views
private EditText editTextName, editTextAddress, editTextEmail, editTextPhoneOrRid, editTextPassword;
private Button buttonSave;
private ProgressDialog progressDialog;
public final static int QRcodeWidth = 500;
private Bitmap bitmap;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);
    /*final int min = 1;
    final int max = 10000;
    Random r = new Random();
    int counter = r.nextInt(max - min + 1) + min;
    ctr = String.valueOf(counter);*/


    progressDialog = new ProgressDialog(this);
    firebaseAuth = FirebaseAuth.getInstance();
                  String user = firebaseAuth.getCurrentUser().toString();

    mDatabse = FirebaseDatabase.getInstance().getReferenceFromUrl("https://lpuevents-8f661.firebaseio.com/AppUsers/");

    //getting the views from xml resource
    editTextAddress = (EditText) findViewById(R.id.editText7);
    editTextName = (EditText) findViewById(R.id.editText3);
    editTextEmail = (EditText) findViewById(R.id.editText4);
    editTextPhoneOrRid = (EditText) findViewById(R.id.editText6);
    editTextPassword = (EditText) findViewById(R.id.editText8);
    buttonSave = (Button) findViewById(R.id.button3);
    if (user == null) {
        //closing this activity
        finish();
        //starting login activity
        startActivity(new Intent(this, Login.class));
    }

    buttonSave.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            saveUserInformation();
            // wait(360000);


            registerUser();

        }
    });
}


Bitmap TextToImageEncode(String Value) throws WriterException {
    BitMatrix bitMatrix;
    try {
        bitMatrix = new MultiFormatWriter().encode(
                Value,
                BarcodeFormat.DATA_MATRIX.QR_CODE,
                QRcodeWidth, QRcodeWidth, null
        );

    } catch (IllegalArgumentException Illegalargumentexception) {

        return null;
    }
    int bitMatrixWidth = bitMatrix.getWidth();

    int bitMatrixHeight = bitMatrix.getHeight();

    int[] pixels = new int[bitMatrixWidth * bitMatrixHeight];

    for (int y = 0; y < bitMatrixHeight; y++) {
        int offset = y * bitMatrixWidth;

        for (int x = 0; x < bitMatrixWidth; x++) {

            pixels[offset + x] = bitMatrix.get(x, y) ?
                    getResources().getColor(R.color.black) : getResources().getColor(R.color.white);
        }
    }
    Bitmap bitmap = Bitmap.createBitmap(bitMatrixWidth, bitMatrixHeight, Bitmap.Config.ARGB_4444);

    bitmap.setPixels(pixels, 0, 500, 0, 0, bitMatrixWidth, bitMatrixHeight);
    return bitmap;
}


private void saveUserInformation() {
    //Getting values from database
    final String name = editTextName.getText().toString().trim();
    final String address = editTextAddress.getText().toString().trim();
    final String email = editTextEmail.getText().toString().trim();
    final String phone = editTextPhoneOrRid.getText().toString().trim();

    //String id = user.getUid().trim();
    try {

        bitmap = TextToImageEncode(phone+" "+email);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] data = baos.toByteArray();
        String uuid = UUID.randomUUID().toString();
        mStorage = FirebaseStorage.getInstance().getReferenceFromUrl("gs://lpuevents-8f661.appspot.com/"+uuid);
    final StorageReference lol = mStorage;
       // final DatabaseReference db = mDatabse;
        UploadTask uploadTask = lol.putBytes(data);
        uploadTask.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception exception) {
                // Handle unsuccessful uploads
            }
        }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
              //  Toast.makeText(Register.this, "Succesfully Saved...", Toast.LENGTH_LONG).show();
                DatabaseReference userInfo = mDatabse.push();
                Uri downloadUrl = taskSnapshot.getDownloadUrl();
                taskSnapshot.getMetadata();
                userInfo.child("name").setValue(name);
                userInfo.child("email").setValue(email);
                userInfo.child("address").setValue(address);
                userInfo.child("phone").setValue(phone);
                userInfo.child("image").setValue(downloadUrl.toString());

            }
        });

        //imageView.setImageBitmap(bitmap);

    } catch (WriterException e) {
        e.printStackTrace();
    }


private void registerUser() {

    //getting email and password from edit texts
    String email = editTextEmail.getText().toString().trim();
    String password = editTextPassword.getText().toString().trim();

    //checking if email and passwords are empty
    if (TextUtils.isEmpty(email)) {
        Toast.makeText(this, "Please enter email", Toast.LENGTH_LONG).show();
        return;
    }

    if (TextUtils.isEmpty(password)) {
        Toast.makeText(this, "Please enter password", Toast.LENGTH_LONG).show();
        return;
    }

    //if the email and password are not empty
    //displaying a progress dialog

    progressDialog.setMessage("Registering Please Wait...");
    progressDialog.show();
    progressDialog.dismiss();

    //creating a new user
    firebaseAuth.createUserWithEmailAndPassword(email, password)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    //checking if success
                    if (task.isSuccessful()) {
                       // saveUserInformation();
                        Toast.makeText(Register.this, "Successfully registered", Toast.LENGTH_LONG).show();
                    } else {
                        //display some message here
                        Toast.makeText(Register.this, "Registration Error", Toast.LENGTH_LONG).show();
                    }
                    progressDialog.dismiss();
                }
            });

}

}

0 个答案:

没有答案