简体   繁体   中英

How can I pass an image from an activity to another activity in Android?

I have an image on my settings screen, I want to send it to my home screen.

I saved it in my sharedPreferences and would like to use the key on my other screen, just like I do with texts.

I can get texts and put a setText in texts, but I wanted to know how to do this in an image.

public void salvarDados(){
    String usrname = edtEmailSettings.getText().toString();
    String name = edtNameField.getText().toString();
    String phone = edtPhoneField.getText().toString();
    String company = edtCompanySettings.getText().toString();
    String photo = imgProfileImage.toString();
    if(!savelogincheckbox.isChecked()){
        editor.putBoolean("savelogin",true);
        editor.putString("user",usrname);
        editor.putString("nam", name);
        editor.putString("phon", phone);
        editor.putString("company", company);
        editor.putString("image", photo);
        editor.commit();
    }
}

Trying to get the die:

saveLogin = sharedPreferences.getBoolean("saveLogin", true);
    if (saveLogin == true){
        edtEmail.setText(sharedPreferences.getString("user", null));
        edtNome.setText(sharedPreferences.getString("nam", null));
        imgProfileImage.set // I do not know what to do here
    }

E/UncaughtException: java.lang.RuntimeException: Unable to start activity ComponentInfo{homologa.cappta.com.br.capptahomologa/homologa.cappta.com.br.capptahomologa.Activity.TelaPrincipalActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'byte[] android.os.Bundle.getByteArray(java.lang.String)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2830) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2909) at android.app.ActivityThread.-wrap11(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1606) at android.os.Handler.dispatchMessage(Handler.java:105) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6592) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:769) Caused by: java.lang. NullPointerException: Attempt to invoke virtual method 'byte[] android.os.Bundle.getByteArray(java.lang.String)' on a null object reference at homologa.cappta.com.br.capptahomologa.Activity.TelaPrincipalActivity.inicializarComponentes(TelaPrincipalActivity.java:180) at homologa.cappta.com.br.capptahomologa.Activity.TelaPrincipalActivity.onCreate(TelaPrincipalActivity.java:101) at android.app.Activity.performCreate(Activity.java:6984) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1235) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2783) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2909) at android.app.ActivityThread.-wrap11(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1606) at android.os.Handler.dispatchMessage(Handler.java:105) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6592) at java.lang.reflect.Method.invoke (Native Method) at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:769) I/Process: Sending signal. PID: 30923 SIG: 9 Application terminated.

Bitmap implements Parcelable interface, so...

You can pass Bitmap through intent.putExtra() with parcelable:

Intent intent = new Intent(this, MyActivity.class);
intent.putExtra("MY_BITMAP", mBitmap);
startActivity(intent);

In new Activity read this extra and put somewhere you want from onCreate method:

Bitmap destinationBitmap = (Bitmap) getIntent().getParcelableExtra ("MY_BITMAP");

You can use Glide image library loading for android

GlideApp.with(this).load(/*your saved value here*/).into(imgProfileImage);

Or you can use Picasso image library loading for android

Picasso.get().load(/*your saved value here*/).into(imgProfileImage);

First Convert your passing image into Byte Array and then pass it through Intent and in next activity get byte array from Bundle and Convert into Image(Bitmap) and set into ImageView.

To convert Bitmap into Imageview:

Bitmap bitmap= BitmapFactory.decodeResource(getResources(), R.drawable.your_image);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();

Pass byte array into intent:-

Intent intent = new Intent(this, NextActivity.class);
intent.putExtra("picture", byteArray);
startActivity(intent);

Get Byte Array from Bundle and Convert into Bitmap Image:-

Bundle extras = getIntent().getExtras();
byte[] byteArray = extras.getByteArray("picture");

Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
ImageView image = (ImageView) findViewById(R.id.imageView1);

image.setImageBitmap(bmp);

I suggest you use a different approach (store it in a file that's more efficient, and less work for you) because it causes the memory costs and your app performance may affect as well while transitioning between activities(it depends on the quality of bitmap).

If your bitmap is small, like a thumbnail etc, pass it as a byte array

Intent objIntent = new Intent(CurrentActivity.this, DestinationActivity.class);
Bitmap objbitmap; // your bitmap
ByteArrayOutputStream bstream = new ByteArrayOutputStream();
objbitmap.compress(Bitmap.CompressFormat.PNG, 80, bs);
objIntent.putExtra("bitmaparray", bstream.toByteArray());
startActivity(objIntent);

Try this:

Using SharedPreferences edit data like this:

 SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPrefsSkip", Context.MODE_PRIVATE);
                            SharedPreferences.Editor editor = pref.edit();
                            editor.putString("username",username); // Storing string
                            editor.putString("phone",phone); 
                            editor.putString("image",image);// Storing string
                            editor.apply();

get data in next activity like this

/* using sharedpref to get data*/
private void getSharedprefData() {
    SharedPreferences prefs = getSharedPreferences("MyPrefsSkip", Context.MODE_PRIVATE);
    username= prefs.getString("username", null);
    phone= prefs.getString("phone", null);
    image= prefs.getString("image", null);
}

using SharedPreferences set data in text view like this:

userName.setText(username);
phone.setText(phone);

set Image Using glide like this:

RequestOptions options = new RequestOptions()
            .centerCrop()
            .placeholder(R.drawable.no_preview)
            .error(R.drawable.no_preview)
            .diskCacheStrategy(DiskCacheStrategy.ALL)
            .priority(Priority.HIGH)
            .dontAnimate()
            .dontTransform();

    Glide.with(context)
            .load(image)
            .apply(options)
            .into(uploadiImage);

i hope it helps you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM