Aşağıdaki fonksiyonu resim eklemek istendiğinde bir butona basılırken çağırırsanız galeriye erişilir.
private void chooseImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select picture"), Common.PICK_IMAGE_REQUEST);
}
Manifest dosyasına eklenmesi için alınması gereken istekler:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Dosyayı seçtikten sonra aşağıdaki kod ile istenen pathe yükleyebilirsiniz.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Common.PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null) {
Uri saveUri = data.getData();
if (saveUri != null) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Uploading");
progressDialog.show();
String imageName = UUID.randomUUID().toString();
final StorageReference imageFolder = storageReference.child("image/" + imageName);
imageFolder.putFile(saveUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
imageFolder.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(final Uri uri) {
AccountKit.getCurrentAccount(new AccountKitCallback<Account>() {
@Override
public void onSuccess(Account account) {
Map<String, Object> avatarUpdate = new HashMap<>();
avatarUpdate.put("avatarUrl", uri.toString());
DatabaseReference userInformation = FirebaseDatabase.getInstance().getReference().child("Users");
driverInformation.child(account.getId())
.updateChildren(avatarUpdate)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful())
Toast.makeText(Home.this, "Uploaded", Toast.LENGTH_SHORT).show();
else
Toast.makeText(Home.this, "Uploaded error", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onError(AccountKitError accountKitError) {
}
});
}
});
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
progressDialog.setMessage("Uploaded" + progress + "%");
}
});
}
}
}
Ben FirebaseAuth yerine FacebookAccountKit kullanıyorum. account.getId() yerine Firebaseden gelen ID bilgisi yazılmalı.