update record in recordstore j2me - java-me

i want to know the method used to update record in recordstore in j2me. thanks....

Simply use RecordStore.setRecord()

try this
Preferences preferences = new Preferences("ChatAppPref");
preferences.put("login", "y");
preferences.save();
String pIsLogin = preferences.get("login");
Preferences class here
package com.util;
import java.util.*;
import javax.microedition.rms.*;
public class Preferences {
private String mRecordStoreName;
private Hashtable mHashtable;
public Preferences(String recordStoreName)
throws RecordStoreException {
mRecordStoreName = recordStoreName;
mHashtable = new Hashtable();
load();
}
public String get(String key) {
return (String)mHashtable.get(key);
}
public void put(String key, String value) {
if (value == null) value = "";
mHashtable.put(key, value);
}
private void load() throws RecordStoreException {
RecordStore rs = null;
RecordEnumeration re = null;
try {
rs = RecordStore.openRecordStore(mRecordStoreName, true);
re = rs.enumerateRecords(null, null, false);
while (re.hasNextElement()) {
byte[] raw = re.nextRecord();
String pref = new String(raw);
// Parse out the name.
int index = pref.indexOf('|');
String name = pref.substring(0, index);
String value = pref.substring(index + 1);
put(name, value);
}
}
finally {
if (re != null) re.destroy();
if (rs != null) rs.closeRecordStore();
}
}
public void save() throws RecordStoreException {
RecordStore rs = null;
RecordEnumeration re = null;
try {
rs = RecordStore.openRecordStore(mRecordStoreName, true);
re = rs.enumerateRecords(null, null, false);
// First remove all records, a little clumsy.
while (re.hasNextElement()) {
int id = re.nextRecordId();
rs.deleteRecord(id);
}
// Now save the preferences records.
Enumeration keys = mHashtable.keys();
while (keys.hasMoreElements()) {
String key = (String)keys.nextElement();
String value = get(key);
String pref = key + "|" + value;
byte[] raw = pref.getBytes();
rs.addRecord(raw, 0, raw.length);
}
}
finally {
if (re != null) re.destroy();
if (rs != null) rs.closeRecordStore();
}
}
}

Related

Hazelcast Predicate SQL into map

I'm trying to build a method that deletes entries with attributes that are not null, but I keep failing in predicates and I don't know how to implement properly the predicate because hazelcast doesn't take "NOT NULL" or "IS NULL" as a where clause Any idea how can I find into the map the values I need to search to delete them?
the method
public int removeEntry(String CacheName, String claveReq, int id_interno_pe, String cod_nrbe_en, int num_sec_ac) {
int counter = 0;
IMap<String, ResponseSerializablePlus> map = clientInstance.getMap(CacheName);
// Predicate claveReqQuery = Predicates.equal("claveReq", claveReq);
// Predicate idInternoQuery = Predicates.equal("id_interno_pe", id_interno_pe);
// Predicate codNrbeQuery = Predicates.equal("cod_nrbe_en", cod_nrbe_en);
// Predicate numSecQuery = Predicates.equal("num_sec_ac", num_sec_ac);
// Predicate query = Predicates.and(idInternoQuery,codNrbeQuery,numSecQuery);
Predicate query = Predicates.sql("id_interno_pe IS NOT NULL");
if (!map.isEmpty()) {
for (ResponseSerializablePlus entry : map.values(query)) {
System.out.println("Entry "+entry.toString()+" Found");
map.delete(entry);
counter++;
}
System.out.println("Map Size ->"+map.size());
System.out.println("Deleted entries -> "+counter);
return counter;
}else {
System.out.println("No matches");
return 0;
}
}
the main class ResponseSerializablePlus
public class ResponseSerializablePlus implements IdentifiedDataSerializable{
private int id_interno_pe;
private String cod_nrbe_en;
private int num_sec_ac;
private int statusCode;
private HashMap<String,List<String>> headers;
private byte[] content;
public ResponseSerializablePlus(int id_interno_pe, String cod_nrbe_en, int num_sec_ac, int statusCode,
HashMap<String, List<String>> headers, byte[] content) {
this.id_interno_pe = id_interno_pe;
this.cod_nrbe_en = cod_nrbe_en;
this.num_sec_ac = num_sec_ac;
this.statusCode = statusCode;
this.headers = headers;
this.content = content;
}
public ResponseSerializablePlus() {
}
public void writeData(ObjectDataOutput out) throws IOException {
out.writeInt(id_interno_pe);
out.writeString(cod_nrbe_en);
out.writeInt(num_sec_ac);
out.writeInt(statusCode);
out.writeObject(headers);
out.writeByteArray(content);
}
public void readData(ObjectDataInput in) throws IOException {
this.id_interno_pe = in.readInt();
this.cod_nrbe_en = in.readString();
this.num_sec_ac = in.readInt();
this.statusCode = in.readInt();
this.headers = in.readObject();
this.content = in.readByteArray();
}
public int getFactoryId() {
return ResponseSerializablePlusFactory.FACTORY_ID;
}
public int getClassId() {
return ResponseSerializablePlusFactory.RESPONSE_SERIALIZABLE_PLUS_CLASS;
}
#Override
public String toString() {
return "ResponseSerializablePlus [id_interno_pe=" + id_interno_pe + ", cod_nrbe_en=" + cod_nrbe_en
+ ", num_sec_ac=" + num_sec_ac + ", statusCode=" + statusCode + ", headers=" + headers + ", content="
+ Arrays.toString(content) + "]";
}
}
It's indeed not supported, and it's document, along with the alternative option. Have a look here: https://github.com/hazelcast/hazelcast/blob/3cb8ce1fc3bb848aced6c87a30bf7b31aec16cf7/hazelcast/src/main/java/com/hazelcast/query/Predicates.java#L492-L497

Application in JaveME using RMS

I'm trying write application in Jave ME with RMS. Application stores information about courier's customer.
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.DataOutputStream;
import java.io.DataInputStream;
public class ClientsApp extends MIDlet implements CommandListener {
// controls
private Display screen = null;
private List menu = null;
private Form addClientForm = null;
private Form showClientForm = null;
private RecordStore clients;
private ByteArrayOutputStream stream = null;
private DataOutputStream out = null;
private byte[] dates;
TextField name = null;
TextField surname = null;
TextField email = null;
TextField phone = null;
DateField date = null;
TextField price = null;
TextField description = null;
// comands
private final Command backCommand;
private final Command mainMenuCommand;
private final Command exitCommand;
private final Command addClientCommand;
public ClientsApp() {
// initializating controls and comands
menu = new List("Lista klientów", Choice.IMPLICIT);
backCommand = new Command("Cofnij", Command.BACK, 0);
mainMenuCommand = new Command("Main", Command.SCREEN, 1);
exitCommand = new Command("Koniec", Command.EXIT, 2);
addClientCommand = new Command("Zapisz", Command.OK, 3);
stream = new ByteArrayOutputStream();
out = new DataOutputStream(stream);
menu.append("Dodaj klienta", null);
menu.append("Przegladaj klientow", null);
menu.append("Usun klienta", null);
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
}
protected void pauseApp() {
}
protected void startApp() throws MIDletStateChangeException {
screen = Display.getDisplay(this);
screen.setCurrent(menu);
try {
clients = RecordStore.openRecordStore("clients", false, RecordStore.AUTHMODE_PRIVATE, false);
}
catch(RecordStoreException exc) {
}
menu.addCommand(exitCommand);
menu.setCommandListener(this);
}
public void commandAction(Command cmd, Displayable dsp) {
if(cmd.getCommandType() == Command.EXIT) {
try{
destroyApp(false);
notifyDestroyed();
}
catch(Exception exc) {
exc.printStackTrace();
}
}
else if(cmd.getCommandType() == Command.BACK) {
screen.setCurrent(menu);
}
else if(cmd.getCommandType() == Command.OK) {
try {
out.writeUTF(name.getString());
out.writeUTF(surname.getString());
out.writeUTF(email.getString());
out.writeUTF(phone.getString());
out.writeUTF(date.getDate().toString());
out.writeUTF(price.getString());
out.writeUTF(description.getString());
dates = stream.toByteArray();
clients.addRecord(dates, 0, dates.length);
stream.close();
out.close();
clients.closeRecordStore();
}
catch(Exception exc) {
}
}
else {
List option = (List) screen.getCurrent();
switch(option.getSelectedIndex()) {
case 0 : {
addClients();
break;
}
case 1 : {
showClients();
break;
}
case 2 : {
deleteClients();
break;
}
}
}
}
protected void addClients() {
addClientForm = new Form("Dodaj klienta");
name = new TextField("Imię klienta", "", 10, TextField.ANY);
surname = new TextField("Nazwisko klienta", "", 15, TextField.ANY);
email = new TextField("Email klienta", "", 20, TextField.EMAILADDR);
phone = new TextField("Numer telefonu", "", 12, TextField.PHONENUMBER);
date = new DateField("Data dostarczenia", DateField.DATE);
price = new TextField("Do zapłaty", "", 6, TextField.NUMERIC);
description = new TextField("Uwagi", "", 50, TextField.ANY);
addClientForm.append(name);
addClientForm.append(surname);
addClientForm.append(email);
addClientForm.append(phone);
addClientForm.append(date);
addClientForm.append(price);
addClientForm.append(description);
screen.setCurrent(addClientForm);
addClientForm.addCommand(backCommand);
addClientForm.addCommand(addClientCommand);
addClientForm.setCommandListener(this);
}
protected void showClients() {
TextBox info = new TextBox("Klienci", null, 100, 0);
RecordEnumeration iterator = null;
String str = null;
byte[] temp = null;
try {
iterator = clients.enumerateRecords(null, null, false);
while(iterator.hasNextElement()) {
temp = iterator.nextRecord();
}
for(int i = 0; i < temp.length; i++) {
str += (char) temp[i];
}
System.out.println(str);
clients.closeRecordStore();
}
catch(Exception exc) {
}
info.setString(str);
screen.setCurrent(info);
}
}
Write/read information from RecordStore don't work. I don't have any exception throw. Could somebody help me?
PS Sorry for my bad language.
Are you sure you do not get any exception? Catch blocks are empty...
I see several issues:
Shouldn't you open the record store with createIfNecessary (2nd parameter) set to true?
In ShowClients method, you should use DataInputStream to read items from the record (the byte array 'temp'), the loop over temp is strange. And a check for null 'temp' to avoid NPE when the store is empty is missing too.
On OK command, and also in ShowClients, the store is closed, so next time it will fail with RecordStoreNotOpenException I guess.
I would also consider flushing 'out' stream before calling stream.toByteArray(), although in this case (DataOutputStrea/ByteArrayOutputStream) it is nothing but a good practice..

Blackberry - How if addElement() doesn't work?

I am a newbie of Blackberry developing application. I try to store all xml parsing data to an object, and set them to a vector.
public class XmlParser extends MainScreen {
Database d;
private HttpConnection hcon = null;
private Vector binN;
public Vector getBinN() {
return binN;
}
public void setBinN(Vector bin) {
this.binN = bin;
}
LabelField from;
LabelField ttl;
LabelField desc;
LabelField date;
public XmlParser() {
LabelField title = new LabelField("Headline News" ,LabelField.HCENTER|LabelField.USE_ALL_WIDTH);
setTitle(title);
try {
URI myURI = URI.create("file:///SDCard/Database/WebFeed.db");
d = DatabaseFactory.open(myURI);
Statement st = d.createStatement("SELECT feed_url, feed_name FROM WebFeed");
st.prepare();
Cursor c = st.getCursor();
while (c.next()) {
Row r = c.getRow();
hcon = (HttpConnection)Connector.open(r.getString(0));
hcon.setRequestMethod(HttpConnection.GET);
hcon.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0");
hcon.setRequestProperty("Content-Length", "0");
hcon.setRequestProperty("Connection", "close");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
builder.isValidating();
Document document = builder.parse(hcon.openInputStream());
Element rootElement = document.getDocumentElement();
rootElement.normalize();
NodeList list = document.getElementsByTagName("item");
int i=0;
while (i<10){
Node item = list.item(i);
if(item.getNodeType() != Node.TEXT_NODE) {
NodeList itemChilds = item.getChildNodes();
int j=0;
while (j<10){
Node detailNode = itemChilds.item(j);
if(detailNode.getNodeType() != Node.TEXT_NODE) {
if(detailNode.getNodeName().equalsIgnoreCase("title")) {
ttl = new LabelField(getNodeValue(detailNode)) {
public void paint(Graphics g) {
g.setColor(Color.BLUE);
super.paint(g);
}
};
from = new LabelField(r.getString(1), LabelField.FIELD_RIGHT|LabelField.USE_ALL_WIDTH);
ttl.setFont(Font.getDefault().derive(Font.BOLD));
from.setFont(Font.getDefault().derive(Font.BOLD));
add (from);
add (ttl);
} else if(detailNode.getNodeName().equalsIgnoreCase("description")) {
desc = new LabelField(getNodeValue(detailNode), 0, 70, USE_ALL_WIDTH);
add(desc);
} else if(detailNode.getNodeName().equalsIgnoreCase("dc:date")) {
date = new LabelField(getNodeValue(detailNode), 11, 5, USE_ALL_WIDTH) {
public void paint(Graphics g) {
g.setColor(Color.ORANGE);
super.paint(g);
}
};
add(date);
add(new SeparatorField());
} else if(detailNode.getNodeName().equalsIgnoreCase("pubDate")) {
date = new LabelField(getNodeValue(detailNode), 0, 22, USE_ALL_WIDTH) {
public void paint(Graphics g) {
g.setColor(Color.ORANGE);
super.paint(g);
}
};
add(date);
add(new SeparatorField());
} else {
System.out.println("not the node");
}
} else {
System.out.println("not text node");
}
j++;
}
}
i++;
BinNews bin = new BinNews();
bin.setProv(from.getText());
bin.setTitle(ttl.getText());
bin.setDesc(desc.getText());
bin.setDate(date.getText());
binN.addElement(bin);
}
setBinN(binN);
}
//setBinN(binN);
st.close();
d.close();
} catch (Exception e) {
add (new LabelField(e.toString(),LabelField.HCENTER|LabelField.USE_ALL_WIDTH));
System.out.println(e.toString());
}
}
public String getNodeValue(Node node) {
NodeList nodeList = node.getChildNodes();
Node childNode = nodeList.item(0);
return childNode.getNodeValue();
}
}
I try to store all data from an object called BinNews, to a vector called binN. But when I do debugging, I found that BinN has null value, because "binN.addElement(bin)" doesn't work.
Please advise.
First, you don't actually call setBinN until after the while(i < 10) loop completes. So when you say binN.addElement(bin) then binN will be null.
However your setBinN(binN) call doesn't make sense because you're passing in binN and then setting it to itself which isn't going to do anything.
What you can do is have binN = new Vector(); at the top of the constructor and then it won't be null later on. I don't think the setBinN call will be necessary later on if you're adding the BinNews objects straight to binN.

No Overload for method 'Render' takes 1 arguments

This is my code i have done it for my project to genrate a pdf report
public partial class Report : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
getreport();
}
}
public override void VerifyRenderingInServerForm(Control control)
{
// base.VerifyRenderingInServerForm(control);
}
public void getreport()
{
string province = Request.QueryString["Province"].ToString();
string district = Request.QueryString["District"].ToString();
string village = Request.QueryString["Village"].ToString();
ReportViewer1.ProcessingMode = ProcessingMode.Local;
LocalReport rep = ReportViewer1.LocalReport;
rep.ReportPath = #"Report.rdlc";
ReportDataSource dsRep = new ReportDataSource();
dsRep.Name = "DataSet1";
dsRep.Value = GetDataTable(province, district, village);
rep.DataSources.Clear();
rep.DataSources.Add(dsRep);
//ReportViewer1.DocumentMapCollapsed = true;
//ReportViewer1.ShowPrintButton = true;
//rep.Render("PDF");
byte[] result = null;
result = rep.Render("PDF");
Response.ClearContent();
Response.AppendHeader("content-length", result.Length.ToString());
Response.ContentType = "application/pdf";
Response.BinaryWrite(result);
Response.Flush();
Response.Close();
rep.Refresh();
}
protected DataTable GetDataTable(string p,string d,string v)
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DBConnectionString"].ToString());
DataTable dt;
SqlDataAdapter da;
SqlCommand cmd;
string filter = "";
try
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
cmd = new SqlCommand("select '" +p + "' as UserName, '"+d+"'Password,'"+ v+"' as category", con);
da = new SqlDataAdapter(cmd);
dt = new DataTable();
da.Fill(dt);
cmd.Dispose();
con.Close();
return dt;
}
catch (Exception ex)
{
return null;
}
}
The Render method does have an overload that takes one parameter in .NET 4.0, but not in previous versions.
You'll have to call the (String, String, out String, out String, out String, out String[], out Warning[]) overload as below.
string extension;
string encoding;
string mimeType;
string extension;
string[] streams;
Warning[] warnings;
result = rsExec.Render("PDF", null,
out extension, out encoding,
out mimeType, out streams, out warnings);

How to sort recordstore records based on a certain field in it?

For example there are three records in a recordstore , and the structure of a record in the recordstore is like this : lastname;firstname;moneyborrowed
I want to show these three records inside a LWUIT Table and I want them to be sorted by the lastname column. How to achieve that ?
save using
Preferences preferences = new Preferences("mydbname");
preferences.put("key","lastname;firstname;moneyborrowed");
preferences.save();
and retrieve using
String val = (string) preferences.get("key");
Preferences.java
import java.util.Enumeration;
import java.util.Hashtable;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
public class Preferences {
private final String mRecordStoreName;
private final Hashtable mHashtable;
public Preferences(String recordStoreName)
throws RecordStoreException {
mRecordStoreName = recordStoreName;
mHashtable = new Hashtable();
load();
}
public String get(String key) {
return (String)mHashtable.get(key);
}
public void put(String key, String value) {
if (value == null) value = "";
mHashtable.put(key, value);
}
private void load() throws RecordStoreException {
RecordStore rs = null;
RecordEnumeration re = null;
try {
rs = RecordStore.openRecordStore(mRecordStoreName, true);
re = rs.enumerateRecords(null, null, false);
while (re.hasNextElement()) {
byte[] raw = re.nextRecord();
String pref = new String(raw);
// Parse out the name.
int index = pref.indexOf('|');
String name = pref.substring(0, index);
String value = pref.substring(index + 1);
put(name, value);
}
}
finally {
if (re != null) re.destroy();
if (rs != null) rs.closeRecordStore();
}
}
public void save() throws RecordStoreException {
RecordStore rs = null;
RecordEnumeration re = null;
try {
rs = RecordStore.openRecordStore(mRecordStoreName, true);
re = rs.enumerateRecords(null, null, false);
// First remove all records, a little clumsy.
while (re.hasNextElement()) {
int id = re.nextRecordId();
rs.deleteRecord(id);
}
// Now save the preferences records.
Enumeration keys = mHashtable.keys();
while (keys.hasMoreElements()) {
String key = (String)keys.nextElement();
String value = get(key);
String pref = key + "|" + value;
byte[] raw = pref.getBytes();
rs.addRecord(raw, 0, raw.length);
}
}
finally {
if (re != null) re.destroy();
if (rs != null) rs.closeRecordStore();
}
}
}

Resources