Android 使用onActivityResult

Android 使用onActivityResult,android,Android,我试着从我的图库中挑选一幅图像。 我强制使用startActivityForResult,因为我的类不扩展活动,我需要使用onActivityResult来设置图像视图和所选图像。 我的代码 Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT); getIntent.setType("image/*"); Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provide

我试着从我的图库中挑选一幅图像。 我强制使用startActivityForResult,因为我的类不扩展活动,我需要使用onActivityResult来设置图像视图和所选图像。 我的代码

Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT);
getIntent.setType("image/*");
Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pickIntent.setType("image/*");

Intent chooserIntent = Intent.createChooser(getIntent, "Elegir imagen");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{pickIntent});            
((Activity)context).startActivityForResult(chooserIntent, INTENT_ELEGIR_IMAGEN);
我的onActivityResult

public void onActivityResult(int requestCode, int resultCode, Intent data)
{
    if (resultCode == Activity.RESULT_OK) {
        switch (requestCode) {
            case INTENT_ELEGIR_IMAGEN:
                Uri selectedImageUri = data.getData();

                if(selectedImageUri !=null) {
                    try {
                        fotoJugador.setImageBitmap(decodeUri(selectedImageUri));
                        imageSelected = true;
                    } catch (FileNotFoundException e) {
                        throw new RuntimeException(e);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
                break;
        }
    }
}
如果没有解决方案,请给出建议!! 谢谢 我添加了完整的代码

公共类seccionadapterjugadorequipmoinfo扩展了RecyclerView.Adapter{
私人名单;
公共设备;
私有静态RecycleServiceClickListener itemListener;
私有上下文c;
公共静态类seccionjugadorinfoiwholder扩展
RecyclerView.ViewHolder{
//在本例中,每个数据项只是一个字符串
公共图像视图fotoJugador;
//公共图像视图埃斯库多;
公共文本视图nombreJugador;
公共文本视图;
公共文本视图位置;
公共文本视图阿尔图拉;
公共CardView简历;
公共图像视图菜单;
公共秘书长(视图五){
超级(五);
//fotoJugador=(ImageView)v.findViewById(R.id.fotoEquipoJugadorInfo);
fotoJugador=(图像视图)v.findviewbyd(R.id.fotoJugador);
nombreJugador=(TextView)v.findViewById(R.id.nombreJugadorInfo);
posicion=(TextView)v.findViewById(R.id.posicionjugatorequipmoinfo);
//nombreEquipo=(TextView)v.findViewById(R.id.nombreEquipoJugadorInfo);
//nombreEquipo=(TextView)v.findViewById(R.id.nombreEquipoJugadorInfo);
cv=(CardView)v.findViewById(R.id.CardViewJugadoInfo);
menu=(ImageView)v.findviewbyd(R.id.menu);
最终复选框=(复选框)v.findviewbyd(R.id.star);
}
}
公共秘书长(装备e、名单、上下文c){
this.equipo=equipo;
this.jugadores=jugadores;
这个.c=c;
}
@凌驾
public com.followup.arielverdugo.followup.seccionadapterjugadorequipmoinfo.seccionjugadorinfoiwholder onCreateViewHolder(视图组父级、,
int视图类型){
视图v=LayoutInflater.from(parent.getContext())
.充气(R.layout.activity\u card\u EquipadoInfo,父级,假);
返回新的com.followup.arielverdugo.followup.seccionadapterjugatorequipmoinfo.seccionjugadorinfoiwholder(v);
}
@凌驾
BindViewHolder上的公共无效(最终com.followup.arielverdugo.followup.seccionadapterjugadorEquipmoinfo.seccionjugadorInfo视图持有人,最终int i){
final int id=jugadores.get(i).getId();
if(jugadores.get(i).getFoto()!=null){
位图fotoJugador=BitmapFactory.decodeByteArray(jugadores.get(i).getFoto(),0,jugadores.get(i).getFoto().length);
viewHolder.fotoJugador.setImageBitmap(fotoJugador);
}否则{
viewHolder.fotoJugador.setImageResource(R.drawable.sinimagen);
}
viewHolder.nombreJugador.setText(jugadores.get(i).getNombre()+“”+jugadores.get(i).getApellido());
viewHolder.posicion.setText(jugadores.get(i.getPosicion());
viewHolder.menu.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
showPopupMenu(viewHolder.menu,i、c、id);
}
});
}
私有void显示弹出菜单(视图、整型位置、上下文上下文、整型id){
//充气菜单
PopupMenu popUp=新的PopupMenu(view.getContext(),view);
MenuInflater充气器=弹出窗口。getMenuInflater();
充气器。充气(R.menu.delete_edit_equipmoinfo,popUp.getMenu());
popUp.setOnMenuItemClickListener(新的com.followup.arielverdugo.followup.MyMenuItemClickListener(位置,c,id));
popUp.show();
}
//返回数据集的大小(由布局管理器调用)
@凌驾
public int getItemCount(){
返回jugadores.size();
}
}

MyMenuItemClickListener类实现了PopupMenu.OnMenuItemClickListener{ 私有回收视图。适配器lastmAdapter; 私人职位; 私人语境; 私有int-id; 私人图像视图fotoJugador; 公共静态最终int int int int int int int int int int ENT\u ELEGIR\u IMAGEN=1; private Boolean imageSelected=false; 公共MyMenuItemClickListener(整数位置、上下文上下文、整数id){ 这个位置=位置; this.context=上下文; this.id=id; } @凌驾 公共布尔onMenuItemClick(MenuItem MenuItem){ 开关(menuItem.getItemId()){ 案例R.id.editarJugadorEquipo: final Jugador jugadorEditar=JugadorRepository.getInstance(context.findJugadorById(id)); LayoutFlater充气器=(LayoutFlater)context.getSystemService(context.LAYOUT\u充气器\u服务); 最终视图组PopupViewEdtar=(视图组)充气器。充气(R.layout.dialog_editar_jugador,null); 字符串nombreainterior=jugadorEditar.getNombre(); 字符串apellidoAnterior=jugadorEditar.getApellido(); 字节[]fotointerior=jugadorEditar.getFoto(); EditText nombre=(EditText)popupViewEditar.findViewById(R.id.editarNombreJugador); nombre.setText(nombreinterior); EditText-apellido=(EditText)popupViewEditar.findViewById(R.id.EditarPellidoJugador); apellido.setText(apellidoAnterior); 如果(FOTOINTERIOR==null) { fotoJugador=(ImageView)popupViewEditar.findviewbyd(R.id.editarFotoJugador); fotoJugador.setImageResource(R.drawable.anadirimagen); fotoJugador.setOnClickListener(新视图.OnClickListener(){ @凌驾 公共void onClick(视图v){ //伽利略宫酒店 Intent getIntent=新意图(Intent.ACTION\u GET\u CONTENT); getIntent.setType(“image/*”); Intent pickIntent=newintent(Intent.ACTION\u PICK,android.provider.MediaStore.Images.Media.EXTERNAL\u CONTENT\u URI);
public class SeccionAdapterJugadorEquipoInfo extends RecyclerView.Adapter<com.followup.arielverdugo.followup.SeccionAdapterJugadorEquipoInfo.SeccionJugadorInfoViewHolder> {
private List<Jugador> jugadores;
public Equipo equipo;

private static RecyclerViewClickListener itemListener;
private Context c;


    public static class SeccionJugadorInfoViewHolder extends 
     RecyclerView.ViewHolder{
    // each data item is just a string in this case
    public ImageView fotoJugador;
    //public ImageView escudo;
    public TextView nombreJugador;
    public TextView nombreEquipo;
    public TextView posicion;
    public TextView altura;
    public CardView cv;
    public ImageView menu;


    public SeccionJugadorInfoViewHolder(View v) {
        super(v);

        //fotoJugador = (ImageView) v.findViewById(R.id.fotoEquipoJugadorInfo);
        fotoJugador = (ImageView) v.findViewById(R.id.fotoJugador);
        nombreJugador = (TextView) v.findViewById(R.id.nombreJugadorInfo);
        posicion = (TextView) v.findViewById(R.id.posicionJugadorEquipoInfo);
        //nombreEquipo = (TextView) v.findViewById(R.id.nombreEquipoJugadorInfo);
        //nombreEquipo = (TextView) v.findViewById(R.id.nombreEquipoJugadorInfo);
        cv = (CardView) v.findViewById(R.id.cardViewJugadorEquipoInfo);
        menu =(ImageView) v.findViewById(R.id.menu);
        final CheckBox checkBox = (CheckBox) v.findViewById(R.id.star);
    }

}

public SeccionAdapterJugadorEquipoInfo(Equipo e, List<Jugador> jugadores ,Context c) {
    this.equipo = equipo;
    this.jugadores = jugadores;
    this.c=c;

}



@Override
public com.followup.arielverdugo.followup.SeccionAdapterJugadorEquipoInfo.SeccionJugadorInfoViewHolder onCreateViewHolder(ViewGroup parent,
                                                                                                                          int viewType) {
    View v = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.activity_card_jugadorequipoinfo, parent, false);

    return new com.followup.arielverdugo.followup.SeccionAdapterJugadorEquipoInfo.SeccionJugadorInfoViewHolder(v);
}


@Override
public void onBindViewHolder(final com.followup.arielverdugo.followup.SeccionAdapterJugadorEquipoInfo.SeccionJugadorInfoViewHolder viewHolder, final int i) {


    final int id = jugadores.get(i).getId();
    if(jugadores.get(i).getFoto() != null){
        Bitmap fotoJugador = BitmapFactory.decodeByteArray(jugadores.get(i).getFoto(), 0, jugadores.get(i).getFoto().length);
        viewHolder.fotoJugador.setImageBitmap(fotoJugador);

    } else {
        viewHolder.fotoJugador.setImageResource(R.drawable.sinimagen);
    }


    viewHolder.nombreJugador.setText(jugadores.get(i).getNombre() + " " +jugadores.get(i).getApellido());
    viewHolder.posicion.setText(jugadores.get(i).getPosicion());
    viewHolder.menu.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            showPopupMenu(viewHolder.menu,i,c,id);
        }
    });

}

private void showPopupMenu(View view,int position,Context context,int id) {
    // inflate menu
    PopupMenu popUp = new PopupMenu(view.getContext(),view);
    MenuInflater inflater = popUp.getMenuInflater();
    inflater.inflate(R.menu.delete_edit_jugadorequipoinfo, popUp.getMenu());
    popUp.setOnMenuItemClickListener(new com.followup.arielverdugo.followup.MyMenuItemClickListener(position,c,id));
    popUp.show();


}




// Return the size of your dataset (invoked by the layout manager)
@Override
public int getItemCount() {
    return jugadores.size();
}
class MyMenuItemClickListener implements PopupMenu.OnMenuItemClickListener{

private RecyclerView.Adapter lastmAdapter;
private int position;
private Context context;
private int id;
private ImageView fotoJugador;
public static final int INTENT_ELEGIR_IMAGEN = 1;
private Boolean imageSelected = false;



public MyMenuItemClickListener(int positon,Context context,int id) {
    this.position=positon;
    this.context = context;
    this.id = id;
}

@Override
public boolean onMenuItemClick(MenuItem menuItem) {
    switch (menuItem.getItemId()) {
        case R.id.editarJugadorEquipo:
            final Jugador jugadorEditar = JugadorRepository.getInstance(context).findJugadorById(id);

            LayoutInflater inflater = (LayoutInflater) context.getSystemService( context.LAYOUT_INFLATER_SERVICE);
            final ViewGroup popupViewEditar = (ViewGroup) inflater.inflate(R.layout.dialog_editar_jugador, null);
            String nombreAnterior = jugadorEditar.getNombre();
            String apellidoAnterior = jugadorEditar.getApellido();
            byte[] fotoAnterior = jugadorEditar.getFoto();


            EditText nombre = (EditText) popupViewEditar.findViewById(R.id.editarNombreJugador);
            nombre.setText(nombreAnterior);
            EditText apellido = (EditText) popupViewEditar.findViewById(R.id.editarApellidoJugador);
            apellido.setText(apellidoAnterior);


            if (fotoAnterior == null)
            {
                fotoJugador = (ImageView) popupViewEditar.findViewById(R.id.editarFotoJugador);
                fotoJugador.setImageResource(R.drawable.anadirimagen);
                fotoJugador.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        //para ir a la galeria
                        Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT);
                        getIntent.setType("image/*");

                        Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        pickIntent.setType("image/*");

                        Intent chooserIntent = Intent.createChooser(getIntent, "Elegir imagen");
                        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{pickIntent});

                        //utiliza la constante INTENT_ELEGIR_IMAGEN en onActivityResult
                        ((Activity) context).startActivityForResult(chooserIntent, INTENT_ELEGIR_IMAGEN);
                        onActivityResult(chooserIntent);



                    }
                });

            }
            else
            {
                fotoJugador = (ImageView) popupViewEditar.findViewById(R.id.editarFotoJugador);

                Bitmap bitmap = BitmapFactory.decodeByteArray(fotoAnterior, 0, fotoAnterior.length);
                fotoJugador.setImageBitmap(bitmap);

                fotoJugador.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        //para ir a la galeria
                        Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT);
                        getIntent.setType("image/*");

                        Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        pickIntent.setType("image/*");

                        Intent chooserIntent = Intent.createChooser(getIntent, "Elegir imagen");
                        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{pickIntent});

                        //utiliza la constante INTENT_ELEGIR_IMAGEN en onActivityResult
                        ((Activity) context).startActivityForResult(chooserIntent, INTENT_ELEGIR_IMAGEN);
                        onActivityResult(chooserIntent);





                    }
                });
            }
            //se crea y llena el spiner de equipos
            List<Equipo> equipos = EquipoRepository.getInstance(context).getEquipos();
            ArrayList<String> equiposNombre = new ArrayList<>();
            for (int i = 0; i < equipos.size(); i++)
            {
                equiposNombre.add(equipos.get(i).getNombre());
            }

            final Spinner spinnerEquipos = (Spinner) popupViewEditar.findViewById(R.id.editarEquipoJugador);
            ArrayAdapter<String> adapter;
            adapter = new ArrayAdapter<String>(context,R.layout.spinner_equipos, equiposNombre);
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            //Cree una clase NothingSelectedSpinnerAdapter y un xml Spinner_row_selected
            spinnerEquipos.setAdapter(adapter);
            String compareValue = jugadorEditar.getEquipo().getNombre();

            if (!compareValue.equals(null)) {
                int spinnerPosition = adapter.getPosition(compareValue);
                spinnerEquipos.setSelection(spinnerPosition);
            }


            //se crea y llena el spinner de posciones
            ArrayList<String> posicionesJugadores = new ArrayList<>();
            posicionesJugadores.add("Base");
            posicionesJugadores.add("Ayuda Base");
            posicionesJugadores.add("Alero");
            posicionesJugadores.add("Ala Pivot");
            posicionesJugadores.add("Pivot");

            final Spinner spinnerPosiciones = (Spinner) popupViewEditar.findViewById(R.id.editarPosicionJugador);
            ArrayAdapter<String>adapterPosiciones;
            adapterPosiciones = new ArrayAdapter<String>(context,R.layout.spinner_posicion, posicionesJugadores);
            adapterPosiciones.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinnerPosiciones.setAdapter(adapterPosiciones);
            String compareValuePosicion = jugadorEditar.getPosicion();

            if (!compareValuePosicion.equals(null)) {
                int spinnerPosition = adapterPosiciones.getPosition(compareValuePosicion);
                spinnerPosiciones.setSelection(spinnerPosition);
            }

            //se crea y llena el spinner de altura

            Integer alturaMinima = 160;
            Integer alturaMaxima = 221;
            Integer step = 1;
            String[] myValues = getArrayWithSteps(alturaMinima, alturaMaxima, step);
            NumberPicker picker = new NumberPicker(context);
            picker.setDisplayedValues(myValues);
            picker.setWrapSelectorWheel(false);

            final Spinner spinnerAlturas = (Spinner) popupViewEditar.findViewById(R.id.editarAlturaJugador);
            ArrayAdapter<String> adapterAltura;
            adapterAltura = new ArrayAdapter<String>(context,R.layout.spinner_altura, myValues);
            adapterAltura.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinnerAlturas.setAdapter(adapterAltura);
            int alturaJugador = jugadorEditar.getAltura();
            String compareValueAltura = Integer.toString(alturaJugador);

            if (!compareValueAltura.equals(null)) {
                int spinnerPosition = adapterAltura.getPosition(compareValueAltura);
                spinnerAlturas.setSelection(spinnerPosition);
            }



            AlertDialog.Builder builderEditar =
                    new AlertDialog.Builder(context)
                            .setTitle("Editar Jugador")
                            .setPositiveButton("Editar", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    // capturar y gaurdadr en bd
                                    final String NOMBRE = (((TextView) popupViewEditar.findViewById(R.id.editarNombreJugador)).getText().toString());
                                    final String APELLIDO = (((TextView) popupViewEditar.findViewById(R.id.editarApellidoJugador)).getText().toString());
                                    Bitmap FOTO = null;
                                    FOTO = ((BitmapDrawable) ((ImageView) popupViewEditar.findViewById(R.id.editarFotoJugador)).getDrawable()).getBitmap();

                                    jugadorEditar.setNombre(NOMBRE);
                                    jugadorEditar.setApellido(APELLIDO);
                                    jugadorEditar.setFoto(Utils.getByteArrayFromBitmap(FOTO));

                                    JugadorRepository.getInstance(context).updateJugador(jugadorEditar);
                                    Toast.makeText(context, "Jugador editado", Toast.LENGTH_SHORT).show();

                                    //se refresca el cardview

                                    dialog.dismiss();

                                }
                            })
                            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.cancel();
                                }
                            });
            builderEditar.setView(popupViewEditar);
            builderEditar.show();

            break;


        case R.id.eliminarJugadorEquipo:
            AlertDialog.Builder builderEliminar;

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                builderEliminar = new AlertDialog.Builder(context, android.R.style.Theme_Material_Dialog_Alert);
            } else {
                builderEliminar = new AlertDialog.Builder(context);
            }
            builderEliminar.setTitle("Delete entry")
                    .setMessage("Are you sure you want to delete this entry?")
                    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            JugadorRepository.getInstance(context).deleteJugadorById(id);
                            Equipo e = EquipoRepository.getInstance(context).findEquipoById(JugadorEquipoInfoActivity.idEquipo);
                            lastmAdapter = new com.followup.arielverdugo.followup.SeccionAdapterJugadorEquipoInfo(e,new ArrayList<Jugador>(e.jugadores),context);
                            FragmentJugadorEquipoInfo.mRecyclerViewStatic.setAdapter(lastmAdapter);
                        }
                    })
                    .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            // do nothing
                            dialog.cancel();
                        }
                    })
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .show();

            break;
        default:
    }
    return false;
}

public void onActivityResult(int requestCode, int resultCode, Intent data)
{
    if (resultCode == Activity.RESULT_OK) {
        switch (requestCode) {
            case INTENT_ELEGIR_IMAGEN:
                Uri selectedImageUri = data.getData();

                if(selectedImageUri !=null) {
                    try {
                        fotoJugador.setImageBitmap(decodeUri(selectedImageUri));
                        imageSelected = true;
                    } catch (FileNotFoundException e) {
                        throw new RuntimeException(e);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
                break;
        }
    }
}




private  Bitmap decodeUri(Uri selectedImage) throws FileNotFoundException {
    BitmapFactory.Options o = new BitmapFactory.Options();
    o.inJustDecodeBounds = true;

    BitmapFactory.decodeStream(context.getContentResolver().openInputStream(selectedImage), null, o);
    // The new size we want to scale to
    final int REQUIRED_SIZE = 150;

    // Find the correct scale value. It should be the power of 2.
    int width_tmp = o.outWidth, height_tmp = o.outHeight;
    int scale = 1;
    while (true) {
        if (width_tmp / 2 < REQUIRED_SIZE
                || height_tmp / 2 < REQUIRED_SIZE) {
            break;
        }
        width_tmp /= 2;
        height_tmp /= 2;
        scale *= 2;
    }

    // Decode with inSampleSize
    BitmapFactory.Options o2 = new BitmapFactory.Options();
    o2.inSampleSize = scale;
    return BitmapFactory.decodeStream(context.getContentResolver().openInputStream(selectedImage), null, o2);

}

public String[] getArrayWithSteps(Integer iMinValue,Integer iMaxValue, Integer iStep)
{
    double iStepsArray = iMaxValue-iMinValue; //obtengo el largo del array

    String[] arrayValues= new String[(int)iStepsArray]; //creo un array de ese largo
    arrayValues[0] = String.valueOf(iMinValue);

    for(int i = 1; i < iStepsArray; i++)
    {
        arrayValues[i] = String.valueOf(Integer.parseInt(arrayValues[i-1])+iStep);
    }

    return arrayValues;
}
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, 0);
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == 0 && resultCode == RESULT_OK && data != null && data.getData() != null) {

        Uri uri = data.getData();

        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);

            fotoJugador.setImageBitmap(bitmap);
            imageSelected = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}