安卓无法从意图(Intent)中获取字节数组。

4
我正在尝试从一个活动向另一个活动发送byte[]。在接收活动中,获取意图额外信息后,byte[]似乎为null。有什么想法吗?
谢谢。
Button save = (Button)findViewById(R.id.save);
         save.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                touchView.isSaved = true;
                Bundle bundle = new Bundle();
                bundle.putByteArray("byteArr", touchView.data);
                Intent intent = new Intent(mContext, SavePic.class);

                intent.putExtra(bundle );



                startActivity(intent);


            }}) ;

.

 public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.savepic);


        final EditText edittext = (EditText) findViewById(R.id.edittext);
        edittext.setText("");

        edittext.setOnKeyListener(new OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                // If the event is a key-down event on the "enter" button
                if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
                    (keyCode == KeyEvent.KEYCODE_ENTER)) {
                  // Perform action on key press

                    Bundle extras = getIntent().getExtras();
                    byte [] arr = extras.getByteArray("byteArr");
                    if(arr != null){
                        Log.e("xxxxxx", "********* arr not null");
                    }else{
                        Log.e("xxxxxx", "********* arr is null");
                    }
                      final Bitmap mCBitmap2 = BitmapFactory.decodeByteArray(arr, 0, arr.length);

[更新]我已更改关键值,使它们不是相同的数据 / bytrArr,同时意图现在只传递一个Bundle。

3个回答

8
键的值不是你的问题。您并没有以相同的方式检索数据,而是将其放入其中。 在代码的第一部分中,您正在将byte []放入Bundle中,然后将该Bundle放入Intent extras中。这意味着键为“data”的EXTRA是Bundle,而不是byte []。您无需以此方式插入额外内容。只需执行intent.putExtra("byteArr", touchView.data) 将byte [] 作为Extra插入即可。 通过这样做,您将能够在第二个代码部分中使用getIntent().getByteArrayExtra("byteArr") 检索回您的byte []。 最后,只是顺便提一下,如果您确实有多个Extra要应用于一个调用,则可以将每个Extra放入Bundle中,然后调用Intent.putExtras(bundle) ,以使来自Bundle的所有数据都单独放置到Intent中。但这与将该Bundle作为Extra本身添加并不相同。 希望对您有所帮助。

你好,我已经按照你的建议修改了代码,但是它仍然在 arr 数组上抛出 NPE 异常。 - turtleboy
嗨,我刚刚再次测试了一下,你是正确的。这与我的代码有关,第一次启动应用程序时未设置数组数据。谢谢。 - turtleboy

0
不要给额外参数起同样的键名,要取一个不同的名字。
只需调用intent.putExtra(bundle);将bundle放入意图中即可。

0

替换

intent.putExtra("data",bundle );

intent.putExtras(bundle );


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接