我正在尝试允许应用程序用户从其图库中选择图像,并且仅在用户实际选择图像uri时设置图像uri。我面临的问题是,当我打开图像库时,所有图像都会变灰,并且无论图像格式如何,都无法选择图像。这是我的代码:
public class Signup extends AppCompatActivity implements View.OnClickListener {
Button btnRegister;
TextView edtsdate, edtbirthdate;
int date, month, year;
EditText emailEditText, passEditText, conpassEditText, userEditText, edtAddress, edtcontact;
RadioGroup gender;
ImageView userphoto;
static int PReqCode =1;
static int REQUESCODE =1;
Uri pickedImg;
private EditText edtfn;
private EditText edtLn;
private DatabaseReference myRef;
private FirebaseAuth mAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
mAuth = FirebaseAuth.getInstance();
// Write a message to the database
FirebaseDatabase database = FirebaseDatabase.getInstance();
myRef = database.getReference("User");
/*FirebaseUser currentUser = mAuth.getCurrentUser();
updateUI(currentUser);*/
btnRegister = (Button) findViewById(R.id.bt_register1);
edtsdate = (TextView) findViewById(R.id.birthdate);
edtsdate.setOnClickListener(this);
Calendar calendar = Calendar.getInstance();
date = calendar.get(Calendar.DAY_OF_MONTH);
month = calendar.get(Calendar.MONTH);
year = calendar.get(Calendar.YEAR);
gender = (RadioGroup) findViewById(R.id.radiogrp);
edtfn = (EditText) findViewById(R.id.Fname);
edtLn = (EditText) findViewById(R.id.lname);
edtbirthdate = (TextView) findViewById(R.id.birthdate);
edtcontact = (EditText) findViewById(R.id.Contact);
emailEditText = (EditText) findViewById(R.id.Email);
passEditText = (EditText) findViewById(R.id.Password);
conpassEditText = (EditText) findViewById(R.id.Confirm);
userEditText = (EditText) findViewById(R.id.username);
edtAddress = (EditText) findViewById(R.id.address);
userphoto = (ImageView) findViewById(R.id.profile_photo);
userphoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= 22) {
checkAndRequestForPermission();
}
else
{
openGallery();
}
}
});
btnRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// final String gend = gender.
final String email = emailEditText.getText().toString();
final String pass = passEditText.getText().toString();
final String confirm = conpassEditText.getText().toString();
final String username = userEditText.getText().toString();
final String strfn = edtfn.getText().toString();
final String strln = edtLn.getText().toString();
final String edtadd = edtAddress.getText().toString();
final String birth = edtbirthdate.getText().toString();
final String mobile = edtcontact.getText().toString();
final String bdate = edtbirthdate.getText().toString();
if (email.equals("") && email.isEmpty()) {
emailEditText.setError("Enter Email");
} else if (!isValidEmail(email)) {
emailEditText.setError("Invalid Email");
} else if (pass.equals("") && pass.isEmpty()) {
passEditText.setError("Enter Password");
} else if (!isValidPassword(pass)) {
passEditText.setError("Please Use Combination of Upper Case(A-Z),Lower Case(a-z),and Numbers(0-9) and should be of minimum 6 character ");
} else if (!pass.contentEquals(confirm)) {
conpassEditText.setError("Password Not Match");
} else if (username.equals("")) {
userEditText.setError("Username Can't be Empty");
} else if (mobile.equals("*")) {
edtcontact.setError("Enter Valid Mobile Number");
} else {
/* CreateUserAccount(email,confirm,strfn,strln,username,mobile,bdate,edtadd,pass);*/
mAuth.createUserWithEmailAndPassword(email, pass)
.addOnCompleteListener(Signup.this, new OnCompleteListener<AuthResult>() {
final String email = emailEditText.getText().toString();
final String pass = passEditText.getText().toString();
final String confirm = conpassEditText.getText().toString();
final String username = userEditText.getText().toString();
final String strfn = edtfn.getText().toString();
final String strln = edtLn.getText().toString();
final String edtadd = edtAddress.getText().toString();
final String birth = edtbirthdate.getText().toString();
final String mobile = edtcontact.getText().toString();
final String bdate = edtbirthdate.getText().toString();
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d("TAG", "createUserWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
String strUserID = user.getUid();
String userkey = myRef.push().getKey();
UserModel userModel = new UserModel();
userModel.setFirstname(strfn);
userModel.setLastname(strln);
userModel.setEmailid(email);
userModel.setPassword(confirm);
userModel.setUsername(username);
userModel.setUserid(strUserID);
userModel.setSignaddress(edtadd);
userModel.setMobileno(mobile);
userModel.setUser_birthdate(bdate);
myRef.child(strUserID).setValue(userModel);
updateUserInfo(username,pickedImg,mAuth.getCurrentUser());
Toast.makeText(Signup.this, "Sign Up Successful", Toast.LENGTH_SHORT).show();
Intent i = new Intent(Signup.this, Login.class);
startActivity(i);
} else {
// If sign in fails, display a message to the user.
Log.w("TAG ", "createUserWithEmail:failure", task.getException());
Toast.makeText(Signup.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
//updateUI(null);
}
// ...
}
});
}
}
});
}
/* private void CreateUserAccount(String pass, final String email, final String confirm, final String strfn, final String strln, final String username, final String mobile, final String bdate, final String edtadd) {
}*/
private void updateUserInfo(final String username, Uri pickedImg, final FirebaseUser currentUser) {
StorageReference mStorage = FirebaseStorage.getInstance().getReference().child("users_photos");
final StorageReference imageFilePath = mStorage.child(pickedImg.getLastPathSegment());
imageFilePath.putFile(pickedImg).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
imageFilePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
UserProfileChangeRequest profileUpdate = new UserProfileChangeRequest.Builder()
.setDisplayName(username)
.setPhotoUri(uri)
.build();
currentUser.updateProfile(profileUpdate)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(Signup.this, "Photo Uploaded", Toast.LENGTH_SHORT).show();
updateUI();
}
}
});
}
});
}
});
}
private void showMessage(String registered_successfully) {
Toast.makeText(this, registered_successfully, Toast.LENGTH_SHORT).show();
}
private void openGallery() {
Intent gallery = new Intent(Intent.ACTION_GET_CONTENT);
/* Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);*/
gallery.setType("images/*");
startActivityForResult(gallery,REQUESCODE);
}
private void checkAndRequestForPermission() {
if(ContextCompat.checkSelfPermission(Signup.this, Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED){
if(ActivityCompat.shouldShowRequestPermissionRationale(Signup.this, Manifest.permission.READ_EXTERNAL_STORAGE)){
Toast.makeText(Signup.this,"Please Accept For Required Permission",Toast.LENGTH_SHORT).show();
}
else
{
ActivityCompat.requestPermissions(Signup.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
PReqCode);
}
}
else
openGallery();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK && requestCode == REQUESCODE && data !=null){
pickedImg = data.getData();
userphoto.setImageURI(pickedImg);
}
}
private void updateUI() {
Toast.makeText(Signup.this, "Sign Up Successful", Toast.LENGTH_SHORT).show();
/*Intent i = new Intent(Signup.this, Login.class);
startActivity(i);
finish();*/
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.birthdate:
DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
edtsdate.setText(i2 + "/" + (i1 + 1) + "/" + i);
}
}, year, month, date);
datePickerDialog.show();
break;
}
}
// validating email id
private boolean isValidEmail(String email) {
String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
Pattern pattern = Pattern.compile(EMAIL_PATTERN);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
// validating password with retype password
private boolean isValidPassword(String pass) {
if (pass != null && pass.length() > 6) {
return true;
}
return false;
}
}
答案 0 :(得分:0)
用于图像拾取
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, PICK_PHOTO);
覆盖OnActivityResult()
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_PHOTO && resultCode == Activity.RESULT_OK) {
if (data == null) {
//Display an error
return;
}
try {
Uri selectedImageUri = data.getData();
String selectedImagePath = getPath(selectedImageUri);
Log.e("TAG", "file path => " + selectedImagePath);
} catch (Exception e) {
e.printStackTrace();
}
}
}
从uri获取路径
/**
* helper to retrieve the path of an image URI
*/
public String getPath(Uri uri) {
// just some safety built in
if (uri == null) {
// TODO perform some logging or show user feedback
return null;
}
// try to retrieve the image from the media store first
// this will only work for images selected from gallery
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String path = cursor.getString(column_index);
cursor.close();
return path;
}
// this is our fallback here
return uri.getPath();
}
希望有帮助。