org.json.JSONException:没有id的值 - 不可能解决

时间:2015-03-02 17:10:35

标签: java android json websocket dynamic-websites

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

您好,

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

我想发送多个" String"一次到服务器。我很难搞清楚这一点。

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

它的工作方式是......

  

使用WebSocketClient类创建Web套接字,它具有所有回调方法,如onConnect,onMessage和onDisconnect。   在onMessage方法中,调用parseMessage()来解析从套接字服务器接收的JSON。   在parseMessage()方法中,通过读取标志值来标识JSON的用途。   收到新消息时,消息将添加到列表视图数据源,并调用adapter.notifyDataSetChanged()以更新聊天列表。   sendMessageToServer()方法用于将消息从android设备发送到套接字服务器。   每当收到新消息时,都会调用pl​​ayBeep()方法播放设备的默认通知声音。

单击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值&#34; id&#34;成功///但我如何更改值而无需键入&#34; 5&#34;请看下面..

// 这是我改变的JSONutilty方法。 //     public String getSendAllMessageJson(String sessionId,String fromName,                 String message,String photoId){             String 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正在使用的方法。我可以成功地从此活动发送消息,以实用方法通过网络发送。

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

如何检索通过网络发送的值以放置在我所拥有的位置&#34; 5&#34;而不是硬编码吗?

感谢!!!

2 个答案:

答案 0 :(得分:2)

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

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

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

这解决了第一期onlineCountsessionId

答案 1 :(得分:1)

谢谢@miselking,你在哪里正确,服务器缺少JSON字符串&#34; id&#34;。要真正解决帖子的问题。

&#34;我想发送多个&#34; String&#34;一次到服务器。我很难搞清楚这一点。&#34;

你就是这样做的。

步骤1)

将字符串photoId添加到方法

public String getSendAllMessageJson(String sessionId, String fromName,
            String message, String photoId) {
        String 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;
    }
}

步骤2)

将字符串添加到方法的正确位置。

  String json = null;
  json = jsonUtils 
  .getSendAllMessageJson(sessionId, name, message,
                                    photoId);

步骤3)解析JSON

    try {
            JSONObject jObj = new JSONObject(message);
            msg = jObj.getString("message");
            photoId = jObj.getString("id");
        } catch (JSONException e) {
            e.printStackTrace();
        }