Native Interface for J2Me device Codename One - java-me

I created an Interface class:
package userclasses;
import com.codename1.system.NativeInterface;
public interface NativeJ2MEInterface extends NativeInterface {
public void pollBackground();
}
This is the native class - after I edited it:
package userclasses;
import userclasses.StateMachine;
public class NativeJ2MEInterfaceImpl {
public void pollBackground() {
try {
Date now = new Date();
long timeToRun = now.getTime() + (1000 * 60 );
System.out.println("RUNNNNNNN forest runnn!");
PushRegistry.registerAlarm(StateMachine.class.getName(), timeToRun);
}
catch (Exception e) {
System.out.println("EXC-1:"+e.getMessage());
}
}
public boolean isSupported() {
return true;
}
}
I want to call the javax.microedition.io.PushRegistry registerAlarm method, but my Codename One J2ME build fails saying:
error: cannot find symbol
PushRegistry.registerAlarm(StateMachine.class.getName(), timeToRun);
I added a midp_2.1.jar to the native j2me directory, but it did not work.
How can I get this to work? Or how can I directly access j2me alarm API?

Don't add the jar, it will get packaged into the final build.
Try setting the build argument j2me.ashaNative=true.

Related

Commons Configuration2 ReloadingFileBasedConfiguration

I am trying to implement the Apache Configuration 2 in my codebase
import java.io.File;
import java.util.concurrent.TimeUnit;
import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.builder.ConfigurationBuilderEvent;
import org.apache.commons.configuration2.builder.ReloadingFileBasedConfigurationBuilder;
import org.apache.commons.configuration2.builder.fluent.Parameters;
import org.apache.commons.configuration2.convert.DefaultListDelimiterHandler;
import org.apache.commons.configuration2.event.EventListener;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.apache.commons.configuration2.reloading.PeriodicReloadingTrigger;
import org.apache.commons.configuration2.CompositeConfiguration;
public class Test {
private static final long DELAY_MILLIS = 10 * 60 * 5;
public static void main(String[] args) {
// TODO Auto-generated method stub
CompositeConfiguration compositeConfiguration = new CompositeConfiguration();
PropertiesConfiguration props = null;
try {
props = initPropertiesConfiguration(new File("/tmp/DEV.properties"));
} catch (ConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
compositeConfiguration.addConfiguration( props );
compositeConfiguration.addEventListener(ConfigurationBuilderEvent.ANY,
new EventListener<ConfigurationBuilderEvent>()
{
#Override
public void onEvent(ConfigurationBuilderEvent event)
{
System.out.println("Event:" + event);
}
});
System.out.println(compositeConfiguration.getString("property1"));
try {
Thread.sleep(14*1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Have a script which changes the value of property1 in DEV.properties
System.out.println(compositeConfiguration.getString("property1"));
}
protected static PropertiesConfiguration initPropertiesConfiguration(File propsFile) throws ConfigurationException {
if(propsFile.exists()) {
final ReloadingFileBasedConfigurationBuilder<PropertiesConfiguration> builder =
new ReloadingFileBasedConfigurationBuilder<PropertiesConfiguration>(PropertiesConfiguration.class)
.configure(new Parameters().fileBased()
.setFile(propsFile)
.setReloadingRefreshDelay(DELAY_MILLIS)
.setThrowExceptionOnMissing(false)
.setListDelimiterHandler(new DefaultListDelimiterHandler(';')));
final PropertiesConfiguration propsConfiguration = builder.getConfiguration();
PeriodicReloadingTrigger trigger = new PeriodicReloadingTrigger(builder.getReloadingController(),
null, 1, TimeUnit.SECONDS);
trigger.start();
return propsConfiguration;
} else {
return new PropertiesConfiguration();
}
}
}
Here is a sample code that I using to check whether the Automatic Reloading works or not. However when the underlying property file is updated, the configuration doesn't reflect it.
As per the documentation :
One important point to keep in mind when using this approach to reloading is that reloads are only functional if the builder is used as central component for accessing configuration data. The configuration instance obtained from the builder will not change automagically! So if an application fetches a configuration object from the builder at startup and then uses it throughout its life time, changes on the external configuration file become never visible. The correct approach is to keep a reference to the builder centrally and obtain the configuration from there every time configuration data is needed.
https://commons.apache.org/proper/commons-configuration/userguide/howto_reloading.html#Reloading_File-based_Configurations
This is different from what the old implementation was.
I was able to successfully execute your sample code by making 2 changes :
make the builder available globally and access the configuration from the builder :
System.out.println(builder.getConfiguration().getString("property1"));
add the listener to the builder :
`builder.addEventListener(ConfigurationBuilderEvent.ANY, new EventListener() {
public void onEvent(ConfigurationBuilderEvent event) {
System.out.println("Event:" + event);
}
});
Posting my sample program, where I was able to successfully demonstrate it
import java.io.File;
import java.util.concurrent.TimeUnit;
import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.builder.ConfigurationBuilderEvent;
import org.apache.commons.configuration2.builder.ReloadingFileBasedConfigurationBuilder;
import org.apache.commons.configuration2.builder.fluent.Parameters;
import org.apache.commons.configuration2.event.EventListener;
import org.apache.commons.configuration2.reloading.PeriodicReloadingTrigger;
public class TestDynamicProps {
public static void main(String[] args) throws Exception {
Parameters params = new Parameters();
ReloadingFileBasedConfigurationBuilder<PropertiesConfiguration> builder =
new ReloadingFileBasedConfigurationBuilder<PropertiesConfiguration>(PropertiesConfiguration.class)
.configure(params.fileBased()
.setFile(new File("src/main/resources/override.properties")));
PeriodicReloadingTrigger trigger = new PeriodicReloadingTrigger(builder.getReloadingController(),
null, 1, TimeUnit.SECONDS);
trigger.start();
builder.addEventListener(ConfigurationBuilderEvent.ANY, new EventListener<ConfigurationBuilderEvent>() {
public void onEvent(ConfigurationBuilderEvent event) {
System.out.println("Event:" + event);
}
});
while (true) {
Thread.sleep(1000);
System.out.println(builder.getConfiguration().getString("property1"));
}
}
}
The problem with your implementation is, that the reloading is done on the ReloadingFileBasedConfigurationBuilder Object and is not being returned to the PropertiesConfiguration Object.

Not Implemented Exception while using Insight.Database micro ORM

I was trying to use the cool Insight.Database micro ORM and run into a Not Implemeneted exception everytime I try to invoke the InsertCustomer method in the CustomerRepository.Any help would be appreciated
Update: I made sure that the method name matches the sql server stored procedure name
public class CustomerRepository
{
private ICustomerRepository _repo;
public static async Task<int> InsertCustomer(Customer cust)
{
var _repo = ConfigSettings.CustomerRepository;
return await _repo.InsertCustomer(cust);
}
}
public class ConfigSettings
{
private static ICustomerRepository _customerRepository;
public static ICustomerRepository CustomerRepository
{
get
{
if (_customerRepository == null)
{
_customerRepository = new SqlConnection(ConfigurationManager.ConnectionStrings["CustomerService_Conn_String"].ConnectionString).AsParallel<ICustomerRepository>();
}
return _customerRepository;
}
}
}
[Sql(Schema="dbo")]
public interface ICustomerRepository
{
[Sql("dbo.InsertCustomer")]
Task<int> InsertCustomer(Customer cust);
}
If you're getting a NotImplementedException, and running v4.1.0 to 4.1.3 you're probably running into a problem registering your database provider.
I recommend using v4.1.4 or later and making sure you register the provider for your database.
See
https://github.com/jonwagner/Insight.Database/wiki/Installing-Insight
If you have any more problems, you can post an issue on github.

Dependency Property usage in Silverlight

I am just following the code examples of a Beginning SilverLight book and here is part of the code about user controls and Dependeny Property that I have typed from the book into my IDE:
public class CoolDownButtonControl: Control
{
public static readonly DependencyProperty CoolDownSecondsProperty =
DependencyProperty.Register(
"CoolDownSeconds",
typeof(int),
typeof(CoolDownButtonControl),
new PropertyMetadata(
new PropertyChangedCallback(
CoolDownButtonControl.OnCoolDownSecondsPropertyChanged
)
)
);
public int CoolDownSeconds
{
get
{
return (int)GetValue(CoolDownSecondsProperty);
}
set
{
SetValue(CoolDownSecondsProperty, value);
}
}
private static void OnCoolDownSecondsPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
CoolDownButtonControl cdBuutton = d as CoolDownButtonControl;
cdBuutton.OnCoolDownButtonChange(null);
}
}
The problem is that IDE highlights the line of cdBuutton.OnCoolDownButtonChange(null); complaining about
CoolDownButtonControl does not contain a definition for
OnCoolDownButtonChange
As I am new to this and hoping to learn it from this example I couldn't figure out what is wrong and how to fix it?
You should add that method too, something like this:
protected virtual void OnCoolDownButtonChange(RoutedEventArgs e)
{
}

NoClassDefFoundError in j2me

I have build a jar file and trying to use it in j2me application. I have included the jar in the build path and imported the required classes as well. But when I run my j2me application I am getting NoClassDefFound Error in the line where I am trying to instantiate the class which is present in the jar.
I can instantiate the classes of the jar in the java project but not in j2me.
Below is the error log:
WARNING - MMA -
C:/Builds/jme-sdk/javacall-javame-sdk-305/implementation/share/jsr135_mmapi/ju_mmconfig.c
line 801: caps: optional settings missing: SuspendBehavior
java.lang.NoClassDefFoundError: com/canvasm/ida/gps/LocationUpdater
- com.test.ida.HelloIDA.(HelloIDA.java:11)
- java.lang.Class.newInstance(), bci=0
- com.sun.midp.main.CldcMIDletLoader.newInstance(), bci=46
- com.sun.midp.midlet.MIDletStateHandler.createMIDlet(), bci=66
- com.sun.midp.midlet.MIDletStateHandler.createAndRegisterMIDlet(), bci=17
- com.sun.midp.midlet.MIDletStateHandler.startSuite(), bci=27
- com.sun.midp.main.AbstractMIDletSuiteLoader.startSuite(), bci=52
- com.sun.midp.main.CldcMIDletSuiteLoader.startSuite(), bci=8
- com.sun.midp.main.AbstractMIDletSuiteLoader.runMIDletSuite(), bci=161
- com.sun.midp.main.AppIsolateMIDletSuiteLoader.main(), bci=26 javacall_lifecycle_state_changed() lifecycle: event is
JAVACALL_LIFECYCLE_MIDLET_SHUTDOWN status is JAVACALL_OK
TestApp(j2me app):
import com.test.gps.LocationUpdater;
public class Hello extends MIDlet {
public Hello() {
LocationUpdater loc = new LocationUpdater();
System.out.println("Loc updater object :"+loc.toString());
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
// TODO Auto-generated method stub
}
protected void pauseApp() {
// TODO Auto-generated method stub
}
protected void startApp() throws MIDletStateChangeException {
}
}
JAR file main class:
public class LocationUpdater {
private boolean isUpdateSuccess = false;
public static void main(String[] args){
}
public boolean updateLocation(final String serverUrl, final String userMSISDN) throws LocationException{
AppConstants.url = serverUrl;
AppConstants.msisdn = userMSISDN;
LocationCanvas loc = new LocationCanvas();
isUpdateSuccess = loc.getLocation(serverUrl, userMSISDN);
return isUpdateSuccess;
}
}
LocationCanvas class:
public class LocationCanvas {
private Location location;
private LocationProvider locationProvider;
private Coordinates coordinates;
private Criteria criteria;
private Timer tm;
private double lat, lon;
private String posturl;
private boolean status,updateStatus;
public LocationCanvas() {
}
public boolean getLocation(String url, String msisdn) {
tm = new Timer();
criteria = new Criteria();
criteria.setHorizontalAccuracy(500);
try {
locationProvider = LocationProvider.getInstance(criteria);
if (locationProvider != null) {
tm.wait(4000);
try {
location = locationProvider.getLocation(2000);
} catch (Exception e) {
System.out.println(e.getMessage());
}
coordinates = (Coordinates)location.getQualifiedCoordinates();
if (coordinates != null) {
// Use coordinate information
lat = coordinates.getLatitude();
lon = coordinates.getLongitude();
System.out.println("Latitude :"+lat);
System.out.println("Longitude :"+lon);
}
posturl = url + "?IMEI=" + msisdn
+ "&positioningtype=" + "gps" + "&locationdata=" + lat
+ "," + lon;
}else{
//return false.. cos location provider is null
updateStatus = false;
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return updateStatus;
}
error log:
Exception in thread "main" java.lang.NoClassDefFoundError:
javax/microedition/location/Coordinates
at com.canvasm.ida.gps.LocationUpdater.updateLocation(LocationUpdater.java:17)
at com.test.HelloTest.main(HelloTest.java:10)
Caused by: java.lang.ClassNotFoundException: javax.microedition.location.Coordinates
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
Any help would be appreciated.
It specifies that class file present at compile time is not found at run time.Check for build time and run time classpaths .
Finally able to solve the issue.
The problem was not in the code. It was due to the compilation issue.
First of all To solve the NoClassDefFoundError , I had to right click on the project and in the build path-> order and export -> check the jar that you have added.
Later while running I faced classFormatError 56.
The jar file which was created, was compiled using 1.6v.
And the j2me application was getting compiled with 1.3v.
I had to recompile my library project with 1.3v and create a jar out of it and used it in the j2me application.
Here is the link to guide: Build a Project from the Command Line - Java ME SDK

j2me bluetooth client. Function startInquiry nothing found

I develop simple j2me bluetooth client and have problem with bluetooth device search.
Function startInquiry nothing found.
Client : nokia 5220
Server : my pc with bluetooth adapter
All bluetooth devices is on.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import javax.microedition.midlet.*;
import javax.bluetooth.*;
import java.util.Vector;
import javax.microedition.lcdui.*;
/**
* #author Администратор
*/
public class Midlet extends MIDlet implements DiscoveryListener
{
private static Vector vecDevices=new Vector();
private static String connectionURL=null;
private LocalDevice localDevice;
private DiscoveryAgent agent;
private RemoteDevice remoteDevice;
private RemoteDevice[] devList;
private Display display;
private Form form;
public void startApp() {
display = Display.getDisplay(this);
form = new Form( "Client" );
try {
localDevice = LocalDevice.getLocalDevice();
} catch( BluetoothStateException e ) {
e.printStackTrace();
}
form.append("Address: "+localDevice.getBluetoothAddress()+"\n\n");
form.append("Name: "+localDevice.getFriendlyName()+"\n\n");
try {
agent = localDevice.getLocalDevice().getDiscoveryAgent();
form.append("Starting device inquiry... \n\n");
boolean si = agent.startInquiry(DiscoveryAgent.GIAC, this);
if ( si ) {
form.append("true");
} else {
form.append("false");
}
} catch( BluetoothStateException e ) {
}
int deviceCount = vecDevices.size();
if(deviceCount <= 0){
form.append("No Devices Found .");
}
else{
//print bluetooth device addresses and names in the format [ No. address (name) ]
form.append("Bluetooth Devices: ");
for (int i = 0; i < deviceCount; i++) {
remoteDevice=(RemoteDevice)vecDevices.elementAt(i);
form.append( remoteDevice.getBluetoothAddress() );
}
}
display.setCurrent(form);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
//add the device to the vector
if(!vecDevices.contains(btDevice)){
vecDevices.addElement(btDevice);
}
}
public void inquiryCompleted(int discType)
{
}
//implement this method since services are not being discovered
public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
if(servRecord!=null && servRecord.length>0){
connectionURL=servRecord[0].getConnectionURL(0,false);
}
}
//implement this method since services are not being discovered
public void serviceSearchCompleted(int transID, int respCode) {
}
}
Not sure what the exact problem is, but you definitely don't want to be doing this in your midlet's startApp() method. This is a system lifecycle method, and should return quickly, but scanning for bluetooth devices will block it for a long time. Your startApp() method is tying up the device's resources which it could need for doing the actual scanning!
Refactor, so your device scanning is done in a new thread, then see what happens.
You seem to have misunderstood how the Bluetooth API works. The startInquiry method only starts the device discovery process and returns immediately afterwards, leaving the discovery running in the background. When devices are discovered, you get a callback of the deviceDiscovered method for each of them, and when the discovery process has completed, you get a callback of the inquiryCompleted method. So you need to move the accessing of the vecDevices member and the form manipulation from startApp to inquiryCompleted to be able to actually show the discovered information.
You say all devices are on - but also check if all devices are discoverable.
I've made this mistake before myself!
Lookup the method LocalDevice.setDiscoverable() if you want to toggle between modes programatically.

Resources