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

时间:2015-04-16 06:05:27

标签: java android bytearray

我正在尝试将一个字节数组从活动A传递给活动B,但由于某种原因,该变量突然变为空。我一直想弄清楚发生了什么,但我找不到解决方案,也许你可以帮助我。 这是我的活动代码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 );
    }
}

活动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();
    }
}

在活动B的代码中,即使在for循环中打印keys->值之后,变量“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

感谢任何帮助,谢谢!

2 个答案:

答案 0 :(得分:4)

下面:

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

使用imag_plato密钥名称传递空间。使用key with-out space character:

intentDetalle.putExtra("imag_plato", imag_plato);

答案 1 :(得分:1)

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