0

わかりました、これをできる限り最善の方法で説明します。

私はチャット アプリケーションを持っており、パブリック チャンネルのリストを受け取るリクエストを送信しています。サーバーから返される文字列は次のとおりです。

RESP_PUBLICCHANNELLIST, channelID 1, channelName 1, channelID 2, channelName 2

このリストを AlertDialog に追加すると、各チャネルとチャネル ID が個別のチャネルとして表示されます。AlertDialog にチャンネル名を入れて、キー値を持つマップにチャンネル ID を入れたいと思います。これは可能ですか?

問題が発生している現在のコードは次のとおりです。

 public void ShowPublicChannelList(){

     String PublicChannelsPost = "";
     PublicChannelsPost = ExecuteCommand(_chatProtocol.ShowPublicChannelList());
     System.out.println("Public Channels: " + PublicChannelsPost);
     _publicChannels.add("New..");

     List <String> responseList = Arrays.asList(PublicChannelsPost.split(","));
        if (responseList.contains("RESP_PUBLICCHANNELLIST")){
            for (int i = 1; i < responseList.size(); i++) {
                _publicChannels.add(responseList.get(i));
                System.out.println("Channels: " + _publicChannels);
            }   
                SetPublicChannelList(_publicChannels);
                }

どんな助けでも素晴らしいでしょう!

ありがとうございました!

4

1 に答える 1

1

If I understand your question correctly, you're unsure about how to parse the server response into a mapping of a channel ID and name? You could simply step through your list of separated strings with steps of two and populate every pair into a single map entry. This does make the assumption that a channel id is always followed by a channel name (or vice versa: every name is preceded by an id).

if (responseList.contains("RESP_PUBLICCHANNELLIST")) {
    Map<String, String> channelMap = new HashMap<String, String>();
    for (int i=1; i<responseList.size(); i+=2) {
        if (i+1 >= responseList.size()) break; // this only happens if not every id has name
        channelMap.put(responseList.get(i), responseList.get(i+1));
    }

    // print values to check correct mapping
    for (Map.Entry<String, String> channel : channelMap.entrySet()) System.out.println(channel.getKey() + " | " +channel.getValue());
}

As you can see, I simply break the loop if the length of the source list is 'unexpected'. you might want to consider implementing something more robust, unless you're absolutely sure the illegal case will never arise.

于 2012-04-09T02:45:48.673 に答える