java - org.json.JSONException : No value for id - IMPOSSIBLE TO SOLVE

标签 java android json websocket

http://www.androidhive.info/2014/10/android-building-group-chat-app-using-sockets-part-2/

嗨,

这是一个关于使用套接字编程构建群聊应用程序的教程。这个应用程序允许我们在多个设备(例如 Android 手机和网络)之间聊天。

我想一次向服务器发送多个“字符串”。我很难弄清楚这一点。

上面粘贴了我下载代码的教程的链接。我已经制作了动态网页,并将其托管在 eapps.com 上。这封电子邮件的最底部是该应用程序的编辑代码。如果您点击上面的链接,您可以看到我如何更改它。

它的工作方式是..

A web socket is created using WebSocketClient class and it has all the callback methods like onConnect, onMessage and onDisconnect. In onMessage method parseMessage() is called to parse the JSON received from the socket server. In parseMessage() method, the purpose of JSON is identified by reading the flag value. When a new message is received, the message is added to list view data source and adapter.notifyDataSetChanged() is called to update the chat list. sendMessageToServer() method is used to send the message from android device to socket server. playBeep() method is called to play device’s default notification sound whenever a new message is received.​

当您单击 btnSend 时。它使用 UtilsXd 类中的此方法。我对它做了一些改变,试图传递一个额外的值。

public String getSendMessageJSONXD(String message, String whichPicIndex) {
        String json = null;

        try {
            JSONObject jObj = new JSONObject();
            jObj.put("flag", FLAG_MESSAGE);
            jObj.put("sessionId", getSessionId());
            jObj.put("message", message);
            jObj.put("id", id);
            json = jObj.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return json;
    }

首先,我还是不明白的是,

的值在哪里?
String sessionId = jObj.getString("sessionId");

String onlineCount = jObj.getString("onlineCount");​

通过此方法

private void parseMessage(final String msg, String idINDEX) {

来自。

它们没有添加到 UtilsXD 类中创建的 JSON 对象中,那么它们是如何创建的?

这不是我遇到的问题。这是。

superString 是我想要传递来指示要显示哪张图片的值。

superString = (sharedPrefs.getString("prefSyncAvatar", "1"));​

您可以从设置中更改图片。

当接收到消息时,switch/case 语句根据 superString 传递的值更改接收到的消息的图片。

我应该能够坐在那里接收消息,无论用户传递什么数字,profilePicture 都应该根据该数字进行设置。

这就是问题开始的地方。

此构造函数根据刚刚解析的消息构建消息。

// Message m = new Message(fromName, message, isSelf);
                Message m = new Message(fromName, message, isSelf, id, name,
                        image, status, profilePic, timeStamp, url);

在这个方法中。

private void parseMessage(final String msg, String idINDEX) {

我可以将值传递给字符串“id”,但不包括我需要的 JSON。

String id = idINDEX;​

这有效,

String id = "0";

这有效,

String id = utils.getPictureId();

这有效,

String id = jObj.getString("id");

这不起作用。

这是我遇到的错误。

org.json.JSONException:没有 id 值(这就是问题)

我已添加键/值对

jObj.put("id", id);

public String getSendMessageJSONXD(String message, String whichPicIndex) {​

但它并没有出现在消息中。

我认为问题就出在这里。

方法 onMessage 不能接受额外的参数,因为它来自库项目。我找不到创建新构造函数的方法。

@Override
            public void onMessage(String message) {
                Log.d(TAG, String.format("Got string message! %s", message));

                parseMessage(message, superString);


            }

            @Override
            public void onMessage(byte[] data) {
                Log.d(TAG, String.format("Got binary message! %s",
                        bytesToHex(data)));
                String hello = "99";

                parseMessage(bytesToHex(data), superString);


            }

///////下面是最终代码////////

    // JSON flags to identify the kind of JSON response
        private static final String TAG_SELF = "self", TAG_NEW = "new",
                TAG_MESSAGE = "message", TAG_ID = "id", TAG_EXIT = "exit";



@SuppressWarnings("deprecation")
    @SuppressLint({ "NewApi", "CutPasteId" })
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_chat);

        showUserSettings();
        getActionBar().setTitle("City Chat - Beta 1.3");

        superString = (sharedPrefs.getString("prefSyncAvatar", "1"));

        listView = (ListView) findViewById(R.id.list_view_messages);

        feedItems = new ArrayList<FeedItem>();

        // We first check for cached request

        vollewStuff();
        //
        //
        // THis is where this fun begins

        btnSend = (Button) findViewById(R.id.btnSend);
        inputMsg = (EditText) findViewById(R.id.inputMsg);
        listViewMessages = (ListView) findViewById(R.id.list_view_messages);

        utils = new UtilsXD(getApplicationContext());

        // Getting the person name from previous screen
        Intent i = getIntent();
        name = i.getStringExtra("name");



        Integer.parseInt((sharedPrefs.getString("prefSyncAvatar", "1")));

        btnSend.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // Sending message to web socket server
                sendMessageToServer(utils.getSendMessageJSONXD(inputMsg
                        .getText().toString(), superString), superString);

                utils.storePictureId((sharedPrefs.getString("prefSyncAvatar",

                "1")));

                // Clearing the input filed once message was sent
                inputMsg.setText("");
            }
        });

        listMessages = new ArrayList<Message>();

        adapter = new MessagesListAdapter(this, listMessages, feedItems);
        listViewMessages.setAdapter(adapter);

        /**
         * Creating web socket client. This will have callback methods
         * */
        client = new WebSocketClient(URI.create(WsConfig.URL_WEBSOCKET
                + URLEncoder.encode(name)), new WebSocketClient.Listener() {
            @Override
            public void onConnect() {

            }

            /**
             * On receiving the message from web socket server
             * */
            @Override
            public void onMessage(String message) {
                Log.d(TAG, String.format("Got string message! %s", message));

                parseMessage(message, superString);

                // parseMessage(message,
                // (sharedPrefs.getString("prefSyncAvatar", "1")));

            }

            @Override
            public void onMessage(byte[] data) {
                Log.d(TAG, String.format("Got binary message! %s",
                        bytesToHex(data)));
                String hello = "99";

                parseMessage(bytesToHex(data), superString);

                // Message will be in JSON format
                // parseMessage(bytesToHex(data),
                // (sharedPrefs.getString("prefSyncAvatar", "1")));
            }

            /**
             * Called when the connection is terminated
             * */
            @Override
            public void onDisconnect(int code, String reason) {

                String message = String.format(Locale.US,
                        "Disconnected! Code: %d Reason: %s", code, reason);

                showToast(message);
                //
                // clear the session id from shared preferences
                utils.storeSessionId(null);
            }

            @Override
            public void onError(Exception error) {
                Log.e(TAG, "Error! : " + error);

                // showToast("Error! : " + error);

                showToast("Are you sure you want to leave?");
            }

        }, null);

        client.connect();
    }


    /**
     * Method to send message to web socket server
     * */

    private void sendMessageToServer(String message, String id) {
        if (client != null && client.isConnected()) {
            client.send(message);
            client.send(id);
        }
    }

    /**
     * Parsing the JSON message received from server The intent of message will
     * be identified by JSON node 'flag'. flag = self, message belongs to the
     * person. flag = new, a new person joined the conversation. flag = message,
     * a new message received from server. flag = exit, somebody left the
     * conversation.
     * */

    private void parseMessage(final String msg, String idINDEX) {

        try {
            jObj = new JSONObject(msg);

            // JSON node 'flag'
            String flag = jObj.getString("flag");

            String id = idINDEX;

            // if flag is 'self', this JSON contains session id
            if (flag.equalsIgnoreCase(TAG_SELF)) {

                String sessionId = jObj.getString("sessionId");

                // Save the session id in shared preferences
                utils.storeSessionId(sessionId);

                Log.e(TAG, "Your session id: " + utils.getSessionId());

            } else if (flag.equalsIgnoreCase(TAG_NEW)) {
                // If the flag is 'new', new person joined the room
                String name = jObj.getString("name");
                String message = jObj.getString("message");

                // number of people online
                String onlineCount = jObj.getString("onlineCount");

                showToast(name + message + ". Currently " + onlineCount
                        + " people online!");

            } else if (flag.equalsIgnoreCase(TAG_MESSAGE)) {
                // if the flag is 'message', new message received
                String fromName = name;
                String message = jObj.getString("message");
                String sessionId = jObj.getString("sessionId");

                // switch (Integer.parseInt((sharedPrefs.getString(
                // "prefSyncAvatar", "1"))))

                boolean isSelf = true;

                switch (Integer.parseInt(utils.getPictureId())) {

                case 1:

                    profilePic = "http://clxxxii.vm-host.net/clxxxii/citychatlion.png";

                    break;
                case 2:

                    profilePic = "http://clxxxii.vm-host.net/clxxxii/citychatmatt.png";

                    break;
                case 3:

                    profilePic = "http://clxxxii.vm-host.net/clxxxii/citychatroboman.png";

                    break;
                case 4:

                    profilePic = "http://clxxxii.vm-host.net/clxxxii/citychatalien.png";

                    break;
                case 5:

                    profilePic = "http://clxxxii.vm-host.net/clxxxii/citychatkitty.png";

                    break;

                case 10:

                    profilePic = "http://clxxxii.vm-host.net/clxxxii/citychatkitty.png";

                    break;

                }

                // Checking if the message was sent by you
                if (!sessionId.equals(utils.getSessionId())) {
                    fromName = jObj.getString("name");
                    // profilePic = jObj.getString("profilePic");

                    //
                    //
                    //
                    //
                    jObj.getString("message");
                    isSelf = false;

                    profilePic = "http://clxxxii.vm-host.net/clxxxii/citychatalien.png";
                }

                // profilePic =
                // "http://clxxxii.vm-host.net/clxxxii/citychatlion.png";

                Integer.parseInt(utils.getPictureId());

                String name = "clxxxii";
                String image = "http://i.huffpost.com/gen/1716876/thumbs/o-ATLANTA-TRAFFIC-facebook.jpg";
                String status = "status";
                String timeStamp = "1403375851930";
                String url = "url";

                // Message m = new Message(fromName, message, isSelf);
                Message m = new Message(fromName, message, isSelf, id, name,
                        image, status, profilePic, timeStamp, url);

                // Appending the message to chat list
                appendMessage(m);

            } else if (flag.equalsIgnoreCase(TAG_EXIT)) {
                // If the flag is 'exit', somebody left the conversation
                String name = jObj.getString("name");
                String message = jObj.getString("message");

                showToast(name + message);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

/////////我已经更新了第一个项目的套接字服务器。///////我已成功添加 JSON 值“id”///但我如何更改该值而无需输入“5”,请参见下文..

// 这是我更改的 JSONutilty 方法。 // 公共(public)字符串 getSendAllMessageJson(字符串 sessionId, 字符串 fromName, 字符串消息,字符串 photoId) { 字符串 json = null;

        try {
            JSONObject jObj = new JSONObject();
            jObj.put("flag", FLAG_MESSAGE);
            jObj.put("sessionId", sessionId);
            jObj.put("name", fromName);
            jObj.put("message", message);
            jObj.put("id", photoId);

            json = jObj.toString();

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return json;
    }
}

这是 SocketServer 使用的方法。我可以成功地将消息从此 Activity 发送到实用程序方法以通过网络发送。

                // Normal chat conversation message
                json = jsonUtils //
                        .getSendAllMessageJson(sessionId, name, message, "5");

如何检索通过网络发送的值并将其放置在“5”所在的位置,而不是对其进行硬编码?

谢谢!!!

最佳答案

jobj 没有值id。 JSON 对象的示例如下所示:

{
    "message": " joined conversation!",
    "flag": "new",
    "sessionId": "4",
    "name": "Ravi Tamada",
    "onlineCount": 6
}

(如同一教程的part1所示)。

这解决了 onlineCountsessionId 的第一个问题。

关于java - org.json.JSONException : No value for id - IMPOSSIBLE TO SOLVE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28815583/

相关文章:

java - 任务 ':app:compileDebugNdk' 执行失败无法运行此命令 ndk-build.cmd

android - 为什么我们应该在 Android 中使用 sp 作为字体大小?

javascript - 我想使用 Jquery 在我的网站中嵌入 API 调用

java - Android File.listFiles() 返回 null

php - 来自 YouTube API 的 channel 观看次数?

ios - 使用 Codable 解码具有相似键的嵌套 JSON

java - 使用 Eclipse 调试 GlassFish 全局过滤器

java - Hibernate到MySql的连接字符集是什么?

java - 比较连接字符串和普通字符串

android - 如何创建自定义搜索框