首页 > 解决方案 > 我可以从 String (包含我的 Object 引用)转换为 Object 吗?安卓工作室

问题描述

我目前正在通过蓝牙将一个对象(购物)从一个用户发送到另一个用户。当我从服务器电话单击“发送”按钮时,对象购物已正确发送,我通过Log.d(StringNameOfShopping)

但我只能发送bytes[]数组,将其转换为 int 字节然后创建一个new String(buffer[], offset, bytes)

那么有没有一种方法可以从 String (例如,我的对象 Shopping 参考 : Shopping@bd429a9)转换为 Shopping 对象?

这是我收听输入和输出的方法。

    public void run(){

        byte[] buffer = new byte[1024];  // buffer store for the stream

        int bytes; // bytes returned from read()

        // Keep listening to the InputStream until an exception occurs
        while (true) {
            // Read from the InputStream
            try {
                bytes = mmInStream.read(buffer);
                String incomingMessage = new String(buffer, 0, bytes);
                Log.d(TAG, "InputStream: " + incomingMessage);
            } catch (IOException e) {
                Log.e(TAG, "write: Error reading Input Stream. " + e.getMessage() );
                break;
            }
        }
    }

    //Call this from the main activity to send data to the remote device
    public void write(byte[] bytes) {
        String text = new String(bytes, Charset.defaultCharset());
        Log.d(TAG, "write: Writing to outputstream: " + text);
        try {
            mmOutStream.write(bytes);
        } catch (IOException e) {
            Log.e(TAG, "write: Error writing to output stream. " + e.getMessage() );
        }
    }

这是我的序列化/反序列化方法(但是我应该把它们放在哪里?在我的 MainActivity 或购物类中?或蓝牙类?

public byte[] serialize(Shopping shopping) throws IOException {
    ByteArrayOutputStream b = new ByteArrayOutputStream();
    ObjectOutputStream o = new ObjectOutputStream(b);
    o.writeObject(shopping);
    return b.toByteArray();
}

//AbstractMessage was actually the message type I used, but feel free to choose your own type
public static Shopping deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
    ByteArrayInputStream b = new ByteArrayInputStream(bytes);
    ObjectInputStream o = new ObjectInputStream(b);
    return (Shopping) o.readObject();
}

标签: javaandroidcastingbluetooth

解决方案


这是行不通的,因为另一部手机无法解析自己内存中的对象。您需要在一部手机上序列化您的对象并在另一部手机上反序列化它。

关于您的编辑:您已决定使用 Java 的序列化机制。为此,您需要Serializable在 Shopping 中实现接口。这只是一个“标记接口”,即它没有方法,只是表明该类可以与 Java 的序列化工具一起使用。

下一步是使用您要传输serialize的实例调用该方法。Shopping这为您提供了一个包含序列化对象的字节数组。现在您可以write使用此字节数组调用该函数。

在接收端,您需要将整个输入流读入一个字节数组。然后可以传递这个数组deserialize来获取Shopping实例。


推荐阅读