如何将裁剪的图像传递到Firebase(Android Studio)的另一个活动中

问题描述 投票:-1回答:1

问题:我希望用户能够从画廊上载图像,对其进行裁剪,然后我希望该图像传递到另一个活动的图像视图。

  • 在Activity1中,用户可以将个人资料图片上传到Circle ImageView。
  • 然后,此上传的图片应传递到另一个活动的Circle ImageView(Personal_Wall.class)。
  • 我尝试了互联网上的其他解决方案,但似乎没有任何效果。常见错误通常会导致应用程序崩溃。
  • 关于任何解决方案,请也告诉我代码中应该放在哪里。-非常感谢!

Activity1

    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 Occured: " + 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();
        }



    }

Activity2

    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);

}

如果这仍然是我需要的正确代码,请让我知道它在我的代码中的位置。我出错的原因可能是我将其放在错误的位置的结果。

android firebase picasso
1个回答
0
投票

好吧,既然您已经下载了uri,为什么不直接传递字符串而不是位图:

活动1:

Intent intent= new Intent(this, personal_wall.class);
                        intent.putExtra("image", downloadurl.tostring());
                        startActivity(intent);

活动2:

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);

滑行真的很有帮助。另外,如果您打算前后传递位图,则使用字符串将使您的生活更加轻松,因为您必须确保位图不会超出parceil大小或所谓的大小。很多的崩溃。我也在努力学习。哈哈

© www.soinside.com 2019 - 2024. All rights reserved.