org.json.JSONException:id的无值 - 不可能解决 [英] org.json.JSONException: No value for id - IMPOSSIBLE TO SOLVE

查看:209
本文介绍了org.json.JSONException:id的无值 - 不可能解决的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这是一个关于建立使用套接字编程群聊应用程序的教程。这个程序可以让我们像Android的手机和网络的多个设备之间的聊天。

This is a tutorial about building a group chat app using socket programming. This app allows us to chat between multiple devices like android mobiles and web.

我想送一多串在同一时间到服务器。我无法搞清楚了这一点。

I want to send more than one "String" at a time to the server. I'm having trouble figuring that out.

到本教程的链接,我下载了code上面粘贴。我已经做动态网页,我把它托管在eapps.com在这封邮件是编辑code为应用程序的最底部。如果你点击上面的链接,你可以看到我是如何改变了它。

The link to the tutorial where I downloaded the code is pasted above. I've already made the dynamic web page and I have it hosted on eapps.com At the very bottom of the this email is the edited code for the app. If you click the link above, you can see how I changed it.

它的工作方式是...

The way it works is..

一个网络插座使用WebSocketClient类,它有所有的回调方法类似的onConnect,和的onMessage创建onDisconnect。
  在onMessage方法parseMessage()被调用来解析从套接字服务器接收到的JSON。
  在parseMessage()方法,JSON的目的是通过读取标志值确定。
  当收到新邮件,添加邮件列表视图的数据源和adapter.notifyDataSetChanged()被调用以更新聊天列表。
  sendMessageToServer()方法用于从Android设备将消息发送到socket服务器。
  playBeep()方法被调用打每当收到新信息设备的默认的通知声音。

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类此方法。我已经改变了一点,试图传递一个额外的价值。

When you click the btnSend. it uses this method from the UtilsXd class. I've changed it a little in an attempt to pass an extra value.

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

首先,我仍然不明白的是,在这里做的值

First of all, what I still don't understand is, where did the values for

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

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

此方法

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

从何而来。

他们were't在UtilsXD类创建的JSON对象添加,因此它们是如何产生的?

They were't added in the JSON object created in the UtilsXD class so how are they created?

这不是我有问题。这是

超弦理论是我想要的值传递给决定显示哪些图片。

superString is the value I want to pass to dictate which picture to show.

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

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

You can change your picture in from the settings.

当接收到一个消息,一个开关/ case语句更改/为根据超弦理论传递的值接收消息的图片。

When a message is received, a switch/case statement changes the picture of/ for the message received according to the value passed by superString.

我应该能够坐在那里,只是接收邮件,和任何数量的用户通过,profilePicture应该按照这个数字来设定。

I should be able to sit there and just receive messages, and whatever number the user passes, the profilePicture should be set according to that number.

这里的问题开始的地方。

Here's where the problem begins.

这个建筑工建立了基于这只是被解析的消息的消息。

This constructer builds a message based of the message that's just been parsed.

// 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

I can pass an value to the string "id" excluding the JSON I need it to.

String id = idINDEX;​

这个作品,

String id = "0";

这个作品,

String id = utils.getPictureId();

这个作品,

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

这是行不通的。

这是我得到的错误。

org.json.JSONException:id的无值(这是问题)

org.json.JSONException: No value for id (this is the issue)

我添加键/值对

jObj.put("id", id);

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

但它不来,虽然该消息。

but it's not coming though to the message.

下面就是我认为这个问题是。

Here's where I think the problem is.

该方法的onMessage,是不是不能,因为它从一个库项目是需要一个额外的参数。我不能找到方法,使一个新的构造。

The method onMessage, isn't can't take an extra parameter because it's from a library project. And I can't find that method to make a new constructor.

@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);


            }

///////下面是最终code低于////////

/////// Here's the final code below ////////

    // 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,请参见下面的。

///////// I've updated the socket server from the first project. /////// I've added the JSON value "id" successfully /// But I how do I change the value without having to type in "5" please see below..

//
这是JSONutilty方法我改变。
//
    公共字符串getSendAllMessageJson(字符串的sessionId,字符串FROMNAME,
                字符串消息,串PHOTOID){
            JSON字符串= NULL;

// This is the JSONutilty method I changed. // 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的方法。我可以成功地从这次活动发送消息,以实用的方法来通过网络发送。

This is the method that is being used by SocketServer. I can successfully send a message from this activity, to the utility method to send over the network.

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

我如何可以检索网络上发送的一个值点的地方在那里我有5,而不是硬编码呢?

How can I retrieve a value sent over the network to place in spot where I have "5" instead of hard coding it?

谢谢!

推荐答案

jobj 不具有值 ID 。 JSON对象的示例如下:

jobj doesn't have the value id. Example of the JSON object looks like this:

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

(如图中的第1部分相同教程)。

这解决了第一个问题 onlineCount 的sessionId

That solves the first issue of onlineCount and sessionId.

这篇关于org.json.JSONException:id的无值 - 不可能解决的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆