http://www.androidhive.info/2014/10/android-building-group-chat-app-using-sockets-part-2/org.json.JSONException:id的無值 - 不可能解決
嗨,
這是一個關於建立使用套接字編程羣聊應用程序的教程。這個應用程序允許我們在Android手機和網絡等多種設備之間進行聊天。
我想一次向服務器發送多個「字符串」。我很難解決這個問題。
上面粘貼了我下載代碼的教程的鏈接。我已經制作了動態網頁,並將其託管在eapps.com上。此電子郵件的最底部是應用程序的編輯代碼。如果你點擊上面的鏈接,你可以看到我是如何改變它的。
它的工作方式是..
一個網絡插座使用WebSocketClient類創建的,它具有所有的回調方法類似的onConnect,和的onMessage onDisconnect。 在onMessage方法中,調用parseMessage()來解析從套接字服務器接收到的JSON。 在parseMessage()方法中,通過讀取標誌值來識別JSON的用途。 收到新消息時,消息將被添加到列表視圖數據源和adapter.notifyDataSetChanged()以更新聊天列表。 sendMessageToServer()方法用於將消息從android設備發送到套接字服務器。 只要收到新消息,就會調用playBeep()方法播放設備的默認通知聲音。
當您單擊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;
}
首先,我還是不明白的是,在此方法
private void parseMessage(final String msg, String idINDEX) {
沒有爲
String sessionId = jObj.getString("sessionId");
和
String onlineCount = jObj.getString("onlineCount");
值來自。
它們沒有添加到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(這是問題)在
public String getSendMessageJSONXD(String message, String whichPicIndex) {
,但它是沒有價值
我已經添加了鍵/值對
jObj.put("id", id);
沒有來到消息。
這是我認爲問題出在哪裏。
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();
}
}
/////////我已經更新了socket服務器的最終代碼來自第一個項目。 ///////我已經成功添加了JSON值「id」///但是我該如何更改數值而不必輸入「5」請參閱下面的內容..
// This是我改變的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");
如何檢索通過網絡發送的值,以便在現場放置「5」而不是硬編碼它?
謝謝!
的ID號值意味着您的JSONObject這麼想的包含的值id,所以檢查你的JSON。 – 2015-03-02 17:22:24