将数据从servlet保存到j2me中的记录库

时间:2011-12-10 13:40:28

标签: java-me

我正在开发一个使用servlet与数据库通信的j2me应用程序。 我想将从servlet接收的数据存储到记录存储中并显示它。这可以实现吗?请提供代码示例。 提前谢谢

 public void viewcon()
 {
  StringBuffer sb = new StringBuffer();

  try {
  HttpConnection c = (HttpConnection) Connector.open(url);
  c.setRequestProperty("User-Agent","Profile/MIDP-1.0, Configuration/CLDC-1.0");
  c.setRequestProperty("Content-Language","en-US");
  c.setRequestMethod(HttpConnection.POST);
  DataOutputStream os = (DataOutputStream)c.openDataOutputStream();

  os.flush();
  os.close();

  // Get the response from the servlet page.
  DataInputStream is =(DataInputStream)c.openDataInputStream();
  //is = c.openInputStream();
   int ch;
   sb = new StringBuffer();
   while ((ch = is.read()) != -1) {
   sb.append((char)ch);
       }
  // return sb;
   showAlert(sb.toString());//display data received from servlet 

    is.close();
    c.close();

              } catch (Exception e) {
                  showAlert(e.getMessage());
              }
        }

2 个答案:

答案 0 :(得分:0)

将此函数调用放在显示响应数据警报的位置

writeToRecordStore(sb.toString().getBytes());

功能定义如下:

private static String RMS_NAME = "NETWORK-DATA-STORAGE";
private boolean writeToRecordStore(byte[] inStream) {
    RecordStore rs = null;
    try {
        rs = RecordStore.openRecordStore(RMS_NAME, true);
        if (null != rs) {
            //Based on your logic either ADD or SET the record
            rs.addRecord(inStream, 0, inStream.length);
            return true;
        } else {
            return false;
        }
    } catch (RecordStoreException ex) {
        ex.printStackTrace();
        return false;
    } finally {
        try {
            if (null != rs) {
                rs.closeRecordStore();
            }
        } catch (RecordStoreException recordStoreException) {
        } finally {
            rs = null;
        }
    }
}

保存数据后,请阅读记录存储RMS-NAME并检查添加的索引以获取响应数据。

注意:假设网络响应数据将附加到记录存储。如果要将其设置为特定记录,请相应地修改方法writeToRecordStore(...)

答案 1 :(得分:0)

   //this code throws exception in display class. 
    try
    {
     byte[] byteInputData = new byte[5];
    int length = 0;
// access all records present in record store
    for (int x = 1; x <= rs.getNumRecords(); x++)
    {
      if (rs.getRecordSize(x) > byteInputData.length)
      {
        byteInputData = new byte[rs.getRecordSize(x)];
      }
      length = rs.getRecord(x, byteInputData, 0);
    }

     alert =new Alert("reading",new String(byteInputData,0,length),null,AlertType.WARNING);
     alert.setTimeout(Alert.FOREVER);
     display.setCurrent(alert);
 }