在 bundle 中传递字节数组变为 null

Passing a byte array inside bundle becomes null

我正在尝试将字节数组从 activity A 传递到 activity B,但由于某种原因,变量突然变为空。我一直在试图弄清楚发生了什么,但我还没有找到解决方案,也许你可以帮助我。 这是我的 activity A:

代码
    @Override
public void respond( String desc_plato, byte[] imag_plato ){
        System.out.println("des plato: "+desc_plato);
        System.out.println("image plato: "+imag_plato);

        if( imag_plato != null )
        {
            System.out.println("HERE IMAG_PLATO IS NOT NULL");
        }

        Intent intentDetalle = new Intent( this, PlatosDetalle.class );
        intentDetalle.putExtra("desc_plato", desc_plato);
        intentDetalle.putExtra("imag_plato ", imag_plato);
        startActivity( intentDetalle );
    }
}

代码在 activity B:

@Override
protected void onCreate(Bundle savedInstanceState) {
    // excluding common code here... then:
    System.out.println("PlatosDetalle onCreate");

    Bundle PlatosIntent = getIntent().getExtras();
    String desc_plato = PlatosIntent.getString("desc_plato");
    byte[] imagen_plato = PlatosIntent.getByteArray("imag_plato");
    // I GOT THIS CODE FROM ANOTHER ANSWER, TO CHECK KEYS ON INTENT
    /**************************************************/
    for (String key : PlatosIntent.keySet()) {
        Object value = PlatosIntent.get(key);
        System.out.println("BUNDLE KEYS:"+ String.format("%s %s\n", key,  
            value.toString()));
    }
    System.out.println( imagen_plato );
    /************************************************/


    if( imagen_plato == null )
    {
        System.out.println("HERE IMAGEN_PLATO IS NULL");
        finish();
    }
}

在 activity B 的代码中,即使在 for 循环中打印键-> 值之后变量 "imagen_plato" 已经为空...

这是我的 logCat,或者至少是我用 System.out.println 做的日志:

04-16 02:04:35.915: I/System.out(5072): des plato: Pizza especial para clientes vegetarianos
04-16 02:04:35.925: I/System.out(5072): image plato: [B@41a80170
04-16 02:04:35.925: I/System.out(5072): HERE IMAG_PLATO IS NOT NULL
04-16 02:04:35.955: I/Choreographer(5072): Skipped 132 frames!  The application may be doing too much work on its main thread.
04-16 02:04:36.015: I/System.out(5072): PlatosDetalle onCreate
04-16 02:04:36.015: I/System.out(5072): BUNDLE KEYS:desc_plato Pizza especial para clientes vegetarianos
04-16 02:04:36.015: I/System.out(5072): BUNDLE KEYS:imag_plato  [B@41757c48
04-16 02:04:36.015: I/System.out(5072): null
04-16 02:04:36.015: I/System.out(5072): HERE IMAGEN_PLATO IS NULL

感谢任何帮助,谢谢!!!

这里:

 intentDetalle.putExtra("imag_plato ", imag_plato);
                                   ^

传递 space 和 imag_plato 键名。使用不带 space 字符的键:

intentDetalle.putExtra("imag_plato", imag_plato);

正如@ρяσѕρєя-k 指出的那样,使用正确的键来放置和获取字节数组。最好创建一些常量并在您的代码中将它们用作键,这样您就不必每次都将键作为文字键入。这将有助于在未来消除所有这些类型的问题。