Аватар для 4damir4
4 / 4 / 1
Регистрация: 14.10.2011
Сообщений: 36

try{} catch(){}

14.10.2011, 11:49. Показов 3771. Ответов 18
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Как достать строковую переменную из try{} catch(){}
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
          //Создаем форму
          Form firstForm=new Form("Добро пожаловать");
 
try {
                      String s; 
 
                      storage = RecordStore.openRecordStore ("Baza", true); // предварительные ласки
 
                      s = new String(storage.getRecord (1)); // взятие строки из хранилища в котором хранится строка "Vasya"
 
                      storage.closeRecordStore(); //закрываем RecordStore
 
   }
              catch (RecordStoreException err) {}
 
          //Добавляем строку
          firstForm.append(s);
          //Делаем окно формы видимым     
          display.setCurrent(firstForm);
В данном примере форма не видит переменную s. Получается ошибка – s переменная не инициализирована.

Я объявляю, но в форме выводится null (точней совсем не чего не выводится). А мне надо строчку из памяти телефона. А вставляется пустая переменная.
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
14.10.2011, 11:49
Ответы с готовыми решениями:

блок try {} catch() и быстродействие.
Приветствую! Проблема встала об оптимизации ВСЕГО кода по быстродействию. Пришлось уделять внимание таким мелочам, как циклы с...

Проблема с возвращающим значением метода в блоке try-catch
Поставил блок try -catch, начало ругаться на значение return myArray;, которое должен вернуть метод. Что ни так? public static double...

Проблема с закрытием InputStream: try { dataStream.close(); } catch (Exception e) {...}
сам inputStream получаю с урла, а проблема возникает при следующем коде: URL dataURL = new URL(...); URLConnection dataConn =...

18
 Аватар для mutagen
2587 / 2260 / 257
Регистрация: 14.09.2011
Сообщений: 5,185
Записей в блоге: 18
14.10.2011, 14:19
вынеси String s; за границы блока try
0
 Аватар для 4damir4
4 / 4 / 1
Регистрация: 14.10.2011
Сообщений: 36
16.10.2011, 10:29  [ТС]
Я объявляю, но в форме выводится null (точней совсем не чего не выводится).

Добавлено через 42 минуты
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
  String s;
  private TextField TFName; 
...
           TFName=new TextField("Укажите имя","",50,TextField.ANY);
...
          //Создаем форму
          Form firstForm=new Form("Добро пожаловать");
 
try {
                      
                      storage = RecordStore.openRecordStore ("Baza", true); // предварительные ласки
 
                        byte [] b = TFName.getString().getBytes(); 
 
                       storage.setRecord (1,b, 0, TFName.getString().length()); // запись строки
 
                      s = new String(storage.getRecord (1)); // взятие строки из хранилища в котором хранится строка "Vasya"
 
                      storage.closeRecordStore(); //закрываем RecordStore
 
   }
              catch (RecordStoreException err) {}
 
          //Добавляем строку
          firstForm.append(s);
          //Делаем окно формы видимым     
          display.setCurrent(firstForm);
0
 Аватар для mutagen
2587 / 2260 / 257
Регистрация: 14.09.2011
Сообщений: 5,185
Записей в блоге: 18
16.10.2011, 13:52
Если ты добавишь обработку исключения то увидишь почему в блоке try эта переменная не получает значение
0
 Аватар для 4damir4
4 / 4 / 1
Регистрация: 14.10.2011
Сообщений: 36
16.10.2011, 13:55  [ТС]
я новичок в яве. напишите пожалуйста что добавить?
0
 Аватар для mutagen
2587 / 2260 / 257
Регистрация: 14.09.2011
Сообщений: 5,185
Записей в блоге: 18
16.10.2011, 13:56
Мне вообще не понятно зачем гонять строку в массив и назад

Добавлено через 33 секунды
Давай код рекрдсторе
0
 Аватар для 4damir4
4 / 4 / 1
Регистрация: 14.10.2011
Сообщений: 36
16.10.2011, 13:58  [ТС]
оно так роботает. как все таки проверить?
0
 Аватар для mutagen
2587 / 2260 / 257
Регистрация: 14.09.2011
Сообщений: 5,185
Записей в блоге: 18
16.10.2011, 14:24
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
        RecordStore rs = null;
        try {
            rs = RecordStore.openRecordStore("tst", true);
        } catch (RecordStoreException ex) {
            ex.printStackTrace();
        }
        TextField TFName=new TextField("Укажите имя","",50,TextField.ANY);
        byte [] b = TFName.getString().getBytes(); 
        try {
            rs.setRecord (1,b, 0, TFName.getString().length());
        } catch (RecordStoreNotOpenException ex) {
            ex.printStackTrace();
        } catch (InvalidRecordIDException ex) {
            ex.printStackTrace();
        } catch (RecordStoreException ex) {
            ex.printStackTrace();
        } 
        
        String s = null; 
        try {
            s = new String(rs.getRecord (1));
        } catch (RecordStoreNotOpenException ex) {
            ex.printStackTrace();
        } catch (InvalidRecordIDException ex) {
            ex.printStackTrace();
        } catch (RecordStoreException ex) {
            ex.printStackTrace();
        }
        try {
            rs.closeRecordStore();
        } catch (RecordStoreNotOpenException ex) {
            ex.printStackTrace();
        } catch (RecordStoreException ex) {
            ex.printStackTrace();
        }
Добавлено через 6 минут
в следующий раз форматируй код пожалуйста
1
 Аватар для 4damir4
4 / 4 / 1
Регистрация: 14.10.2011
Сообщений: 36
16.10.2011, 15:56  [ТС]
работает спс. а следом идет подключение к http оно прописанно testGET(то что надо вставить в url);

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
String s,name;
...
public void testGET(String name) throws IOException {
HttpConnection connection = null;
String url = "http://tagilhost.ru/tagil_domen_mobile.php?pas=" + name;
InputStream is = null;
OutputStream os = null;
StringBuffer stringBuffer = new StringBuffer();
 
 
 
try {
connection = (HttpConnection)Connector.open(url);
connection.setRequestMethod(HttpConnection.GET);
connection.setRequestProperty("IF-Modified-Since","20 Jan 2001 16:19:14 GMT");
connection.setRequestProperty("User-Agent","Profile/MIDP-2.0 Confirguration/CLDC-1.0");
connection.setRequestProperty("Content-Language", "en-CA");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
os = connection.openOutputStream();
is = connection.openDataInputStream();
int ch;
while ((ch = is.read()) != -1) {
stringBuffer.append((char) ch);
}
 
} finally {
 
if(is!= null) {
is.close();
}
if(os != null) {
os.close();
}
if(connection != null) {
connection.close();
}
}
finishForm = new Form("имя формы");
finishForm.append(stringBuffer.toString());
finishForm.addCommand(CMD_EXIT);
finishForm.setCommandListener(this);
display.setCurrent(finishForm);
}
...
RecordStore rs = null;
try {
rs = RecordStore.openRecordStore("host", true);
} catch (RecordStoreException ex) {
ex.printStackTrace();
}    
byte [] b = TFName.getString().getBytes(); 
try {
rs.setRecord (1,b, 0, TFName.getString().length());
} catch (RecordStoreNotOpenException ex) {
ex.printStackTrace();
} catch (InvalidRecordIDException ex) {
ex.printStackTrace();
} catch (RecordStoreException ex) {
ex.printStackTrace();
} 
        
String s = null; 
try {
s = new String(rs.getRecord (1));
} catch (RecordStoreNotOpenException ex) {
ex.printStackTrace();
} catch (InvalidRecordIDException ex) {
ex.printStackTrace();
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
try {
rs.closeRecordStore();
} catch (RecordStoreNotOpenException ex) {
ex.printStackTrace();
} catch (RecordStoreException ex) {
ex.printStackTrace();
} 
String name = s;
try {
testGET(name);
} 
catch (IOException e) {
}
при соединении показывает в телефоне http://tagilhost.ru/tagil_dome... p?pas=null
0
 Аватар для mutagen
2587 / 2260 / 257
Регистрация: 14.09.2011
Сообщений: 5,185
Записей в блоге: 18
16.10.2011, 16:49
видимо это пароль ))) раз pas
0
 Аватар для 4damir4
4 / 4 / 1
Регистрация: 14.10.2011
Сообщений: 36
16.10.2011, 16:53  [ТС]
нет домен вот работущий aprodu.ru
0
 Аватар для mutagen
2587 / 2260 / 257
Регистрация: 14.09.2011
Сообщений: 5,185
Записей в блоге: 18
16.10.2011, 17:37
я подозреваю что в RecordStore надо сначала не Set а addRecord и тогда всё будет ок
вот тебе пример http://www.roseindia.net/j2me/... dlet.shtml
1
 Аватар для 4damir4
4 / 4 / 1
Регистрация: 14.10.2011
Сообщений: 36
16.10.2011, 19:50  [ТС]
да ты мне помог

Добавлено через 20 минут
странно программа поработала ровно два раза. а теперь кнопки не нажимаются для перехода в следующую форму

Добавлено через 18 минут
да же кнопка EXIT не работает. циклится где то что ли ?
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
 import java.io.*;
 import javax.microedition.io.*;
 import javax.microedition.lcdui.*;
 import javax.microedition.midlet.*;
 import javax.microedition.rms.*;
 
 
 public class MobileTest  extends MIDlet implements CommandListener, ItemCommandListener{
 
 private Display display;
 
 
 public MobileTest()     {}
 private Form LogoForm,firstForm,tooForm,finishForm;
 private Alert myalert = new Alert("","Сети нет!",null,null);
 private RecordStore recordStore; // хранилище
 private StringItem str;         //Сторка
 private TextField TFName;     //Имя и возраст
 String s,name;
 
 
 
 
 //Создаем комманды
 
 private Command CMD_GO = new Command("Go", Command.ITEM, 1);
 private Command CMD_FIRST = new Command("Начать", Command.EXIT, 2); 
 private Command CMD_START = new Command("OK", Command.EXIT, 2); 
 private Command CMD_NEXT = new Command("OK", Command.EXIT, 2); 
 private Command CMD_YES = new Command("Далее", Command.EXIT, 2);
 private Command CMD_NO = new Command("Назад", Command.SCREEN, 1);  
 private Command CMD_EXIT = new Command("Выход", Command.SCREEN, 1); 
 
 protected void destroyApp( boolean unconditional ) throws MIDletStateChangeException 
 {
 
 exitApp(); // вызывает уборщик мусора
 }
 
 protected void pauseApp()
 {
 }
 
 protected void startApp() throws MIDletStateChangeException
 {
 if( display == null )
 { 
 initApp(); 
 }  
 }
 
 private void initApp()  //Этот метод выполняется при запуске мидлета
 {
 display = Display.getDisplay( this );
 LogoForm=new Form(""); //Создаем первую форму
 LogoForm.setCommandListener(this);
 //Добавляем рисунок. Обратите внимание, рисунок загружается в скобках try{}catch{}
 try{
 Image img=Image.createImage("/Logo.png");
 ImageItem FormImg=new
 ImageItem("MobileTagilHost",img,ImageItem.LAYOUT_CENTER,"");
 LogoForm.append(FormImg);
 }catch(java.io.IOException ex){}
 //Создаем подпись
 str = new StringItem("", "www.tagilhost.ru", Item.HYPERLINK); 
 LogoForm.append(str);   
 //подключаем ссылку
 str.setDefaultCommand(CMD_GO);
 str.setItemCommandListener(this); 
 //Добавляем подэкранные кнопки
 LogoForm.addCommand(CMD_FIRST);
 LogoForm.addCommand(CMD_EXIT);
 //Объявляем обработчик команд
 display.setCurrent(LogoForm);
 
 }
 
 public void exitApp()
 {
 notifyDestroyed(); // уничтожение MIDlet-а
 }   
 
 
 
 public void commandAction(Command c, Item item) {
 if (c == CMD_GO) {
 
 try {
 platformRequest("http://tagilhost.ru/index.html");//запускает встроеный браузер 
 }
 catch (ConnectionNotFoundException ex) {
 }
 
 exitApp();//и выходит из приложения (для нокиа)
 }
 }
 
 public void myrmsMet()
 {
 
 try{
 recordStore = RecordStore.openRecordStore("host", true );
  
 String outputData = TFName.getString();
 byte[] byteOutputData = outputData.getBytes();
 recordStore.addRecord(byteOutputData, 0, 
 byteOutputData.length);
  
 byte[] byteInputData = new byte[1]; 
 int length = 0;
 for (int x = 1; x <= recordStore.getNumRecords(); x++){
 if (recordStore.getRecordSize(x) > byteInputData.length){
 byteInputData = new byte[recordStore.getRecordSize(x)];
 }
 length = recordStore.getRecord(x, byteInputData, 0);
 } 
 String name = new String(byteInputData, 0, length);
 try {
 
 testGET(name);
 } catch (IOException e) {
 
 }
  
 recordStore.closeRecordStore();
 }catch (Exception e){}
 
 
 }
 
 public void testGET(String name) throws IOException {
 HttpConnection connection = null;
 String url = "http://tagilhost.ru/tagil_domen_mobile.php?pas=" + name;
 InputStream is = null;
 OutputStream os = null;
 StringBuffer stringBuffer = new StringBuffer();
 
 
 
 try {
 connection = (HttpConnection)Connector.open(url);
 connection.setRequestMethod(HttpConnection.GET);
 connection.setRequestProperty("IF-Modified-Since","20 Jan 2001 16:19:14 GMT");
 connection.setRequestProperty("User-Agent","Profile/MIDP-2.0 Confirguration/CLDC-1.0");
 connection.setRequestProperty("Content-Language", "en-CA");
 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
 os = connection.openOutputStream();
 is = connection.openDataInputStream();
 int ch;
 while ((ch = is.read()) != -1) {
 stringBuffer.append((char) ch);
 }
 
 } finally {
 
 if(is!= null) {
 is.close();
 }
 if(os != null) {
 os.close();
 }
 if(connection != null) {
 connection.close();
 }
 }
 finishForm = new Form("Осталось дней");
 finishForm.append(stringBuffer.toString());
 finishForm.addCommand(CMD_EXIT);
 finishForm.setCommandListener(this);
 display.setCurrent(finishForm);
 }
 
 
 
 
 
 
 public void commandAction(Command c, Displayable d) {
 if (c == CMD_FIRST) {   //Команда: загрузить первый экран
         
 //Создаем форму
 Form firstForm=new Form("Добро пожаловать");
 //Размещаем на ней поля для ввода текста
 TFName=new TextField("Укажите домен","aprodu.ru",50,TextField.ANY);
 firstForm.append(TFName);
 //Добавляем команды
 firstForm.addCommand(CMD_START);
 firstForm.addCommand(CMD_EXIT);
 firstForm.setCommandListener(this);
 //Делаем окно формы видимым     
 display.setCurrent(firstForm);
 }
 
 if (c == CMD_START)  {//Команда перехода к следующему вопросу
 
 //Создаем форму
 Form tooForm=new Form("Важно!");
 //Размещаем на ней поля для ввода текста
 tooForm.append("Проверте ещё раз домен\nОн вводиться один\nединственный раз.\nЧто бы продолжить\nнажмите <Далее>");// вывод на экран
 tooForm.addCommand(CMD_YES);
 tooForm.addCommand(CMD_NO);
 tooForm.setCommandListener(this);
 //Делаем окно формы видимым   
 
 display.setCurrent(tooForm);
 
 
 
 
 }
 if (c == CMD_NO)  {//Команда перехода к следующему вопросу
 //Создаем форму
 Form firstForm=new Form("Добро пожаловать");
 //Размещаем на ней поля для ввода текста
 TFName=new TextField("Укажите домен",TFName.getString(),50,TextField.ANY);
 
 firstForm.append(TFName);
 //Добавляем команды
 firstForm.addCommand(CMD_START);
 firstForm.addCommand(CMD_EXIT);
 firstForm.setCommandListener(this);
 //Делаем окно формы видимым     
 display.setCurrent(firstForm);                
 
 
                            }
 
 if (c == CMD_YES)  {//Команда перехода к следующему вопросу
 
 display.setCurrent(myalert);
 myrmsMet();
 
 
 
 
 }     
 
 
 
 if (c == CMD_EXIT){exitApp();}  //Команда "Выход"
 
 
 
 }
 }
попробуй сам
0
 Аватар для mutagen
2587 / 2260 / 257
Регистрация: 14.09.2011
Сообщений: 5,185
Записей в блоге: 18
16.10.2011, 20:30
извини но у меня 64 бит jdk поэтому на нём эмулятор мобилки не работает, да и вообще мне кажется то что у тебя всё в одном классе архитектурно неправильно, нет никаких обработок исключений, всё очень беспорядочно и если программа работает а потом падает, то значит обязательно присутствует утечка памяти. Раскидай листенеры и формы в отдельные классы, сделай формы синглетонами и тд, вобщем приведи код в порядок иначе одно за одним будут вылазить грабли.
блок finally, для того чтобы закрыть коннекты если всё плохо, не пойму зачем там if.
все формы в обработчиках команд создаются new похоже это и есть утечка (10 нажатий 10 форм) в мобилке память очень ограничена вот она и выдержала всего пару комманд
1
 Аватар для 4damir4
4 / 4 / 1
Регистрация: 14.10.2011
Сообщений: 36
17.10.2011, 07:06  [ТС]
Цитата Сообщение от mutagen Посмотреть сообщение
Раскидай листенеры и формы в отдельные классы,
было
Java
1
2
3
4
5
 finishForm = new Form("Осталось дней");
 finishForm.append(stringBuffer.toString());
 finishForm.addCommand(CMD_EXIT);
 finishForm.setCommandListener(this);
 display.setCurrent(finishForm);
стало
Java
1
2
3
4
5
6
7
8
9
10
 public void myform {
 finishForm = new Form("Осталось дней");
 finishForm.append(stringBuffer.toString());
 mylistener();
 display.setCurrent(finishForm);
 }
 public void mylistener {
 finishForm.addCommand(CMD_EXIT);
 finishForm.setCommandListener(this);
 }
так?
0
 Аватар для mutagen
2587 / 2260 / 257
Регистрация: 14.09.2011
Сообщений: 5,185
Записей в блоге: 18
17.10.2011, 09:16
я имел в виду под синглетоном вот это:
Java
1
2
3
4
5
6
public Form myForm {
  if(finishForm!=null) { 
  finishForm = new Form("Осталось дней");
  }
 return finishForm;
}
1
 Аватар для 4damir4
4 / 4 / 1
Регистрация: 14.10.2011
Сообщений: 36
17.10.2011, 18:25  [ТС]
обернул все формы. пишет ошибку illegal start of expression(незаконное начало выражения)

public Form myForm1 {

^

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
...
 if (c == CMD_START)  {//Команда перехода к следующему вопросу
 
 //Создаем форму
 
 public Form myForm4 {
 if(tooForm!=null) {
 Form tooForm=new Form("Важно!");
 }
 return tooForm;
 }
 //Размещаем на ней поля для ввода текста
 tooForm.append("Проверте ещё раз домен\nОн вводиться один\nединственный раз.\nЧто бы продолжить\nнажмите <Далее>");// вывод на экран
 tooForm.addCommand(CMD_YES);
 tooForm.addCommand(CMD_NO);
 tooForm.setCommandListener(this);
 //Делаем окно формы видимым   
 
 display.setCurrent(tooForm);
 
 
 
 
 }
 if (c == CMD_NO)  {//Команда перехода к следующему вопросу
 //Создаем форму
 
 public Form myForm5 {
 if(firstForm!=null) {
 Form firstForm=new Form("Добро пожаловать");
 }
 return firstForm;
 }
 //Размещаем на ней поля для ввода текста
 TFName=new TextField("Укажите домен",TFName.getString(),50,TextField.ANY);
 
 firstForm.append(TFName);
 //Добавляем команды
 firstForm.addCommand(CMD_START);
 firstForm.addCommand(CMD_EXIT);
 firstForm.setCommandListener(this);
 //Делаем окно формы видимым     
 display.setCurrent(firstForm);   
...
0
 Аватар для mutagen
2587 / 2260 / 257
Регистрация: 14.09.2011
Сообщений: 5,185
Записей в блоге: 18
17.10.2011, 19:06
Загляни в пример try{} catch(){}
1
 Аватар для 4damir4
4 / 4 / 1
Регистрация: 14.10.2011
Сообщений: 36
17.10.2011, 21:14  [ТС]
Ура !!! Готово! Прибирался! Делал как писал! Вот код, jar, jad (домен для проверки вводи: aprodu.ru):
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
 
 import java.io.*;
 import javax.microedition.io.*;
 import javax.microedition.lcdui.*;
 import javax.microedition.midlet.*;
 import javax.microedition.rms.*;
 
 
 public class MobileTest  extends MIDlet implements CommandListener, ItemCommandListener{
 
 private Display display;
 private Form LogoForm,firstForm,finishForm;
 private Alert myalert = new Alert("","Сети нет!",null,null);
 private RecordStore recordStore; // хранилище
 private StringItem str;         //Сторка
 private TextField TFName;     //Имя и возраст
 String s,name;
 
 
 public MobileTest()     {
 
 display = Display.getDisplay( this );
 LogoForm=new Form(""); //Создаем первую форму
 //Добавляем рисунок. Обратите внимание, рисунок загружается в скобках try{}catch{}
 try{
 Image img=Image.createImage("/Logo.png");
 ImageItem FormImg=new
 ImageItem("MobileTagilHost",img,ImageItem.LAYOUT_CENTER,"");
 LogoForm.append(FormImg);
 }catch(java.io.IOException ex){}
 //Создаем подпись
 str = new StringItem("", "www.tagilhost.ru", Item.HYPERLINK); 
 LogoForm.append(str);   
 //подключаем ссылку
 str.setDefaultCommand(CMD_GO);
 str.setItemCommandListener(this); 
 //Добавляем подэкранные кнопки
 LogoForm.addCommand(CMD_FIRST);
 LogoForm.addCommand(CMD_EXIT);
 LogoForm.setCommandListener(this);
 //Объявляем обработчик команд
 
 }
 
 
 
 //Создаем комманды
 private Command CMD_GO = new Command("Go", Command.ITEM, 1);
 private Command CMD_FIRST = new Command("Начать", Command.EXIT, 2); 
 private Command CMD_START = new Command("OK", Command.EXIT, 2); 
 private Command CMD_EXIT = new Command("Выход", Command.SCREEN, 1); 
 
 protected void destroyApp( boolean unconditional ) throws MIDletStateChangeException 
 {
 
 exitApp(); // вызывает уборщик мусора
 
 }
 
 protected void pauseApp()
 {
 
 }
 
 protected void startApp() throws MIDletStateChangeException
 {
 
 initApp(); 
 
 }
 
 private void initApp()  //Этот метод выполняется при запуске мидлета
 {
 
 display.setCurrent(LogoForm);
 
 }
 
 public void exitApp()
 {
 
 notifyDestroyed(); // уничтожение MIDlet-а
 
 }   
 
 
 
 public void commandAction(Command c, Item item) {
 if (c == CMD_GO) {
 
 try {
 platformRequest("http://tagilhost.ru/index.html");//запускает встроеный браузер 
 }
 catch (ConnectionNotFoundException ex) {
 
 }
 
 exitApp();//и выходит из приложения (для нокиа)
 
 }
 }
 
 public void myrmsMet()
 {
 
 try{
 recordStore = RecordStore.openRecordStore("host", true );
  
 String outputData = TFName.getString();
 byte[] byteOutputData = outputData.getBytes();
 recordStore.addRecord(byteOutputData, 0, 
 byteOutputData.length);
  
 byte[] byteInputData = new byte[1]; 
 int length = 0;
 for (int x = 1; x <= recordStore.getNumRecords(); x++){
 if (recordStore.getRecordSize(x) > byteInputData.length){
 byteInputData = new byte[recordStore.getRecordSize(x)];
 }
 length = recordStore.getRecord(x, byteInputData, 0);
 } 
 String name = new String(byteInputData, 0, length);
 try {
 
 testGET(name);
 } catch (IOException e) {
 
 }
  
 recordStore.closeRecordStore();
 }catch (Exception e){}
 
 
 }
 
  public void myrms2Met()
 {
 
 try{
 recordStore = RecordStore.openRecordStore("host", true );
  
 byte[] byteInputData = new byte[1]; 
 int length = 0;
 for (int x = 1; x <= recordStore.getNumRecords(); x++){
 if (recordStore.getRecordSize(x) > byteInputData.length){
 byteInputData = new byte[recordStore.getRecordSize(x)];
 }
 length = recordStore.getRecord(x, byteInputData, 0);
 } 
 String name = new String(byteInputData, 0, length);
 if(RecordStore.listRecordStores() != null)
 {
  Form firstForm = new Form("Добро пожаловать");
 //Размещаем на ней поля для ввода текста
 TFName = new TextField("Укажите домен",name,50,TextField.ANY);
 firstForm.append(TFName);
 //Добавляем команды
 firstForm.addCommand(CMD_START);
 firstForm.addCommand(CMD_EXIT);
 firstForm.setCommandListener(this);
 display.setCurrent(firstForm);
 }
  else
 {
  Form firstForm = new Form("Добро пожаловать");
 //Размещаем на ней поля для ввода текста
 TFName = new TextField("Укажите домен","",50,TextField.ANY);
 firstForm.append(TFName);
 //Добавляем команды
 firstForm.addCommand(CMD_START);
 firstForm.addCommand(CMD_EXIT);
 firstForm.setCommandListener(this);
 display.setCurrent(firstForm);
 } 
 recordStore.closeRecordStore();
 }catch (Exception e){}
 
 
 }
 
 public void testGET(String name) throws IOException {
 HttpConnection connection = null;
 String url = "http://tagilhost.ru/tagil_domen_mobile.php?pas=" + name;
 InputStream is = null;
 OutputStream os = null;
 StringBuffer stringBuffer = new StringBuffer();
 
 
 
 try {
 connection = (HttpConnection)Connector.open(url);
 connection.setRequestMethod(HttpConnection.GET);
 connection.setRequestProperty("IF-Modified-Since","20 Jan 2001 16:19:14 GMT");
 connection.setRequestProperty("User-Agent","Profile/MIDP-2.0 Confirguration/CLDC-1.0");
 connection.setRequestProperty("Content-Language", "en-CA");
 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
 os = connection.openOutputStream();
 is = connection.openDataInputStream();
 int ch;
 while ((ch = is.read()) != -1) {
 stringBuffer.append((char) ch);
 }
 
 } finally {
 
 if(is!= null) {
 is.close();
 }
 if(os != null) {
 os.close();
 }
 if(connection != null) {
 connection.close();
 }
 }
 Form finishForm = new Form("Осталось дней");
 finishForm.addCommand(CMD_EXIT);
 finishForm.setCommandListener(this);
 finishForm.append(stringBuffer.toString());
 display.setCurrent(finishForm);
 }
 
 
 public void commandAction(Command c, Displayable d) {
 if (c == CMD_FIRST) {   //Команда: загрузить первый экран
 myrms2Met();
 
 }
 
 if (c == CMD_START)  {//Команда перехода к следующему вопросу
 
 display.setCurrent(myalert);
 
 myrmsMet();
 
 }     
 
 if (c == CMD_EXIT) {
 
 exitApp();  //Команда "Выход"
 
 }  
 
 
 
 }
 }
Спасибо что откликнулся! Добавляй! Мне 27 лет. Дамир. ася: 596049176, skype: damirjon4
Вложения
Тип файла: zip MobileTagilHost.zip (7.0 Кб, 9 просмотров)
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
17.10.2011, 21:14
Помогаю со студенческими работами здесь

Конструкция try catch в цикле while. Зацикливается блок catch
Здравствуйте. Столкнулся с проблемой: при попытке запихнуть в цикл конструкцию try catch - зацикливается часть, расположенная в блоке...

try . catch
можно ли провести данную операцию для функции erase у вектора??? пытался, что-то не получилось: #include &lt;vector&gt; #include...

Try-catch
Добрый вечер, #include &lt;iostream&gt; using namespace std; void F1(int); void F2(int, int); void F3(int, int, int);

Try и catch
Пытался сделать простую структуру,чтобы в блоке try задавалось значение переменной x, и если это значение равно,например, 5,то блок catch...

TRY/CATCH
Здравствуйте! У меня есть: MASS; для простоты пояснения, x=rand();y=rand(),znacheniye=rand(); Как игнорировать ошибки...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
19
Ответ Создать тему
Опции темы

Новые блоги и статьи
Модель микоризы: классовый агентный подход 3
anaschu 06.01.2026
aa0a7f55b50dd51c5ec569d2d10c54f6/ O1rJuneU_ls https:/ / vkvideo. ru/ video-115721503_456239114
Owen Logic: О недопустимости использования связки «аналоговый ПИД» + RegKZR
ФедосеевПавел 06.01.2026
Owen Logic: О недопустимости использования связки «аналоговый ПИД» + RegKZR ВВЕДЕНИЕ Введу сокращения: аналоговый ПИД — ПИД регулятор с управляющим выходом в виде числа в диапазоне от 0% до. . .
Модель микоризы: классовый агентный подход 2
anaschu 06.01.2026
репозиторий https:/ / github. com/ shumilovas/ fungi ветка по-частям. коммит Create переделка под биомассу. txt вход sc, но sm считается внутри мицелия. кстати, обьем тоже должен там считаться. . . .
Расчёт токов в цепи постоянного тока
igorrr37 05.01.2026
/ * Дана цепь постоянного тока с сопротивлениями и напряжениями. Надо найти токи в ветвях. Программа составляет систему уравнений по 1 и 2 законам Кирхгофа и решает её. Последовательность действий:. . .
Новый CodeBlocs. Версия 25.03
palva 04.01.2026
Оказывается, недавно вышла новая версия CodeBlocks за номером 25. 03. Когда-то давно я возился с только что вышедшей тогда версией 20. 03. С тех пор я давно снёс всё с компьютера и забыл. Теперь. . .
Модель микоризы: классовый агентный подход
anaschu 02.01.2026
Раньше это было два гриба и бактерия. Теперь три гриба, растение. И на уровне агентов добавится между грибами или бактериями взаимодействий. До того я пробовал подход через многомерные массивы,. . .
Советы по крайней бережливости. Внимание, это ОЧЕНЬ длинный пост.
Programma_Boinc 28.12.2025
Советы по крайней бережливости. Внимание, это ОЧЕНЬ длинный пост. Налог на собак: https:/ / **********/ gallery/ V06K53e Финансовый отчет в Excel: https:/ / **********/ gallery/ bKBkQFf Пост отсюда. . .
Кто-нибудь знает, где можно бесплатно получить настольный компьютер или ноутбук? США.
Programma_Boinc 26.12.2025
Нашел на реддите интересную статью под названием Anyone know where to get a free Desktop or Laptop? Ниже её машинный перевод. После долгих разбирательств я наконец-то вернула себе. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru