Растровое изображение из RecyclerView в Activity и из Activity в Fragment - PullRequest
0 голосов
/ 25 июня 2018

У меня проблема с восстановлением образа.Я не знаю, как отправить с recyclerViewAdapter на activity и с activity отправить изображение на fragment.С текстовыми или числовыми данными проблем нет, проблема с растровыми данными.

Я восстанавливаю данные из phpmysql:

if($consulta){

    if($reg=mysqli_fetch_array($resultado)){

        $result["nombre"]=$reg['nombre'];
        $result["color"]=$reg['color'];
        $result["texto1"]=$reg['texto1'];
        $result["texto2"]=$reg['texto2'];
        $result["texto3"]=$reg['texto3'];
        $result["texto4"]=$reg['texto4'];
        $result["precio"]=$reg['precio'];
        $result["ancho"]=$reg['ancho'];
        $result["largo"]=$reg['largo'];
        $result["informacion"]=$reg['informacion'];
        $result["imagen"]=base64_encode($reg['foto']);
        $json['datos'][]=$reg;
    }
    mysqli_close($conexion);
    echo json_encode($json);
}

восстановленоданные из PHP в Android:

@Override
public void onResponse(JSONObject response) {
    //Toast.makeText(getContext(),"Conexion",Toast.LENGTH_SHORT).show();

    ListaArticulosPOJO miLista=null;

    JSONArray jsonArray = response.optJSONArray("datos");


    try{
        for (int i=0;i<jsonArray.length();i++){

            miLista= new ListaArticulosPOJO();
            JSONObject jsonObject=null;
            jsonObject = jsonArray.getJSONObject(i);

            miLista.setNombre(jsonObject.optString("nombre"));
            miLista.setColor(jsonObject.optString("color"));
            miLista.setTexto1(jsonObject.optString("texto1"));
            miLista.setTexto2(jsonObject.optString("texto2"));
            miLista.setTexto3(jsonObject.optString("texto3"));
            miLista.setTexto4(jsonObject.optString("texto4"));
            miLista.setPrecio(jsonObject.optDouble("precio"));
            miLista.setAncho(jsonObject.optDouble("ancho"));
            miLista.setLargo(jsonObject.optDouble("largo"));
            miLista.setGrueso(jsonObject.optDouble("grueso"));
            miLista.setInformacion(jsonObject.optString("informacion"));
            miLista.setDatos(jsonObject.optString("fotoArticulo"));


            list.add(miLista);

            recuperaActivity=miLista.getNombre().toString();
        }


    }
    catch (Exception e){
        e.printStackTrace();
    }




    RecyclerViewListaArticulosAdapter adapter=new RecyclerViewListaArticulosAdapter(list,getContext());

    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

    recyclerView.setAdapter(adapter);




}

Я сохраняю данные в Intent в RecyclerView:

public void onBindViewHolder(@NonNull final MyViewHolder holder, final int position) {

    holder.id.setText(mDatos.get(position).getNombre());
    holder.color.setText(mDatos.get(position).getColor());



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


            Intent intent=new Intent(mContext,ArticulosActivity.class);
            Bundle bundle= new Bundle();

            intent.putExtra("nombre",mDatos.get(position).getNombre());
            intent.putExtra("color",mDatos.get(position).getColor());
            intent.putExtra("texto1",mDatos.get(position).getTexto1());
            intent.putExtra("texto2",mDatos.get(position).getTexto2());
            intent.putExtra("texto3",mDatos.get(position).getTexto3());
            intent.putExtra("texto4",mDatos.get(position).getTexto4());
            intent.putExtra("precio",mDatos.get(position).getPrecio());
            intent.putExtra("ancho",mDatos.get(position).getAncho());
            intent.putExtra("largo",mDatos.get(position).getLargo());
            intent.putExtra("grueso",mDatos.get(position).getGrueso());
            //intent.putExtra("foto",mDatos.get(position).getFotoArticulo());

            intent.putExtra("informacion",mDatos.get(position).getInformacion());                intent.putExtra("foto",mDatos.get(position).getFotoArticulo());


            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            mContext.startActivity(intent);


        }
    });

}

Я восстанавливаюданные в упражнении:

static String nombre;
static String color;
static String texto1;
static String texto2;
static String texto3;
static String texto4;
static double precio;
static double ancho;
static double largo;
static double grueso;
static String fotoArticulo;
static String informacion;
static ImageView imageView;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_articulos);

    toolbar = (Toolbar)findViewById(R.id.toolbar_activity_articulos);
    setSupportActionBar(toolbar);


    Intent intent=getIntent();
    nombre=intent.getExtras().getString("nombre");
    color=intent.getExtras().getString("color");
    texto4=intent.getExtras().getString("texto4");
    ancho=intent.getExtras().getDouble("ancho");
    largo=intent.getExtras().getDouble("largo");
    grueso=intent.getExtras().getDouble("grueso");
    precio=intent.getExtras().getDouble("precio");
    informacion=intent.getExtras().getString("informacion");
    fotoArticulo=intent.getExtras().getString("foto");

    //imageView=intent.getExtras().("foto");




    android.support.v4.app.FragmentManager fmLista1= getSupportFragmentManager();
    fmLista1.beginTransaction().replace((R.id.txt_base_articulos_izquierda),new ArticulosListaFragment()).commit();

    android.support.v4.app.FragmentManager fmLista2= getSupportFragmentManager();
    fmLista2.beginTransaction().replace((R.id.txt_base_articulos_derecha),new ArticulosDatosFragment()).commit();
}

Я вызываю данные из фрагмента и показываю их:

public ArticulosDatosFragment() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment


    View vista=inflater.inflate(R.layout.fragment_articulos_datos, container, false);
    articulosActivity =new ArticulosActivity();


    radioGroup=(RadioGroup)vista.findViewById(R.id.txt_radio_group);
    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            if (checkedId==R.id.txt_radio_eh){
                Toast.makeText(getContext(),"EH Pulsado ",Toast.LENGTH_SHORT).show();
            }
            else if(checkedId==R.id.txt_radio_gh){
                Toast.makeText(getContext(),"GH Pulsado ",Toast.LENGTH_SHORT).show();
            }
        }
    });

    *imageView=(ImageView)vista.findViewById(R.id.txt_imagen_articulo);
    //imageView.setImageBitmap(articulosActivity.fotoArticulo);*

    informacion=(TextView)vista.findViewById(R.id.txt_articulo_informacion);
    informacion.setText(articulosActivity.informacion);

    texto1=(TextView)vista.findViewById(R.id.txt_text1);
    texto1.setText(articulosActivity.nombre);

    texto2=(TextView)vista.findViewById(R.id.txt_text2);
    texto2.setText(articulosActivity.color);

    texto3=(TextView)vista.findViewById(R.id.txt_text3);
    texto3.setText(articulosActivity.largo+" x "+articulosActivity.ancho+" x "+articulosActivity.grueso);

    texto4=(TextView)vista.findViewById(R.id.txt_text4);
    texto4.setText(articulosActivity.texto4);

    m2=(TextView)vista.findViewById(R.id.txt_precio_metro);
    m2.setText(articulosActivity.precio+"");


    bedarf=(EditText)vista.findViewById(R.id.txt_cliente_metro);
    boton=(Button)vista.findViewById(R.id.txt_boton_kalkulation);
    boxPrecio=(TextView)vista.findViewById(R.id.txt_precio_box);
    boxTotal=(TextView)vista.findViewById(R.id.txt_metros_total);
    menge=(TextView)vista.findViewById(R.id.txt_metros_total);
    summe=(TextView)vista.findViewById(R.id.txt_precio_total);


    return vista;
}

Как восстановить растровое изображениевведите изображение так же, как я восстанавливаю другие данные.Заранее спасибо за помощь.

Ответы [ 2 ]

0 голосов
/ 25 июня 2018

Что я понял из вашего вопроса, так это то, что вы хотите загрузить изображение, которое вы получили в base64, через json, поэтому я отвечу за это.

Поскольку вы получили base64 в виде строки, предположим, что этоenryptedImageString.

public static Bitmap getBitmapFromEncodedString(String enryptedImageString) {
        if (enryptedImageString != null && !enryptedImageString.equals("")) {

            byte[] decodedString = Base64.decode(enryptedImageString, Base64.DEFAULT);
            Bitmap decodeBitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
            return decodeBitmap;
        } else
            return null;
    }

Этот метод будет возвращать растровое изображение вашего строкового изображения base64.

Теперь ваш фрагмент может иметь следующее:

imageView=(ImageView)vista.findViewById(R.id.txt_imagen_articulo);
imageView.setImageBitmap(getBitmapFromEncodedString(articulosActivity.fotoArticulo));

Проверка на нулевое условие этогометод до.
Также я не рекомендую создавать объект действия, вместо этого вы должны попытаться использовать getActivity (), если фрагмент прикреплен правильно.

Следует избегать полной передачи изображения, так как в некоторых случаях изображение может быть довольнобольшой и лучше передайте URL, разместив его, если это возможно.
И используйте библиотеку Glide или Picasso для непосредственного отображения в режиме просмотра изображений.

0 голосов
/ 25 июня 2018

Вы можете использовать путь к изображению и загрузить его, как задано @Android Team, иначе вы можете преобразовать это растровое изображение в байтовый массив, а затем передать его в намерение через intent.putExtra и получить то же самое.

Вы можете попробовать преобразование растрового изображения с этим кодом:

Bitmap bmp = intent.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
bmp.recycle();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...