【问题标题】:Can i cast from a String (containing my Object reference) to an Object ? Android Studio [closed]我可以从 String (包含我的 Object 引用)转换为 Object 吗? Android Studio [关闭]
【发布时间】:2019-05-11 12:42:12
【问题描述】:

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

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

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

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

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

【问题讨论】:

    标签: java android casting bluetooth


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 我应该序列化什么?购物类?谢谢
    • 没错。序列化获取一个对象并将其转换为字符串(或字节数组)表示。该字符串可以发送到另一部手机,反序列化将重新创建具有相同内容的对象。序列化技术有很多,比如xml、json或者Java内置的序列化。
    • 实现parcelable到你的对象(pojo/entity)
    • 我编辑了我的帖子并包含了代码,你能看一下吗?谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-30
    • 2018-07-16
    • 1970-01-01
    • 1970-01-01
    • 2014-10-22
    相关资源
    最近更新 更多