如何使用捆绑Android Studio将图像传输到其他活动



这里我想问如何将从数据库中检索到的数据从RecyclerViewAdapter发送到另一个活动(UpdateActivity(。

这是我的RecyclerViewAdapter,它将发送图像


import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.request.BaseRequestOptions;
import com.bumptech.glide.request.RequestOptions;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>{
private ArrayList<data_mahasiswa> listMahasiswa;
private Context context;
//    Interface delete data
public interface dataLinstener{
void onDeleteData(data_mahasiswa data, int position);
}
dataLinstener linstener;
//    konstruktor input data
public RecyclerViewAdapter(ArrayList<data_mahasiswa> listMahasiswa, Context context) {
this.listMahasiswa = listMahasiswa;
this.context = context;
//        delete fungsi listener
linstener = (ListData)context;
}
@NonNull
@Override
public RecyclerViewAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_design, parent,false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull RecyclerViewAdapter.ViewHolder holder, int position) {
//        Mengambil Nilai/Value yang terdapat pada rcview berdasarkan posisi
final String gambar = listMahasiswa.get(position).getGambar();
final String NIM = listMahasiswa.get(position).getNim();
final String Nama = listMahasiswa.get(position).getNama();
final String Fakultas = listMahasiswa.get(position).getFakultas();
final String Prodi = listMahasiswa.get(position).getProdi();
final String Tanggal = listMahasiswa.get(position).getTanggal_lahir();
final String Phone = listMahasiswa.get(position).getPhone();
final String Email = listMahasiswa.get(position).getEmail();
final String IPK = listMahasiswa.get(position).getIpk();
final String Alamat = listMahasiswa.get(position).getAlamat();
final String Golongan_Darah = listMahasiswa.get(position).getGolonggan_darah();
final String Jenis_Kelamin = listMahasiswa.get(position).getJenis_kelamin();

//        mengisi nilai
BaseRequestOptions requestOptions = (RequestOptions) ((RequestOptions) ((RequestOptions) ((RequestOptions) ((RequestOptions) new RequestOptions().format(DecodeFormat.PREFER_ARGB_8888)).override(Integer.MIN_VALUE)).placeholder((int) R.color.purple_200)).centerCrop()).fitCenter();
if (gambar == null) {
holder.Gambar.setImageResource(R.drawable.ic_baseline_person_100);
ViewHolder viewHolder = holder;
String str = NIM;
} else {
Glide.with(holder.itemView.getContext()).load(gambar.toString().trim()).apply(requestOptions).into(holder.Gambar);
}
holder.NIM.setText("NIM tttt: " + NIM);
holder.Nama.setText("Nama ttt: " + Nama);
holder.Fakultas.setText("Fakultas tt: " + Fakultas);
holder.Prodi.setText("Prodi ttt: " + Prodi);
holder.Tanggal.setText("Tanggal tt: " + Tanggal);
holder.Phone.setText("No Phone t: " + Phone);
holder.Email.setText("Email ttt: " + Email);
holder.IPK.setText("IPK tttt: " + IPK);
holder.Alamat.setText("Alamat tt: " + Alamat);
holder.Golongan_Darah.setText("Golongan Darah tt: " + Golongan_Darah);
holder.Jenis_Kelamin.setText("Jenis Kelamin ttt: " + Jenis_Kelamin);
holder.ListItem.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
final String[] action = {"Update","Delete"};
AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
builder.setItems(action, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case 0:
//                        aktivity update / fungsi update
Bundle bundle = new Bundle();
bundle.putString("dataNIM", listMahasiswa.get(position).getNim());
bundle.putString("dataNama", listMahasiswa.get(position).getNama());
//                                Menggunakan spinner
bundle.putString("dataFakultas", listMahasiswa.get(position).getFakultas());
bundle.putString("dataProdi",listMahasiswa.get(position).getProdi());
bundle.putString("dataTanggal", listMahasiswa.get(position).getTanggal_lahir());
bundle.putString("dataPhone",listMahasiswa.get(position).getPhone());
bundle.putString("dataEmail",listMahasiswa.get(position).getEmail());
bundle.putString("dataIPK",listMahasiswa.get(position).getIpk());
bundle.putString("dataAlamat",listMahasiswa.get(position).getAlamat());
//                        kurang golongan darah dan gender / menggunakan radio
bundle.putString("dataGolongan_Darah",listMahasiswa.get(position).getGolonggan_darah());
bundle.putString("dataJenis_Kelamin",listMahasiswa.get(position).getJenis_kelamin());
//                        gambar
**bundle.putString("dataGambar",listMahasiswa.get(position).getGambar());**
//                        primary key
bundle.putString("getPrimaryKey",listMahasiswa.get(position).getKey());
Intent intent = new Intent(v.getContext(), UpdateActivity.class);
intent.putExtras(bundle);
context.startActivity(intent);

break;
case 1:
linstener.onDeleteData(listMahasiswa.get(position), position);
break;
}
}
});
builder.create();
builder.show();
return true;
}
});
}
@Override
public int getItemCount() {
return listMahasiswa.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView NIM, Nama, Fakultas, Prodi, Tanggal, Phone, Email, IPK, Alamat, Golongan_Darah, Jenis_Kelamin;
private ImageView Gambar;
private LinearLayout ListItem;
public ViewHolder(@NonNull View itemView) {
super(itemView);
Gambar = itemView.findViewById(R.id.ivGambar);
NIM = itemView.findViewById(R.id.tvNim);
Nama = itemView.findViewById(R.id.tvNama);
Fakultas= itemView.findViewById(R.id.tvFakultas);
Prodi= itemView.findViewById(R.id.tvProdi);
Tanggal= itemView.findViewById(R.id.tvTanggal);
Phone= itemView.findViewById(R.id.tvPhone);
Email = itemView.findViewById(R.id.tvEmail);
IPK= itemView.findViewById(R.id.tvIPK);
Alamat = itemView.findViewById(R.id.tvAlamat);
Golongan_Darah= itemView.findViewById(R.id.tvGolongan_Darah);
Jenis_Kelamin= itemView.findViewById(R.id.tvJenis_Kelamin);
ListItem = itemView.findViewById(R.id.list_items);
}
}
}

这是将接收图像(UpdateActivity(的活动

package com.example.presentasi;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.UUID;
import static android.text.TextUtils.isEmpty;
public class UpdateActivity extends AppCompatActivity {
//    tambahan spinner
private String[] ListProdi,ListFakultas;
private Button Update;
private EditText NIM, Nama, Phone, Email, IPK, Alamat,Tanggal;
private Spinner Fakultas, Prodi;
private ImageButton PilihGambar;
private ImageView ViewGambar;
private CheckBox gdA, gdB, gdAB, gdO;
private RadioButton Pria, Wanita;
private String cekNIM,cekNama,cekPhone,cekEmail,cekIPK,cekAlamat;
private DatabaseReference getReference;
//    tanggal
Calendar calendar;
DatePickerDialog datePickerDialog;
//    image pilih
private Bitmap bitmap;
private Uri gambarUri;

//    Upload
private String getNIM,getNama,getPhone,getEmail,getIPK,getAlamat,getFakultas,getProdi,getTanggal_Lahir,getGambar,getJenis_Kelamin,getGolongan_Darah;
private StorageReference reference = FirebaseStorage.getInstance().getReference();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
getSupportActionBar().setTitle("Update Data");
//        Button
Update = findViewById(R.id.btUpdate);
Tanggal = findViewById(R.id.btTanggal);
//        EditText
NIM = findViewById(R.id.etNim);
Nama = findViewById(R.id.etNama);
Phone = findViewById(R.id.etPhone);
Email = findViewById(R.id.etEmail);
IPK = findViewById(R.id.etIpk);
Alamat = findViewById(R.id.etAlamat);
//        Spinner
Fakultas = findViewById(R.id.spFakultas);
Prodi= findViewById(R.id.spProdi);
//        Image
ViewGambar = findViewById(R.id.ivGambar);
PilihGambar = findViewById(R.id.ibGambar);
//        Checkbox
gdA = findViewById(R.id.cbA);
gdB = findViewById(R.id.cbB);
gdAB = findViewById(R.id.cbAB);
gdO = findViewById(R.id.cbO);
//        RadioButton
Pria = findViewById(R.id.rbPria);
Wanita= findViewById(R.id.rbWanita);
FirebaseDatabase database = FirebaseDatabase.getInstance();
getReference = database.getReference();
getData();
Update.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getNIM = NIM.getText().toString();
getNama = Nama.getText().toString();
getPhone = Phone.getText().toString();
getEmail = Email.getText().toString();
getIPK = IPK.getText().toString();
getAlamat = Alamat.getText().toString();
getFakultas = Fakultas.getSelectedItem().toString();
getProdi = Prodi.getSelectedItem().toString();
if (gdA.isChecked()){
getGolongan_Darah = gdA.getText().toString();
gdB.setChecked(false);
gdAB.setChecked(false);
gdO.setChecked(false);
}else {
}if(gdB.isChecked()){
getGolongan_Darah = gdB.getText().toString();
gdA.setChecked(false);
gdAB.setChecked(false);
gdO.setChecked(false);
}else {
}if (gdAB.isChecked()){
getGolongan_Darah = gdAB.getText().toString();
gdA.setChecked(false);
gdB.setChecked(false);
gdO.setChecked(false);
}else {
}if (gdO.isChecked()){
getGolongan_Darah = gdO.getText().toString();
gdA.setChecked(false);
gdAB.setChecked(false);
gdB.setChecked(false);
}else {
}
if(Pria.isChecked()){
getJenis_Kelamin = Pria.getText().toString();
}else {
}if(Wanita.isChecked()){
getJenis_Kelamin = Wanita.getText().toString();
}
getTanggal_Lahir = Tanggal.getText().toString();
Toast.makeText(UpdateActivity.this,"Upload Data",Toast.LENGTH_SHORT).show();
checkUser();
}
});
//        Date Picker
Tanggal.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
calendar = Calendar.getInstance();
int hari = calendar.get(Calendar.DAY_OF_MONTH);
int bulan = calendar.get(Calendar.MONTH);
int tahun = calendar.get(Calendar.YEAR);
datePickerDialog = new DatePickerDialog(UpdateActivity.this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
Tanggal.setText(dayOfMonth + "/" + (month + 1) + "/" + year);
}
}, hari,bulan,tahun);
datePickerDialog.show();
}
});
PilihGambar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
UpdateActivity.this.getimage();
}
});
}
private void getData(){
**int resId =  getIntent().getExtras().getInt("dataGambar");**
**ViewGambar.setImageResource(resId); **
final String getNIM = getIntent().getExtras().getString("dataNIM");
final String getNama = getIntent().getExtras().getString("dataNama");

//        spinner
final String getFakultas = getIntent().getExtras().getString("dataFakultas");
final String getProdi = getIntent().getExtras().getString("dataProdi");
ListFakultas = new String[]{"Ilmukomputer","Ekonomi"};
ArrayAdapter<String> fakultasadapter = new ArrayAdapter<String>(this,R.layout.support_simple_spinner_dropdown_item,ListFakultas);
Fakultas.setAdapter(fakultasadapter);
Fakultas.setSelection(fakultasadapter.getPosition(getFakultas.trim()));
ListProdi = new String[]{"Informatika","Sistem Informasi","Bisnis Digital","Teknologi Informasi"};
ArrayAdapter<String> prodiadapter = new ArrayAdapter<String>(this,R.layout.support_simple_spinner_dropdown_item,ListProdi);
Prodi.setAdapter(prodiadapter);
Prodi.setSelection(prodiadapter.getPosition(getProdi.trim()));

final String getTanggal = getIntent().getExtras().getString("dataTanggal");
final String getPhone = getIntent().getExtras().getString("dataPhone");
final String getEmail = getIntent().getExtras().getString("dataEmail");
final String getIPK = getIntent().getExtras().getString("dataIPK");
final String getAlamat = getIntent().getExtras().getString("dataAlamat");
//        mengambil data golongan dan jenis kelamin
if ("A".equals(getIntent().getExtras().getString("dataGolongan_Darah"))){
gdA.setChecked(true);
}else if ("B".equals(getIntent().getExtras().getString("dataGolongan_Darah"))){
gdB.setChecked(true);
}else if ("AB".equals(getIntent().getExtras().getString("dataGolongan_Darah"))){
gdAB.setChecked(true);
}else if ("O".equals(getIntent().getExtras().getString("dataGolongan_Darah"))) {
gdO.setChecked(true);
}
if ("Pria".equals(getIntent().getExtras().getString("dataJenis_Kelamin"))){
Pria.setChecked(true);
}else if ("Wanita".equals(getIntent().getExtras().getString("dataJenis_Kelamin"))){
Wanita.setChecked(true);
}

NIM.setText(getNIM);
Nama.setText(getNama);
Tanggal.setText(getTanggal);
Phone.setText(getPhone);
Email.setText(getEmail);
IPK.setText(getIPK);
Alamat.setText(getAlamat);
}
//    private void updateMahasiswa(data_mahasiswa mahasiswa){
//        String getKey = getIntent().getExtras().getString("getPrimaryKey");
//        getReference.child("Admin")
//                .child("Mahasiswa")
//                .child(getKey)
//                .setValue(mahasiswa)
//                .addOnSuccessListener(new OnSuccessListener<Void>() {
//                    @Override
//                    public void onSuccess(Void aVoid) {
//                        NIM.setText("");
//                        Nama.setText("");
//                        Phone.setText("");
//                        Email.setText("");
//                        IPK.setText("");
//                        Alamat.setText("");
//                        Tanggal.setText("");
//                        Toast.makeText(UpdateActivity.this, "Data Terupdate", Toast.LENGTH_SHORT).show();
//                        finish();
//                    }
//                });
//    }
//    Pilih gambar
private void getimage() {
AlertDialog.Builder dialog = new AlertDialog.Builder(this).setTitle("Upload Image").setItems(new CharSequence[]{"Galeri"}, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
UpdateActivity.this.startActivityForResult(new Intent("android.intent.action.PICK", MediaStore.Images.Media.EXTERNAL_CONTENT_URI), 2);
}
});
dialog.create();
dialog.show();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 2 && resultCode == -1 && data != null) {
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), data.getData());
}catch (IOException e){
e.printStackTrace();
}
Uri data2 = data.getData();
this.gambarUri = data2;
this.ViewGambar.setImageURI(data2);
}
}
private void checkUser(){
if(isEmpty(getNIM) && isEmpty(getNama) && isEmpty(getTanggal_Lahir) && isEmpty(getPhone) && isEmpty(getEmail) && isEmpty(getIPK) && isEmpty(getAlamat)) {
Toast.makeText(UpdateActivity.this, "Data tidak boleh ada yang kosong", Toast.LENGTH_SHORT).show();
}else{
String getKey = getIntent().getExtras().getString("getPrimaryKey");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream);
reference.child("gambar/"+(UUID.randomUUID() + ".jpg")).putBytes(stream.toByteArray()).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
taskSnapshot.getStorage().getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
UpdateActivity.this.getReference.child("Admin").child("Mahasiswa").child(getKey)
.setValue(new com.example.presentasi.data_mahasiswa(getNIM, getNama, getFakultas, getProdi, getGolongan_Darah, getJenis_Kelamin, getTanggal_Lahir, getPhone, getEmail, getIPK, getAlamat, uri.toString().trim()))
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
NIM.setText("");
Nama.setText("");
Fakultas.setSelection(0);
Prodi.setSelection(0);
if(gdA.isChecked()){
gdA.setChecked(false);
}else if (gdB.isChecked()){
gdB.setChecked(false);
}else if (gdAB.isChecked()){
gdAB.setChecked(false);
}else if (gdO.isChecked()){
gdO.setChecked(false);
}
if(Pria.isChecked()){
Pria.setChecked(false);
}else if(Wanita.isChecked()){
Wanita.setChecked(false);
}
Tanggal.setText("klik untuk memilih tanggal lahir");
Phone.setText("");
Email.setText("");
IPK.setText("");
Alamat.setText("");;
Toast.makeText(UpdateActivity.this,"Upload Berhasil",Toast.LENGTH_SHORT).show();
UpdateActivity.this.ViewGambar.setImageResource(R.drawable.ic_baseline_person_100);
startActivity(new Intent(UpdateActivity.this,ListData.class));
}
});
}
});
}
});
}
}

}

这是简单的代码如何发送

bundle.putString("dataGambar",listMahasiswa.get(position).getGambar());       

如何接收

int resId =  getIntent().getExtras().getInt("dataGambar");
ViewGambar.setImageResource(resId);

将图像传输到另一个图像的方法是将图像转换为字节数组。

要做到这一点,我们首先必须将图像转换为位图。

  1. 将图像转换为位图

Bitmap myLogo = BitmapFactory.decodeResource(context.getResources(), R.drawable.my_drawable);

参考:如何将可绘制的图像从资源转换为位图

  1. 将位图转换为字节数组
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();

参考:将Java位图转换为字节数组

  1. 将数组传递给意图
Intent intent = new Intent(this, NextActivity.class);
intent.putExtra("picture", byteArray);
startActivity(intent);
  1. 在下一个活动中获取tha值
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);

相关内容

  • 没有找到相关文章

最新更新