lưu và truy xuất data sử dụng rms
ứng dụng thực tế: ví dụ lưu settings của chương trình lại để lần sau chương trình có thể truy xuất và setup với settings đã được lưu.
method để lưu data:
Mã:
/**
* save data to rms.
*
*/
private void savedata(string mydata) throws recordstoreexception, ioexception {
try {
recordstore.deleterecordstore("mydata"); // delete recordstore có sẵn ứng với tên mình đặt
}
catch (recordstoreexception e) {
}
recordstore store = recordstore.openrecordstore("mydata", true); // tạo mới với tên mình đặt
try {
bytearrayoutputstream buffer = new bytearrayoutputstream();
dataoutputstream output = new dataoutputstream(buffer);
output.writeutf(mydata); // lưu chuỗi string.
store.addrecord(buffer.tobytearray(), 0, buffer.size());
}
finally {
store.closerecordstore();
}
}
method để load data:
Mã:
/**
* load data
*
*/
private string loaddata() throws recordstoreexception, ioexception {
string mydata = "";
try {
recordstore store = recordstore.openrecordstore("mydata", false); // mở recordstore với tên mình đặt từ trước
try {
bytearrayinputstream buffer = new bytearrayinputstream(store.getrecord(1)); // first record index is 1 (not 0 as usual)
datainputstream input = new datainputstream(buffer);
mydata = input.readutf(); // load dữ liệu được lưu vào biến mydata
}
finally {
store.closerecordstore();
}
}
catch (exception e) {
system.out.println(e.tostring());
}
return mydata;
}
đối với dữ liệu khi lưu thì có thể là string, int, boolean... và ứng với mỗi loại ta có những method tương ứng như writeutf, writeint, writeboolean.... và readutf, readint, readboolean...
khi lưu dữ liệu thì dữ liệu được lưu theo thứ tự và khi load cũng theo thứ tự.
cách thức load dữ liệu cũng tùy thuộc vào developer. load rồi return hoặc sau khi load thì gán cho biến...
ví dụ lần đầu vào chương trình ta cho người dùng nhập tên vào 1 ô text.
basiceditfield name = new basiceditfield("");
sau khi người dùng nhập xong thì gọi method:
savesettings(name.gettext());
lần sau khi vào chương trình thì có thể báo 1 câu chào:
dialog.alert("xin chào " + loaddata());
đối với việc lưu data vào rms sẽ không làm mất data khi thoát khỏi chương trình. do đó lần sau mở chương trình thì ta có thể sử dụng data được lưu sẵn trên máy.
View more random threads:
Vệ sinh cá nhân chủ nghĩa là một phần quan trọng của sức khỏe nam giới. Dùng dung dịch vệ sinh mỗi ngày mang lại nhiều lợi., giúp loại bỏ vi khuẩn và vi sinh vật gây hại, giúp khu vực cơ quan sinh...
Gel vệ sinh dương vật, đàn ông có nên dùng ?