Record store in lwuit - lwuit

Does LWUIT have an implementation for j2me record store?
I have made a lwuit app which uses j2me recordstore. However, I feel that using lwuit api without jumping into j2me api would help make the app more portable. Am I right?
Thanks

Yes, LWUIT has a record store. Check Storage Class of LWUIT IO, but this is only available in LWUIT 1.5.
Yes, it would make it more portable.

You can use J2ME record store for this i.e. RMS record management store.

You no need LWUIT for RS
public static void writeDataToRecordStore(byte[] aData, final String aDir) {
if (aData == null) {
return;
}
RecordStore iRecord = null;
try {
iRecord = RecordStore.openRecordStore(aDir, true);
if (iRecord.getNumRecords() > 0) {
iRecord.setRecord(1, aData, 0, aData.length);
} else {
iRecord.addRecord(aData, 0, aData.length);
}
} catch (Exception ex) {
} finally {
if (iRecord != null) {
try {
iRecord.closeRecordStore();
} catch (Exception ex) {
}
iRecord = null;
}
}
}
/**
* Read data from Record Store
*
* #param aDir
* #return
*/
public static byte[] readDataFromRecordStore(final String aDir) {
RecordStore iReccord = null;
try {
iReccord = RecordStore.openRecordStore(aDir, false);
if (iReccord.getNumRecords() > 0) {
// Has data
return iReccord.getRecord(1);
}
} catch (Exception otherEx) {
} finally {
if (iReccord != null) {
try {
iReccord.closeRecordStore();
} catch (Exception ex1) {
}
}
}
return null;
}

Lwuit using Record Store in HTML Component.
And I think, using record store is not related with LWUIT. They both separate function. LWUIT is for User Interface / View, record store is for data / model.

Related

Opening a Postgres Connection in Xamarin returns Error While Connecting

I am trying to connect my Android Application to Postgres but seems not to work.
The Exception Message is: Exception while Connecting
This is my Code Behind,
private void Login_Clicked(object sender, EventArgs e)
{
DBInterface<DBLogicInput, DBLogicResult> dbLoginLogic = new DBLoginLogic();
DBLogicInput userInput = new DBLogicInput();
DBLogicResult DBResult = new DBLogicResult();
LoginModel useCredentials = new LoginModel()
{
userName = txtUsername.Text,
passWord = txtPassword.Text
};
userInput[typeof(LoginModel).FullName] = useCredentials;
try
{
DBResult = dbLoginLogic.DoProcess(userInput);
bool userExisting = DBResult.ResultCode != DBLogicResult.RESULT_CODE_ERR_DATA_NOT_EXIST;
if (userExisting)
{
Application.Current.MainPage = new NavigationPage(new IndexPage());
}
else
{
_ = DisplayAlert("Login Error", "User does not exist", "Ok");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
This is the Class I created to connect the DB.
public abstract class DBLogic : DBInterface<DBLogicInput, DBLogicResult>
{
public string connectionString = "Server=localhost;Port=5432;User Id=postgres;Password=postgres;Database=proyektoNijuan";
public DBLogicResult DoProcess(DBLogicInput inOut)
{
//throw new NotImplementedException();
DBLogicResult result = default(DBLogicResult);
NpgsqlConnection connection = null;
NpgsqlTransaction transaction = null;
try {
connection = new NpgsqlConnection(connectionString);
if (connection.State != System.Data.ConnectionState.Open)
{
connection.Open();
}
transaction = connection.BeginTransaction();
result = Process(connection, inOut);
transaction.Commit();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
transaction.Rollback();
} finally {
if (connection != null)
{
connection.Close();
}
}
return result;
}
protected abstract DBLogicResult Process(NpgsqlConnection conn, DBLogicInput InOuT);
}
The error exists after the debugger hits the code connection.Open();.
Should I add a web services to connect the postgres to my android app built in xamarin forms?
I am only a beginner in Xamarin Forms. I am just trying to create a self application. And need a little help for me to learn a new platform in programming.
Thank you and Regards,
How to fix it?
Well, I think I am doing it wrong.
Maybe the Right way to Connect the PostgreSQL is to have a WEB API.
Calling that web API to the Xamarin forms.
I really don't know if it is correct, but I will give it a try.
I will update the correct answer after I finish the development of that WEB API so that other beginners will found this answer helpful.

Azure Mobile Apps Offline Client Throws NotSupportedException on Query

I have a Azure Mobile Apps Xamarin.Forms PCL client and have Offline Sync enabled. I tried to Pull data from my backend and afterwards query data from the offline storage with a Where clause. That throws the following exception and I don't know why.
Sync error: 'fahrerinfo.Imei.Equals("02032032030232")' is not supported in a 'Where' Mobile Services query expression.
public async Task SyncAsync()
{
ReadOnlyCollection<MobileServiceTableOperationError> syncErrors = null;
try
{
await OfflineSyncStoreManager.Instance.TruckFahrerTable.PullAsync("allTruckFahrerItems",
OfflineSyncStoreManager.Instance.TruckFahrerTable.CreateQuery());
Debug.WriteLine("SyncAsync: PUSH/PULL completed.");
}
catch (MobileServicePushFailedException e)
{
Debug.WriteLine("SyncAsync: PUSH failed.");
Debug.WriteLine(e.Message);
}
catch (Exception e)
{
Debug.WriteLine("SyncAsync: PUSH/PULL failed.");
Debug.WriteLine(e.Message);
//Debugger.Break();
}
}
public async Task<ObservableCollection<TruckFahrer>> GetTruckFaherAsync(bool syncItems)
{
try
{
if (syncItems)
{
await OfflineSyncStoreManager.Instance.SyncAsync().ConfigureAwait(false);
}
var deviceInfo = DependencyService.Get<IDeviceInfo>().GetPhoneInfo();
var imeiString = deviceInfo[trucker_rolsped.PhoneInfo.PhoneInfo.ImeiKey];
var imei = imeiString.Equals("000000000000000") ? deviceInfo[trucker_rolsped.PhoneInfo.PhoneInfo.IdKey] : imeiString;
IEnumerable<TruckFahrer> items =
await OfflineSyncStoreManager.Instance.TruckFahrerTable
//.Where(fahrerinfo => fahrerinfo.Imei.Equals(imei)) TODO: Why does that throw an exception???
.ToEnumerableAsync();
// TODO: Because above does not work
items = items.Where(fahrer => fahrer.Imei.Equals(imei));
return new ObservableCollection<TruckFahrer>(items);
}
catch (MobileServiceInvalidOperationException msioe)
{
Debug.WriteLine(#"Invalid sync operation: {0}", msioe.Message);
Debugger.Break();
}
catch (Exception e)
{
Debug.WriteLine(#"Sync error: {0}", e.Message);
Debugger.Break();
}
return null;
}
Thanks for any hint,
Eric
Are you a Java developer too? I'm and had this issue because in Java we need to compare strings with String#equals method, haha.
For some reason MobileServices doesn't allow us to use Equals in this situation.
To fix your problem, use == instead. As you can see here C# difference between == and Equals() both have the same effect in this case.
Where(fahrerinfo => fahrerinfo.Imei == imei)

Testing that an Object exists in a Bucket?

I am trying to figure out what the most efficient way to test of the existence of an Object in a Bucket in Google Cloud Store.
This is what I am doing now:
try
{
final GcsFileMetadata md = GCS_SERVICE.getMetadata(bm.getFilename());
if (md == null)
{
// do what I need to do here!
}
}
catch (IOException e)
{
L.error(e.getMessage());
}
Because according to the documentation it returns null if the GcsFilename does not exist.
.
/**
* #param filename The name of the file that you wish to read the metadata of.
* #return The metadata associated with the file, or null if the file does not exist.
* #throws IOException If for any reason the file can't be read.
*/
GcsFileMetadata getMetadata(GcsFilename filename) throws IOException;
Using .list() on a Bucket and checking for .contains() sounds expensive but is explicit in its intention.
Personally I think testing for null to check if something exists is inelegant and not as direct as GCS_SERVICE.objectExists(fileName); but I guess I don't get to design the GCS Client API. I will just create a method to do this test in my API.
Is there a more efficient ( as in time ) or more self documenting way to do this test?
Solution
Here is the working solution I ended up with:
#Nonnull
protected Class<T> getEntityType() { (Class<T>) new TypeToken<T>(getClass()) {}.getRawType(); }
/**
* purge ObjectMetadata records that don't have matching Objects in the GCS anymore.
*/
public void purgeOrphans()
{
ofy().transact(new Work<VoidWork>()
{
#Override
public VoidWork run()
{
try
{
for (final T bm : ofy().load().type(ObjectMetadataEntityService.this.getEntityType()).iterable())
{
final GcsFileMetadata md = GCS_SERVICE.getMetadata(bm.getFilename());
if (md == null)
{
ofy().delete().entity(bm);
}
}
}
catch (IOException e)
{
L.error(e.getMessage());
}
return null;
}
});
}
They added the file.exists() method.
const fileExists = _=>{
return file.exists().then((data)=>{ console.log(data[0]); });
}
fileExists();
//logs a boolean to the console;
//true if the file exists;
//false if the file doesn't exist.

observing for subset of event using jtapi provider

I am using cisco jtapi v7+ and investigating whether I can add a provider to only listen to certain (not all) events. However, the only call I see in the API is the following:
provider.addObserver(ProviderObserver);
I would like to avoid filtering events in my application and have it done through the API. Any thoughts/insight on this would be appreciated!
You must add CallObserver instance to address which you want listen, then filtering events. For example:
Address srcAddr = provider.getAddress(src);
co = new CallObserver() {
public void callChangedEvent(CallEv[] eventList) {
for (int i = 0; i < eventList.length; ++i) {
try {
if (eventList[i].getID() == TermConnRingingEv.ID) {
session.getBasicRemote().sendText("new_call");
}
} catch (Exception ex) {
ex.printStackTrace();
}
if (eventList[i].getID() == ConnDisconnectedEv.ID) {
try {
System.out.println("Disconnected");
session.getBasicRemote().sendText("disconnected");
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (eventList[i] instanceof CallObservationEndedEv) {
System.out.println("Event: Call Observation Ended");
}
if (eventList[i] instanceof CiscoAddrOutOfServiceEv) {
System.out.println("Event: Address Out of service");
}
System.out.println("State: " + eventList[i].getCall().getState());
}
}
};
srcAddr.addCallObserver(co);

how to receive sms in netbeans mobile application

I am developing a mobile application in net-beans that will send and receive SMS, I'm done with sending text but I don't know how to receive SMS in NetBeans mobile application ?
WMA (Wireless Messaging API) is a wireless messaging api defined in MIDP 2.0. These apis are designed to handle text, binary and multipart messages. To make a connection, the application obtains an object implementing the MessageConnection from the Connector class by providing an URL connection string that identifies the address.
/* Make a connection */
public boolean connectSMSServer()
{
try
{
messageConnection messageConnection =
(MessageConnection)Connector.open("sms://:" + port);
messageConnection.setMessageListener(this);
}
catch (Exception e) {
}
}
/* Send text message */
public void sendTextmessage(String address,String message)
{
try
{
//creates a new TextMessage
TextMessage textMessage = (TextMessage)messageConnection.newMessage(
MessageConnection.TEXT_MESSAGE, address);
textMessage.setPayloadText(message);
messageConnection.send(textMessage);
}
catch (Exception e) {
}
}
/* Recieve text message */
public void receiveTextMessage()
{
try
{
Message message = messageConnection.receive();
if (message instanceof TextMessage)
{
TextMessage textMessage = (TextMessage)message;
}
else
{
//Message can be binary or multipart
}
}
catch (Exception e) {
}
}
/* Notify Incoming Message */
public synchronized void notifyIncomingMessage(MessageConnection conn)
{
//notiy thread of incoming message
synchronized (this)
{
notify();
}
}
/* Close Connection */
public void closeConnection()
{
if (messageConnection != null)
{
try
{
messageConnection.setMessageListener(null);
messageConnection.close();
}
catch (Exception e) {
}
}
}
}
When you are coding for Receiving SMS, you need to listen to one particular port. J2ME Application can not read directly from the inbox.