Новичок
Профиль
Группа: Участник
Сообщений: 4
Регистрация: 24.4.2009
Репутация: нет Всего: нет
|
Вобщем беда, пытаюсь сделать клиент чата для мобилки, но что-то я не могу понять где подводный камень, при отправке сообщения (sendCommand) происходит непонятное, выскакивает исключение с сообщением что в lstChat.setFont(....) не правильный индекс, хотя в остальных моментах, где вызывается apptolist всё хорошо! Листинг:Код | package socket;
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import javax.microedition.io.ConnectionNotFoundException; import javax.microedition.io.Connector; import javax.microedition.io.StreamConnection; import javax.microedition.midlet.*; import javax.microedition.lcdui.*;
public class CommMobile extends MIDlet implements CommandListener, Runnable { private static final String str_connect = "Соедениться"; private static final String str_disconnect = "Отключиться"; private Image img_connect, img_error; private static Display display; private List lstMainMenu; // Окно главного меню private List lstChat; // Окно чата private Font smallFont, bigFont; // Мелкий шрифт для лога чата private TextBox textBox; // Ввод нового сообщения private boolean isPaused; // Флаг состояния паузы private boolean stop; // Флаг остановки сокетов private StreamConnection sc; // Сокет для связи private DataInputStream dis; // Входяший поток данных private DataOutputStream dos; // Исходящий поток данных private Thread thread = new Thread(this);; // Поток для работы с сокетом private Command exitCommand = new Command("Выход", Command.EXIT, 1); private Command okCommand = new Command("Выбрать", Command.ITEM, 1); private Command sendCommand = new Command("Отправить", Command.SCREEN, 1); private Command edtmsgCommand = new Command("Написать", Command.SCREEN, 1); private Command mainmenuCommand = new Command("Меню", Command.BACK, 1); private Command backCommand = new Command("Назад", Command.BACK, 1);
public CommMobile() { super(); try { img_connect = Image.createImage("/images/connect24.png"); img_error = Image.createImage("/images/error48.png"); } catch (Exception e) { e.printStackTrace(); Alert a = new Alert("Ошибка #1", e.getMessage(), null, AlertType.ERROR); a.setTimeout(Alert.FOREVER); a.setCommandListener(this); display.setCurrent(a); } display = Display.getDisplay(this);
lstMainMenu = new List("Главное меню", List.IMPLICIT); lstMainMenu.append(str_connect, img_connect); lstMainMenu.addCommand(exitCommand); lstMainMenu.addCommand(okCommand); lstMainMenu.setCommandListener(this);
lstChat = new List("Чат", List.IMPLICIT); lstChat.addCommand(mainmenuCommand); lstChat.addCommand(edtmsgCommand); lstChat.setCommandListener(this); textBox = new TextBox("Текст сообщения", null, 100, TextField.ANY); textBox.addCommand(sendCommand); textBox.addCommand(backCommand); textBox.setCommandListener(this); display.setCurrent(lstMainMenu); }
private synchronized void addtolist(String s, Image i) { try { if (lstChat.size() > 20) { lstChat.delete(0); } lstChat.setFont(lstChat.append(s, i), smallFont); // -------------------------------- ТУТ ПРОИСХОДИТ ИСКЛЮЧЕНИЕ lstChat.setSelectedIndex(lstChat.size()-1, true); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); Alert a = new Alert("Ошибка #2", e.getMessage(), img_error, AlertType.ERROR); a.setTimeout(Alert.FOREVER); display.setCurrent(a, lstMainMenu); } }
public boolean isPaused() { return isPaused; }
public void startApp() { isPaused = false; }
public void pauseApp() { isPaused = true; }
public void destroyApp(boolean unconditional) { stop = true; }
public void commandAction(Command c, Displayable s) { if (c == exitCommand) { destroyApp(true); notifyDestroyed(); } else if ((c == List.SELECT_COMMAND || c == okCommand) && s == lstMainMenu) { String name = lstMainMenu.getString(lstMainMenu.getSelectedIndex()); if (name.equals(str_connect)) { thread.start(); } if (name.equals(str_disconnect)) { stop = true; } } else if (c == mainmenuCommand) { display.setCurrent(lstMainMenu); } else if (c == edtmsgCommand) { display.setCurrent(textBox); } else if (c == backCommand) { if (s == textBox) { display.setCurrent(lstChat); } } else if (c == sendCommand) { // try { dos.write(textBox.getString()); dos.write("\r\n"); addtolist(textBox.getString(), null); // ---------------------------------- ВЫЗОВ ОТСЮДА textBox.setString(null); display.setCurrent(lstChat); } catch (IOException ex) { System.out.println(ex.getMessage()); ex.printStackTrace(); Alert a = new Alert("Ошибка #3 \"Ввода/Вывода\"", ex.getMessage(), img_error, AlertType.ERROR); a.setTimeout(Alert.FOREVER); display.setCurrent(a, lstChat); } } }
public void run() { try { sc = (StreamConnection)Connector.open("socket://"+Properties.host()); addtolist("Соединение установлено...", null); dis = sc.openDataInputStream(); dos = sc.openDataOutputStream(); display.setCurrent(lstChat); lstMainMenu.set(0, str_disconnect, img_connect); while (!stop) { String str = new String(dis.readUTF()); if (str.length() > 0) { addtolist(str, null); } } } catch (ConnectionNotFoundException cnfe) { System.out.println(cnfe.getMessage()); cnfe.printStackTrace(); Alert a = new Alert("Ошибка #4 подключения", "Невозможно подключиться к серверу", img_error, AlertType.ERROR); a.setTimeout(Alert.FOREVER); display.setCurrent(a, lstMainMenu); } catch (IOException ioe) { System.out.println(ioe.getMessage()); ioe.printStackTrace(); if (!stop) { Alert a = new Alert("Ошибка #5 \"Ввода/Вывода\"", ioe.getMessage(), img_error, AlertType.ERROR); a.setTimeout(Alert.FOREVER); display.setCurrent(a, lstMainMenu); } } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); Alert a = new Alert("Ошибка #6", e.getMessage(), img_error, AlertType.ERROR); a.setTimeout(Alert.FOREVER); display.setCurrent(a, lstMainMenu); } finally { stop = true; try { if (dis != null) { dis.close(); }
if (dos != null) { dos.close(); }
if (sc != null) { sc.close(); } } catch (Exception e) { } lstMainMenu.set(0, str_connect, img_connect); addtolist("Соединение закрыто...", null); display.setCurrent(lstMainMenu); } } }
|
Это сообщение отредактировал(а) frutty - 24.4.2009, 01:53
|