android - 如何将裁剪后的图像从 Firebase(Android Studio)传递给另一个活动
问题描述
问题:我希望用户能够从图库中上传图像,对其进行裁剪,然后我希望将此图像传递给另一个活动的图像视图。
- 在Activity1中,用户可以上传一张头像到Circle ImageView。
- 然后,这个上传的图片应该传递给另一个活动(Personal_Wall.class)的 Circle ImageView。
- 我尝试了来自互联网的不同解决方案,但似乎没有任何效果。常见错误通常会导致 App 崩溃。
- 对于任何解决方案,还请告诉我它应该在代码中的位置。-非常感谢!
活动1:
public class Add_Info_After_Registration extends AppCompatActivity {
private EditText FirstName;
private EditText LastName;
private Button RegisterInfoButton;
private Bitmap bitmap;
private DatabaseReference UsersReference;
private CircleImageView ProfileImage;
private StorageReference UserProfileImageRef;
private FirebaseAuth mAuth;
String currentUserID;
final static int Gallery_Pick = 1;
private Uri uri;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add__info__after__registration);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
//this is referring to storing username information in firebase//
UsersReference = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID); //this is referring to storing username information in firebase//
FirstName = findViewById(R.id.add_info_first_name);
LastName = findViewById(R.id.add_info_last_name);
RegisterInfoButton = findViewById(R.id.register_submit_button);
ProfileImage = (CircleImageView) findViewById(R.id.profile_image);
UserProfileImageRef = FirebaseStorage.getInstance().getReference().child("Profile Images");
//Text Watcher For First Name//
FirstName.addTextChangedListener(registerTextWatcher);
LastName.addTextChangedListener(registerTextWatcher);
//Text Watcher For First Name//
RegisterInfoButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SaveAccountSetupInformation();
}
});
ProfileImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view)
{
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*"); //this will only choose images from the gallery and not videos, etc...//
startActivityForResult(galleryIntent, Gallery_Pick);
}
});
UsersReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot)
{
if(dataSnapshot.exists())
{
if (dataSnapshot.hasChild("profileimage"))
{
String image = dataSnapshot.child("profileimage").getValue().toString();
Picasso.get().load(image).placeholder(R.drawable.profile_place_holder).into(ProfileImage);
}
else
{
Toast.makeText(Add_Info_After_Registration.this, "Please select profile image first.", Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
//Textwatcher method//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private TextWatcher registerTextWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String firstnameinput = FirstName.getText().toString().trim();
String lastnameinput = LastName.getText().toString().trim();
LastName.setError("Please Enter Name");
FirstName.setError("Please Enter Name");
//This says when the submit button is clicked, it will disable if the firstname or last name is empty//
RegisterInfoButton.setEnabled(!firstnameinput.isEmpty() && !lastnameinput.isEmpty());
//This says when the submit button is clicked, it will disable if the firstname or last name is empty//
}
@Override
public void afterTextChanged(Editable s) {
if( FirstName.getText().length()>0)
{
FirstName.setError(null);
}
if( LastName.getText().length()>0)
{
LastName.setError(null);
}
}
};
//Textwatcher method/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == Gallery_Pick && resultCode == RESULT_OK && data != null) {
Uri imageUri = data.getData();
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1,1)
.start(this);
}
// when pressing the crop button//
if(requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
{
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
StorageReference filePath = UserProfileImageRef.child(currentUserID + ".jpg");
filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
@Override
public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()) {
Toast.makeText(Add_Info_After_Registration.this, "Image has been added sucessfully...", Toast.LENGTH_SHORT).show();
Task<Uri> result = task.getResult().getMetadata().getReference().getDownloadUrl();
result.addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
final String downloadUrl = uri.toString();
UsersReference.child("profileimage").setValue(downloadUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Intent selfIntent = new Intent(Add_Info_After_Registration.this, Add_Info_After_Registration.class); //Change if neededCHECK THIS LATER THIS MAY BE THE REASON WHY THE CODE REFRESHES AFTER YOU CHOOSE A PICTURE
startActivity(selfIntent);
Toast.makeText(Add_Info_After_Registration.this, "Image has been stored...", Toast.LENGTH_SHORT).show();
} else {
String message = task.getException().getMessage();
Toast.makeText(Add_Info_After_Registration.this, "Error: " + message, Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
}
});
}
else {
Toast.makeText(Add_Info_After_Registration.this, "Error: Image did not upload. Please try again.", Toast.LENGTH_SHORT).show();
}
}
}
private void SaveAccountSetupInformation()
{
String firstname = FirstName.getText().toString();
String lastname = LastName.getText().toString();
//Below is the error message if the user does not enter a first name or last name.
if(TextUtils.isEmpty(firstname))
{
FirstName.setError("Input is required!");
}
if(TextUtils.isEmpty(lastname))
{
LastName.setError("Input is required!");
//Above is the error message if the user does not enter a first name or last name.
}
else
{
HashMap userMap = new HashMap();
userMap.put("firstname", firstname);
userMap.put("lastname", lastname);
UsersReference.updateChildren(userMap).addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task)
{
if(task.isSuccessful())
{
SendUserToMainActivity();
Toast.makeText(Add_Info_After_Registration.this, "your Account is created Successfully.", Toast.LENGTH_LONG).show();
}
else
{
String message = task.getException().getMessage();
Toast.makeText(Add_Info_After_Registration.this, "Error Occurred: " + message, Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void SendUserToMainActivity()
{
Intent setupIntent = new Intent(Add_Info_After_Registration.this, MainActivity.class);
setupIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(setupIntent);
finish();
}
}
活动二:
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.navigation.NavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.squareup.picasso.Picasso;
import de.hdodenhof.circleimageview.CircleImageView;
public class Personal_Wall extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
private Bitmap bitmap;
private Uri uri;
String currentUserID;
private DatabaseReference UsersReference;
private CircleImageView profile_image;
private StorageReference UserProfileImageRef;
private FirebaseAuth mAuth;
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_personal__wall);
//Bringing in Database Stuff//
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
UserProfileImageRef = FirebaseStorage.getInstance().getReference().child("Profile Images");
UsersReference = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID);
//Bringing in Database Stuff//
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//this tells our system to actually use the toolbar as the actionbar.
drawer = findViewById(R.id.drawer_layout);
profile_image = findViewById(R.id.profile_place_holder);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.log_out:
LogOut();
break;
}
return true;
}
@Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)){
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
private void LogOut() {
FirebaseAuth.getInstance().signOut();
sendToLogin();
}
private void sendToLogin() {
Intent loginIntent = new Intent(Personal_Wall.this, Login_Activity.class);
startActivity(loginIntent);
finish();
}
}
我试过的:
我使用了从相关线程中找到的以下内容。
但是,在执行此代码后,我仍然无法传递图像。
//For first Activity//
Intent i = new Intent(this, Personal_Wall.class);
Bitmap b; // your bitmap
ByteArrayOutputStream bs = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.PNG, 50, bs);
i.putExtra("profileimage", bs.toByteArray());
startActivity(i);
//For Second Activity//
if(getIntent().hasExtra("profileimage")) {
ImageView previewThumbnail = new ImageView(this);
Bitmap b = BitmapFactory.decodeByteArray(
getIntent().getByteArrayExtra("profileimage"),0,getIntent().getByteArrayExtra("byteArray").length);
previewThumbnail.setImageBitmap(b);
}
如果这仍然是我需要的正确代码,请告诉我它应该在我的代码中的位置。我错误的原因可能是我把它放在错误的地方。
解决方案
既然你有下载的 uri,为什么不只传递字符串而不是位图:
活动一:
Intent intent= new Intent(this, personal_wall.class);
intent.putExtra("image", downloadurl.tostring());
startActivity(intent);
活动二:
Intent intent = getIntent();
String img= intent.getExtras().getString("image");
then use a library like glide to set the img url:
Glide.with(getApplicationContext()).load(img).into(imgHolder);
滑翔真的很有帮助。另外,如果您打算来回传递位图,那么使用字符串将使您的生活更轻松,因为您必须确保它不会超过包裹大小或其他任何名称。很多都崩溃了。我也在努力学习。哈哈
推荐阅读
- html - 如何从 Quizlet 打印索引卡片大小的抽认卡?
- ios - Obj-C - 按字符串中的日期对表格视图数据进行排序?
- python - 如果在异常后不重置,ContextVar 会在异步逻辑中泄漏内存吗?
- python - Clean Architecture 中的实体可以使用边界对象吗?
- .net-core - 控制台中的CSP报告:如何通过.net代码关闭,浏览器控制台中登录的csp报告
- composer-php - 我试图在我的 laravel 6 项目中运行这个“composer require mckenziearts/laravel-notify”,但我收到了这个错误
- google-sheets - 谷歌表格查询公式转置
- javascript - 在 HtmlUnit 中单击锚点后标记 Iframe 不起作用
- php - Symfony\Component\HttpFoundation\BinaryFileResponse 类的对象无法转换为 int
- python - 由于 NameError,kafka-python KafkaProducer App 失败(退出代码 1):未定义名称“json”