Вниз  Исправления исходников (1-ый пост)
- 4.12.2018 / 20:38
Vlad_jonson
  Пользователь

Vlad_jonson 
Сейчас: Offline
Aladdin, Спасибо ;-)
- 9.12.2018 / 19:22
Vlad_jonson
  Пользователь

Vlad_jonson 
Сейчас: Offline
Вы уж извените,или я тупею или на самом деле из рмс нельзя достать double,я конечно понимаю мол разный размер байтов между типами ну все же знаю что стоит указать компилятору мол все ок я рулю,но в моем случае оказалось все иначе компиль болие чем уверен что я не прав.Кто поможет получить double из byte[] :-D
- 10.12.2018 / 10:49
Askalite
  Пользователь

Askalite 
Сейчас: Offline
Vlad_jonson,
  1.  byte[] bdouble = new byte[8];
  2.  
  3. // чтение в bdouble ...
  4.  
  5. long longBits = ((long)bdouble[0] << 56) +
  6.             ((long)(bdouble[1] & 255) << 48) +
  7.             ((long)(bdouble[2] & 255) << 40) +
  8.             ((long)(bdouble[3] & 255) << 32) +
  9.             ((long)(bdouble[4] & 255) << 24) +
  10.             ((bdouble[5] & 255) << 16) +
  11.             ((bdouble[6] & 255) <<  8) +
  12.             ((bdouble[7] & 255) <<  0);
  13.  
  14. double d = Double.longBitsToDouble(longBits);

- 10.12.2018 / 12:42
aNNiMON
  Супервизор

aNNiMON 
Сейчас: Offline
Vlad_jonson, пожалуйста, взгляни на календарь, там 2018, а не 2008. Какой RMS? Давай уже Java SE осваивать, а с него в Android.
Оберни свой byte[] в ByteArrayInputStream, а его в DataInputStream и читай readDouble();

Askalite, побитовое сложение лучше уж использовать, а не арифметическое. Но вообще, это немного индусский код.
__________________
 let live

Изменено aNNiMON (10.12 / 12:43) (всего 1 раз)
- 21.11.2023 / 21:30
N0004
  Пользователь

N0004 
Сейчас: Offline
Мне дали на этом сайте код. Я его немножко подрулил, но если запустить второй раз с комментированной строчкой //addData(), выясняется что записи не сохраняются в рекорд сторе, даже при выходе из мидлета. Банально нужен код по рекордстору, который бы сохранял записи при закрытии Мидлета, но этого не происходит. :hack:
  1. package j;
  2.  
  3.  
  4. import javax.microedition.midlet.MIDlet;
  5. import javax.microedition.rms.*;
  6.  
  7. class DataStorage {
  8.  
  9.     public static RecordStore recordStore;
  10.     public static String[] data=null;
  11.     public DataStorage(String storeName) {
  12.         openRecordStore(storeName);
  13.         //открываем рекордскор
  14.     }
  15.  
  16.     private void openRecordStore(String storeName) {
  17.         try {//открываем рекордскор
  18.             recordStore = RecordStore.openRecordStore(storeName, true);
  19.         } catch (RecordStoreException e) {
  20.             e.printStackTrace();
  21.         }
  22.     }
  23.  
  24.   static public void closeRecordStore_0() {
  25.         try {//здесь закрываем рекорд стор
  26.             if (recordStore != null) {
  27.                 recordStore.closeRecordStore();
  28.            System.out.println("closing record store");
  29.             }
  30.         } catch (RecordStoreException e) {
  31.             e.printStackTrace();
  32.         }
  33.     }
  34.  
  35.     public static void addData (String data) {
  36.         try {//Здесь добавляем записи к рекрд стору,
  37.             byte[] byteData = data.getBytes();
  38.             recordStore.addRecord(byteData, 0, byteData.length);
  39.         } catch (RecordStoreException e) {
  40.             e.printStackTrace();
  41.         }
  42.     }
  43.  
  44.     public static void Read_All_Records() {
  45.         try {
  46.             //здесь считываем рекордстор
  47.             RecordEnumeration enumeration = recordStore.enumerateRecords(null, null, false);
  48.             int numRecords = enumeration.numRecords();
  49.             data = new String[numRecords];
  50.             int index = 0;
  51.             while (enumeration.hasNextElement()) {
  52.                 int recordId = enumeration.nextRecordId();
  53.                 byte[] record = recordStore.getRecord(recordId);
  54.                 data[index++] = new String(record);
  55.                 System.out.println("System reading recordsotores:" + new String(record));
  56.             }
  57.             enumeration.destroy();
  58.             //return data;
  59.         } catch (RecordStoreException e) {
  60.             e.printStackTrace();
  61.         }
  62.        // return null;
  63.     }
  64.  
  65.     public static void deleteAllData() {
  66.         try {
  67.             //здесь удаляем весь рекорд стор
  68.             RecordEnumeration enumeration = recordStore.enumerateRecords(null, null, false);
  69.             while (enumeration.hasNextElement()) {
  70.                 int recordId = enumeration.nextRecordId();
  71.                 recordStore.deleteRecord(recordId);
  72.             }
  73.             enumeration.destroy();
  74.         } catch (RecordStoreException e) {
  75.             e.printStackTrace();
  76.         }
  77.     }
  78. }
  79.  
  80.  
  81. public class MainApp extends MIDlet {
  82.  
  83.  
  84.     public void startApp() {
  85.         //открываем рекордстор
  86.         DataStorage dataStorage = new DataStorage("MyRecordStore");
  87.         //
  88.       //j.DataStorage.deleteAllData() ;
  89.  
  90.          j.DataStorage.addData("/////////My Recorscore Number 1");//Если закомментировать эту строчку, то ничего не работает
  91.  
  92.         try {
  93.                j.DataStorage.Read_All_Records();
  94.                 int N0 = dataStorage.recordStore.getNumRecords();
  95.                if(N0>0){
  96.                 System.out.println("/////////Amount of recordstere is^"+ N0);                
  97.                }
  98.         } catch (Exception ex) {
  99.             ex.printStackTrace();
  100.         }
  101.         try {
  102.             // Удаление всех данных из RecordStore
  103.             //dataStorage.deleteAllData();
  104.  
  105.  
  106.            // notifyDestroyed();
  107.         } catch (Exception ex) {
  108.             ex.printStackTrace();
  109.         }
  110.     }
  111.  
  112.     public void pauseApp() {
  113.         //добавляем строчку к рекрд стор. и закрываемся.
  114.         j.DataStorage.addData("////////My Recorscore Number 2");
  115.         j.DataStorage.closeRecordStore_0();
  116.  
  117.     }
  118.  
  119.     public void destroyApp(boolean unconditional) {
  120.         //добавляем строчку к рекрд стор. и закрываеся.
  121.         j.DataStorage.addData("/////////My Recorscore Number 3");
  122.         j.DataStorage.closeRecordStore_0();
  123.  
  124.     //notifyDestroyed();
  125.     }
  126. }

- 22.11.2023 / 00:13
aNNiMON
  Супервизор

aNNiMON 
Сейчас: Offline
N0004,
  1. public class Rms {
  2.     private static RecordStore rmsStore;
  3.     public static int startsCount = 0;
  4.     public static String text = "empty";
  5.  
  6.     public static void saveOptions() {
  7.         if (rmsStore == null) return;
  8.         try {
  9.             ByteArrayOutputStream baos = new ByteArrayOutputStream();
  10.             DataOutputStream dos = new DataOutputStream(baos);
  11.             dos.writeInt(startsCount);
  12.             dos.writeUTF(text);
  13.             dos.flush();
  14.             byte[] options = baos.toByteArray();
  15.             dos.close();
  16.             try {
  17.                 rmsStore.setRecord(1, options, 0, options.length);
  18.             } catch (InvalidRecordIDException ridex) {
  19.                 rmsStore.addRecord(options, 0, options.length);
  20.             }
  21.         } catch (Exception ex) {
  22.         } finally {
  23.             try {
  24.                 rmsStore.closeRecordStore();
  25.                 rmsStore = null;
  26.             } catch (RecordStoreException ex) {}
  27.         }
  28.     }
  29.  
  30.     public static void restoreOptions() {
  31.         try {
  32.             rmsStore = RecordStore.openRecordStore("AppName", true);
  33.         } catch (RecordStoreException ex) {
  34.             rmsStore = null;
  35.         }
  36.         if (rmsStore != null) {
  37.             try {
  38.                 DataInputStream dis = new DataInputStream(new ByteArrayInputStream(rmsStore.getRecord(1)));
  39.                 startsCount = dis.readInt();
  40.                 text = dis.readUTF();
  41.                 dis.close();
  42.             } catch (Exception ex) {}
  43.         }
  44.     }
  45. }
  46.  
  47. // startApp()
  48. Rms.restoreOptions();
  49. System.out.println("Saved text: "+ Rms.text);  
  50.  
  51. // destroyApp
  52. Rms.startsCount++;
  53. Rms.text = "Some text";
  54. Rms.saveOptions();
Может так проще будет? Просто после 12 и 40 строки добавлять соответствующие записи и чтения нужных данных.
__________________
 let live

Изменено aNNiMON (22.11 / 00:15) (всего 2 раза)
- 22.11.2023 / 02:28
N0004
  Пользователь

N0004 
Сейчас: Offline
aNNiMON, можете, пожалуйста, очень прошу мне нужен такой код:

  1. При первом запуске мидлета:
  2. Создал.
  3. Открыл.
  4. Добавил 10 записей с текстом "@@@@@".
  5. Закрыл.


  1. При втором запуске и далее всегда.
  2. Открыл.
  3. Считал. (Вывел на экран все 10 записей (этих же которые сохранил).)
  4. 2-ю запись сделал "@@@222".
  5. Закрыл.

Это очень просто, но...
У меня большие успехи: ничего не получается. Кто нить поможет? :lol:
Очень прошу дайте совершенный код. :hack:

Изменено N0004 (22.11 / 02:33) (всего 3 раза)
- 22.11.2023 / 18:04
aNNiMON
  Супервизор

aNNiMON 
Сейчас: Offline
N0004,
  1. public class Rms {
  2.     private static RecordStore rmsStore;
  3.     public static boolean firstStart = true;
  4.     public static Vector messages = new Vector();
  5.  
  6.     public static void saveOptions() {
  7.         if (rmsStore == null) return;
  8.         try {
  9.             ByteArrayOutputStream baos = new ByteArrayOutputStream();
  10.             DataOutputStream dos = new DataOutputStream(baos);
  11.             dos.writeBoolean(firstStart);
  12.             int messagesCount = messages.size();
  13.             dos.writeInt(messagesCount);
  14.             for (int i = 0; i < messagesCount; i++) {
  15.                 dos.writeUTF((String) messages.elementAt(i));
  16.             }
  17.             dos.flush();
  18.             byte[] options = baos.toByteArray();
  19.             dos.close();
  20.             try {
  21.                 rmsStore.setRecord(1, options, 0, options.length);
  22.             } catch (InvalidRecordIDException ridex) {
  23.                 rmsStore.addRecord(options, 0, options.length);
  24.             }
  25.         } catch (Exception ex) {
  26.         } finally {
  27.             try {
  28.                 rmsStore.closeRecordStore();
  29.                 rmsStore = null;
  30.             } catch (RecordStoreException ex) {}
  31.         }
  32.     }
  33.  
  34.     public static void restoreOptions() {
  35.         try {
  36.             rmsStore = RecordStore.openRecordStore("AppName", true);
  37.         } catch (RecordStoreException ex) {
  38.             rmsStore = null;
  39.         }
  40.         if (rmsStore != null) {
  41.             try {
  42.                 DataInputStream dis = new DataInputStream(new ByteArrayInputStream(rmsStore.getRecord(1)));
  43.                 firstStart = dis.readBoolean();
  44.                 int messagesCount = dis.readInt();
  45.                 for (int i = 0; i < messagesCount; i++) {
  46.                     messages.add(dis.readUTF());
  47.                 }
  48.                 text = dis.readUTF();
  49.                 dis.close();
  50.             } catch (Exception ex) {}
  51.         }
  52.     }
  53. }
  54.  
  55. // startApp()
  56. Rms.restoreOptions();
  57. if (Rms.firstStart) {
  58.     Rms.messages.add("@@@@@1");
  59.     Rms.messages.add("@@@@@2");
  60.     // ...
  61.     Rms.messages.add("@@@@@10");
  62.     Rms.firstStart = false;
  63. } else {
  64.   for (int i = 0; i < Rms.messages.size(); i++) {
  65.       System.out.println(Rms.messages.elementAt(i));  
  66.   }
  67.   Rms.messages.add("@@@222");
  68. }
  69.  
  70. // destroyApp
  71. Rms.saveOptions();

__________________
 let live
- 23.11.2023 / 00:02
N0004
  Пользователь

N0004 
Сейчас: Offline
aNNiMON, сделал, как ты сказали, плюс добавил String text, и методы destroyApp() startApp(), и туда завернул как показано у Вас.
Но все равно не пашет, красным горит везде, где написано add(). Прикрепил скриншот.
Или у Вас нету Эмулятора, чтобы проверить? Можете дать полный совершенный код Мидлета j2me? Вот Ваш код в моей интерпретации, он не работает. :stena:
  1. /*
  2.  * To change this license header, choose License Headers in Project Properties.
  3.  * To change this template file, choose Tools | Templates
  4.  * and open the template in the editor.
  5.  */
  6.  
  7. package j;
  8.  
  9. import java.io.ByteArrayInputStream;
  10. import java.io.ByteArrayOutputStream;
  11. import java.io.DataInputStream;
  12. import java.io.DataOutputStream;
  13. import java.util.Vector;
  14.  
  15. import javax.microedition.midlet.MIDlet;
  16. import javax.microedition.rms.InvalidRecordIDException;
  17. import javax.microedition.rms.RecordStore;
  18. import javax.microedition.rms.RecordStoreException;
  19.  
  20.  
  21.  
  22.  
  23. public class Rms extends MIDlet{
  24.     private static RecordStore rmsStore;
  25.     public static boolean firstStart = true;
  26.     public static Vector messages = new Vector();
  27.     public static String text="";
  28.     public static void saveOptions() {
  29.         if (rmsStore == null) return;
  30.         try {
  31.             ByteArrayOutputStream baos = new ByteArrayOutputStream();
  32.             DataOutputStream dos = new DataOutputStream(baos);
  33.             dos.writeBoolean(firstStart);
  34.             int messagesCount = messages.size();
  35.             dos.writeInt(messagesCount);
  36.             for (int i = 0; i < messagesCount; i++) {
  37.                 dos.writeUTF((String) messages.elementAt(i));
  38.             }
  39.             dos.flush();
  40.             byte[] options = baos.toByteArray();
  41.             dos.close();
  42.             try {
  43.                 rmsStore.setRecord(1, options, 0, options.length);
  44.             } catch (InvalidRecordIDException ridex) {
  45.                 rmsStore.addRecord(options, 0, options.length);
  46.             }
  47.         } catch (Exception ex) {
  48.         } finally {
  49.             try {
  50.                 rmsStore.closeRecordStore();
  51.                 rmsStore = null;
  52.             } catch (RecordStoreException ex) {}
  53.         }
  54.     }
  55.  
  56.     public static void restoreOptions() {
  57.         try {
  58.             rmsStore = RecordStore.openRecordStore("AppName", true);
  59.         } catch (RecordStoreException ex) {
  60.             rmsStore = null;
  61.         }
  62.         if (rmsStore != null) {
  63.             try {
  64.                 DataInputStream dis = new DataInputStream(new ByteArrayInputStream(rmsStore.getRecord(1)));
  65.                 firstStart = dis.readBoolean();
  66.                 int messagesCount = dis.readInt();
  67.                 for (int i = 0; i < messagesCount; i++) {
  68.                     messages.add(dis.readUTF());
  69.                 }
  70.                 text = dis.readUTF();
  71.                 dis.close();
  72.             } catch (Exception ex) {}
  73.         }
  74.     }
  75.  
  76.  
  77.  
  78.  
  79.  
  80.     public void startApp() {
  81.   // startApp()
  82.    Rms.restoreOptions();
  83.    if (Rms.firstStart) {
  84.     Rms.messages.add("@@@@@1");
  85.     Rms.messages.add("@@@@@2");
  86.     Rms.messages.add("@@@@@10");
  87.  
  88.     Rms.firstStart = false;
  89. }
  90.   else {
  91.   for (int i = 0; i < Rms.messages.size(); i++) {
  92.       System.out.println(Rms.messages.elementAt(i));  
  93.   }
  94.   Rms.messages.add("@@@222");
  95. }
  96.     }
  97.  
  98.     public void pauseApp() {
  99.     }
  100.  
  101.     public void destroyApp(boolean unconditional) {
  102.   Rms.saveOptions();
  103.     }
  104. }


Изменено N0004 (23.11 / 00:14) (всего 3 раза)


Прикрепленные файлы:
2023-11-23_02-5(…).png (122.79 кб.) Скачано 28 раз
- 23.11.2023 / 01:33
N0004
  Пользователь

N0004 
Сейчас: Offline
Задача поставлена всё та же: нужен полный код, по RecosdStore:
https://annimon.com/forum/post521504
Кто может справиться?
Ребят, плиз, помогите.:stena:

Изменено N0004 (23.11 / 01:47) (всего 9 раз)
Наверх  Всего сообщений: 1662
Фильтровать сообщения
Поиск по теме
Файлы топика (325)