On testing my application in Simulator, my app runs perfectly. But on the real device i get Null for BasicEditField, so I'm not able to execute my application. Following is my code snippet.
public class Login extends MainScreen {
private UiApplication application = UiApplication.getUiApplication();
private BasicEditField _email = null;
private PasswordEditField _pwd = null;
private ButtonField login = null;
String imei = GPRSInfo.imeiToString(GPRSInfo.getIMEI(), false);
public Login(){
try {
_email = new BasicEditField("Email: ", "", 100, EditField.NO_NEWLINE);
_email.setFont(font);
add(_email);
_pwd = new PasswordEditField("Password: ", "", 100, EditField.NO_NEWLINE);
_pwd.setFont(font);
add(_pwd);
login = new ButtonField("Login", ButtonField.CONSUME_CLICK);
login.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
String e = _email.getText();
String xmlUrl = "http://********:9090/com.infra.rest/rest/todo?email='"+ e +"'&dId='"+ imei +"';deviceside=true";
String[][] urlData = XmlFunctions.getUserFromXml(xmlUrl);
}
});
login.setFont(font);
add(login);
} catch (Exception e) {
System.out.println("Failed to create user interface components");
}
}
}
On inspecting the email and imei values i get NULL and an exception saying Method "toString" with signature "()Ljava/lang/String;" is not applicable on this object
It has been a whole day but i'm not able to overcome this problem.
I suspect it has something to do with accessing non-static outer class fields from an anonymous inner class. Try:
String e = Login.this._email.getText();
Have a read through this wikipedia page.
Related
I've performed this example
https://learn.microsoft.com/en-us/azure/iot-dps/quick-enroll-device-x509-java
It does not appear under "registration records" under the enrolment group but it throws this error:
PROVISIONING_DEVICE_STATUS_FAILED, Exception: com.microsoft.azure.sdk.iot.provisioning.device.internal.exceptions.ProvisioningDeviceHubException: Signing certificate info did not match chain elements
Registration:
public class DeviceRegistration {
String idScope;
String globalEndpoint;
String clientCert;
String clientCertPrivateKey;
String signerCert;
public DeviceRegistration(String idScope, String globalEndpoint, String clientCert, String clientCertPrivateKey, String signerCert) {
this.idScope = idScope;
this.globalEndpoint = globalEndpoint;
this.clientCert = clientCert;
this.clientCertPrivateKey = clientCertPrivateKey;
this.signerCert = signerCert;
}
public void register(ProvisioningDeviceClientRegistrationCallback callback) throws Exception {
Collection<String> signerCertificates = new LinkedList<>();
signerCertificates.add(signerCert);
ProvisioningDeviceClient provisioningDeviceClient = null;
SecurityProvider securityProviderX509 = new SecurityProviderX509Cert(clientCert, clientCertPrivateKey, signerCertificates);
provisioningDeviceClient = ProvisioningDeviceClient.create(globalEndpoint, idScope, ProvisioningDeviceClientTransportProtocol.HTTPS,
securityProviderX509);
provisioningDeviceClient.registerDevice(callback, this);
}
private static String loadFile(String filename) throws Exception {
File f = new File(filename);
if (!f.exists())
throw new Exception("File not found: " + filename);
BufferedReader reader = new BufferedReader(new FileReader(f));
char[] buffer = new char[(int) f.length()];
reader.read(buffer);
reader.close();
return new String(buffer);
}
public static void main(String[] args){
try {
CountDownLatch countDownLatch = new CountDownLatch(1);
DeviceRegistration deviceRegistration = new DeviceRegistration(args[0], args[1], loadFile(args[2]), loadFile(args[3]), loadFile(args[4]));
deviceRegistration.register(new ProvisioningDeviceClientRegistrationCallback() {
#Override
public void run(ProvisioningDeviceClientRegistrationResult provisioningDeviceClientRegistrationResult, Exception e, Object context) {
if (provisioningDeviceClientRegistrationResult.getProvisioningDeviceClientStatus() == ProvisioningDeviceClientStatus.PROVISIONING_DEVICE_STATUS_ASSIGNED) {
System.out.println("IotHUb Uri : " + provisioningDeviceClientRegistrationResult.getIothubUri());
System.out.println("Device ID : " + provisioningDeviceClientRegistrationResult.getDeviceId());
countDownLatch.countDown();
} else {
System.out.println("Result: "+provisioningDeviceClientRegistrationResult.getProvisioningDeviceClientStatus()+", Exception: "+e);
}
}
});
countDownLatch.await();
} catch (Exception e) {
e.printStackTrace();
}
}}
Delete the individual enrollment and make sure that you've gone through the verification of your X.509 signing cert (in the Certificates tab in the Azure portal). If you have both an enrollment group and an individual enrollment for a device, the individual enrollment takes precedence.
I experienced the following problem with PopupViews: My application has an error handler set in the UI and this error handler shows some error notification by invoking Notification.show(...) when it receives error event. In a popup view I have a button, which performs some action. When one clicks the button, the popup view is closed (by invoking setPopupVisible(false)) and the action is executed. However, if the action fails to run and throws an exception, I expect the exception to be handled by the UI and the error message is to be shown on the screen. Unfortunately, the handler receives the error event and invokes Notification.show, but no message is shown.
Has someone faced the similar issue?
You can use other notification system and run async JavaScript code.
Also you can wrap any other notification system in 10 minutes (implement Vaadin AbstractJavaScriptComponent), for example noty2 (for use should be included jQuery lib): http://needim.github.io/noty/
and show notif when you action executed like this:
new Notty("WARNING<br>description... (static)", Notty.Type.WARNING).show(UI.getCurrent());
new Notty("WARNING<br>description... (close in 3000ms)", Notty.Type.WARNING, 3000).show(UI.getCurrent());
new Notty("WARNING<br>description... (modal)", Notty.Type.WARNING, 0, true).show(UI.getCurrent());
new Notty("WARNING<br>description... (modal force, close in 3000ms)", Notty.Type.WARNING, 3000, true, true).show(UI.getCurrent());
new Notty("asd", Notty.Type.ERROR, 5000).show(UI.getCurrent());
package user_interface.util.ext;
import com.vaadin.annotations.JavaScript;
import com.vaadin.ui.AbstractJavaScriptComponent;
import com.vaadin.ui.AbstractOrderedLayout;
import com.vaadin.ui.UI;
import java.io.Serializable;
import java.util.Iterator;
public class Notty implements Serializable {
private String message;
private String type;
private int closeIn = 0;
private boolean force = false;
private boolean modal = false;
public Notty(String message, Notty.Type type) {
this.message = message;
this.type = type.value;
}
public Notty(String message, Notty.Type type, int closeIn) {
this.message = message;
this.type = type.value;
this.closeIn = closeIn;
}
public Notty(String message, Notty.Type type, int closeIn, boolean modal) {
this.message = message;
this.type = type.value;
this.closeIn = closeIn;
this.modal = modal;
}
public Notty(String message, Notty.Type type, int closeIn, boolean modal, boolean force) {
this.message = message;
this.type = type.value;
this.closeIn = closeIn;
this.modal = modal;
this.force = force;
}
public void show(UI ui) {
AbstractOrderedLayout aol = (AbstractOrderedLayout) ui.getContent();
NottyMessage nm = null;
boolean wasAdded = false;
Iterator itr = aol.iterator();
while(itr.hasNext()) {
Object o = itr.next();
if (o instanceof NottyMessage) {
nm = (NottyMessage) o;
wasAdded = true;
}
}
if (!wasAdded) {
nm = new NottyMessage();
aol.addComponent(nm);
}
nm.show(message, type, closeIn, force, modal);
}
#JavaScript({"NottyMessage.js"})
private class NottyMessage extends AbstractJavaScriptComponent {
public NottyMessage() {
setImmediate(true);
}
#Override
protected NottyMessageState getState() {
return (NottyMessageState) super.getState();
}
private void show(String mess, String type, int closeIn, boolean force, boolean modal) {
callFunction("show", mess, type, closeIn, force, modal);
}
}
public static enum Type {
ALERT("alert"),
INFORMATION("information"),
ERROR("error"),
WARNING("warning"),
NOTIFICATION("notification"),
SUCCESS("success");
private String value;
private Type(String val) {
this.value = val;
}
}
}
NottyMessageState.java
package user_interface.util.ext;
import com.vaadin.shared.ui.JavaScriptComponentState;
public class NottyMessageState extends JavaScriptComponentState {
public String xhtml;
public String type;
}
NottyMessage.js
user_interface_util_ext_Notty_NottyMessage = function() {
var e = this.getElement();
this.onStateChange = function() {
// change state callb
}
this.show = function(message, messageType, closeInMs, isForce, isModal) {
var n = noty({
text: message,
type: messageType,
dismissQueue: true,
timeout: closeInMs,
force: isForce,
modal: isModal,
maxVisible: 7,
layout: "bottomLeft",
theme: "defaultTheme"
});
}
}
it should look like this:
Maybe the handler is in a different thread and not in the UI thread. I got the same weird behavoir trying to enable a disabled button which did not worked until i used
Button button = new Button("foo")
// ...
getUI().access(new Runnable(){
public void run() {
button.setEnabled(true)
}
})
I am trying to implement a "Wait Screen" in my BlackBerry app. The screen is to appear when the user clicks "Login" and it should go away after login has successfully been made. I am calling the screen in the "Login" listener after which I call a methd to fetch data from webs ervice. When the data is fetched, and the new screen is shown, the "Wait Screen" should disappear. However, on clicking login I get Uncaught - RuntimeException after which new screen is displayed with the "Waiting Screen" on top of it. Can somebody help me with this?
public class MessageScreen extends PopupScreen
{
private String message;
public MessageScreen (String message)
{
super( new HorizontalFieldManager(), Field.NON_FOCUSABLE);
this.message = message;
final BitmapField logo = new BitmapField(Bitmap.getBitmapResource( "cycle.gif"));
logo.setSpace( 5, 5 );
add(logo);
RichTextField rtf = new RichTextField(message, Field.FIELD_VCENTER | Field.NON_FOCUSABLE | Field.FIELD_HCENTER);
rtf.setEditable( false );
add(rtf);
}
}
I am calling this in the "Login" click event - button listener.
public void fieldChanged(Field field, int context)
{
// Push appropriate screen depending on which button was clicked
String uname = username.getText();
String pwd = passwd.getText();
if (uname.length() == 0 || pwd.length()==0) {
Dialog.alert("One of the textfield is empty!");
} else {
C0NNECTION_EXTENSION=checkInternetConnection();
if(C0NNECTION_EXTENSION==null)
{
Dialog.alert("Check internet connection and try again");
}
else
{
UiApplication.getUiApplication().invokeLater( new Runnable()
{
public void run ()
{
UiApplication.getUiApplication().pushScreen( new MessageScreen("Signing in...") );
}
} );
doLogin(uname, pwd);
}
}
}
private String doLogin(String user_id, String password)
{
String URL ="";
String METHOD_NAME = "ValidateCredentials";
String NAMESPACE = "http://tempuri.org/";
String SOAP_ACTION = NAMESPACE+METHOD_NAME;
SoapObject resultRequestSOAP = null;
HttpConnection httpConn = null;
HttpTransport httpt;
SoapPrimitive response = null;
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("username", user_id);
request.addProperty("password", password);
System.out.println("The request is=======" + request.toString());
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
httpt = new HttpTransport(URL+C0NNECTION_EXTENSION);
httpt.debug = true;
try
{
httpt.call(SOAP_ACTION, envelope);
response = (SoapPrimitive) envelope.getResponse();
String result = response.toString();
resultRequestSOAP = (SoapObject) envelope.bodyIn;
String[] listResult = split(result, sep);
strResult = listResult[0].toString();
strsessionFirstName = listResult[1].toString();
strsessionLastName = listResult[2].toString();
strsessionPictureUrl = MAINURL + listResult[3].substring(2);
strsessionStatusId = listResult[4].toString();
strsessionStatusMessage = listResult[5].toString();
strsessionLastUpdateTst = listResult[6].toString();
if(strResult.equals("credentialaccepted"))
{
if(checkBox1.getChecked() == true)
{
persistentHashtable.put("username", user_id);
persistentHashtable.put("password", password);
}
Bitmap bitmap = getLiveImage(strsessionPictureUrl, 140, 140);
StatusActivity nextScreen = new StatusActivity();
nextScreen.getUsername(user_id);
nextScreen.getPassword(password);
nextScreen.setPictureUrl(bitmap);
nextScreen.setImage(strsessionPictureUrl);
nextScreen.setFirstName(strsessionFirstName, strsessionLastName, strsessionLastUpdateTst, strsessionStatusMessage);
UiApplication.getUiApplication().pushScreen(nextScreen);
UiApplication.getUiApplication().invokeLater( new Runnable()
{
public void run ()
{
UiApplication.getUiApplication().pushScreen( UiApplication.getUiApplication().getActiveScreen() );
}
} );
}
if(strResult.equals("credentialdenied"))
{
Dialog.alert("Invalid login details.");
UiApplication.getUiApplication().pushScreen(new LoginTestScreen() );
}
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("The exception is IO==" + e.getMessage());
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
System.out.println("The exception xml parser example==="
+ e.getMessage());
}
System.out.println( resultRequestSOAP);
//UiApplication.getUiApplication().pushScreen( UiApplication.getUiApplication().getActiveScreen() );
return response + "";
//UiApplication.getUiApplication().pushScreen(new InfoScreen());
//Open a new Screen
}
Like Eugen said, you should run doLogin() on a background Thread:
final String uname = username.getText();
final String pwd = passwd.getText();
Thread backgroundWorker = new Thread(new Runnable() {
public void run() {
doLogin(uname, pwd);
}
});
backgroundWorker.start();
If you do that, you'll need to use UiApplication.invokeLater() (or another similar technique) to show your screens (back on the main/UI thread). You can't leave the doLogin() method exactly as it originally was, because it makes calls to change the UI. For example, you have a couple calls to directly use pushScreen(), which should not be called (directly) from the background.
This is not ok (from the background):
UiApplication.getUiApplication().pushScreen(nextScreen);
But, this is:
UiApplication.getUiApplication().invokeLater( new Runnable()
{
public void run ()
{
UiApplication.getUiApplication().pushScreen(nextScreen);
}
} );
But, also, what is this code supposed to do? :
UiApplication.getUiApplication().pushScreen(nextScreen);
UiApplication.getUiApplication().invokeLater( new Runnable()
{
public void run ()
{
UiApplication.getUiApplication().pushScreen( UiApplication.getUiApplication().getActiveScreen() );
}
} );
This doesn't make sense to me. What are you trying to do with those lines of code?
I see only one issue so far - networking in the UI thread. Please put all your networ operations into another Thread.run().
You could also get more detailed error description by:
1) Navigate to home screen
2) Hold alt button and press LGLG on the keyboard
3) Explore showed event log for specific error
try this -
public void fieldChanged(Field field, int context)
{
// Push appropriate screen depending on which button was clicked
String uname = username.getText();
String pwd = passwd.getText();
if (uname.length() == 0 || pwd.length()==0) {
Dialog.alert("One of the textfield is empty!");
} else {
C0NNECTION_EXTENSION=checkInternetConnection();
if(C0NNECTION_EXTENSION==null)
{
Dialog.alert("Check internet connection and try again");
}
else
{
Dialog busyDialog = new Dialog("Signing in...", null, null, 0, Bitmap.getPredefinedBitmap(Bitmap.HOURGLASS));
busyDialog.setEscapeEnabled(false);
synchronized (Application.getEventLock()) {
busyDialog.show();
}
doLogin(uname, pwd);
}
}
}
I have a web service that accepts a username and password and if the login credentials are correct, it returns the user's name, status, image and last known gps coordinates.
As for now I am stuck in the "login" button where the application neither proceeds nor throws any error. Simulator produces no result and I am unable to load the app on to my handset.
package mypackage;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.rmi.RemoteException;
import java.util.Hashtable;
import javacard.framework.UserException;
import javax.microedition.io.HttpConnection;
import javax.microedition.location.Location;
import javax.microedition.location.LocationProvider;
import org.kobjects.base64.Base64;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransport;
import org.xmlpull.v1.XmlPullParserException;
import net.rim.device.api.system.*;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.component.pane.TitleView;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.ui.image.Image;
public class LoginTest extends UiApplication
{
public static void main(String[] args)
{
//Create a new instance of the app
//and start the app on the event thread.
LoginTest app = new LoginTest();
app.enterEventDispatcher();
}
public LoginTest()
{
//Display a new screen.
pushScreen(new LoginTestScreen());
}
}
//Create a new screen that extends MainScreen and provides
//behaviour similar to that of other apps.
final class LoginTestScreen extends MainScreen
{
//declare variables for later use
private InfoScreen _infoScreen;
private ObjectChoiceField choiceField;
private int select;
BasicEditField username;
PasswordEditField passwd;
CheckboxField checkBox1;
ButtonField loginBtn;
Hashtable persistentHashtable;
PersistentObject persistentObject;
static final long KEY = 0x9df9f961bc6d6baL;
// private static final String URL="http://prerel.track24elms.com/Android/T24AndroidLogin.asmx";
String strResult;
public LoginTestScreen()
{
//Invoke the MainScreen constructor.
super();
//Add a screen title.
setTitle("Track24ELMS");
LabelField login = new LabelField("ELMS Login", LabelField.FIELD_HCENTER);
login.setFont(Font.getDefault().derive(Font.BOLD, 30));
login.setMargin(10, 0, 20, 0); //To leave some space from top and bottom
HorizontalFieldManager user = new HorizontalFieldManager();
user.setMargin(0, 0, 10, 0);
HorizontalFieldManager pass = new HorizontalFieldManager();
pass.setMargin(0, 0, 20, 0);
HorizontalFieldManager checkbox = new HorizontalFieldManager();
checkbox.setMargin(0, 0, 30, 0);
HorizontalFieldManager btns = new HorizontalFieldManager(HorizontalFieldManager.FIELD_HCENTER);
LabelField usernameTxt = new LabelField("Username :");
LabelField passwordTxt = new LabelField("Password :");
username = new BasicEditField();
passwd = new PasswordEditField();
loginBtn = new ButtonField("Login", ButtonField.CONSUME_CLICK);
// btn.setChangeListener(new view listener);
//checkBox1 = new CheckboxField("Remember me", false,Field.FOCUSABLE);
checkBox1 = new CheckboxField("Remember me",false);
user.add(usernameTxt);
user.add(username);
pass.add(passwordTxt);
pass.add(passwd);
//checkbox.add(checkBox1);
btns.add(loginBtn);
add(login);
add(user);
add(pass);
add(checkBox1);
add(btns);
// loginBtn.setChangeListener(btnlistener);
}
public void saveChecked() {
persistentHashtable.put("", username.getText());
persistentHashtable.put("", passwd.getText());
persistentHashtable.put("BoolData", new Boolean(checkBox1.getChecked()));
persistentObject.commit();
}
FieldChangeListener btnlistener = new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
//Open a new screen
String uname = username.getText();
String pwd = passwd.getText();
//If there is no input
if (uname.length() == 0 || pwd.length()==0) {
Dialog.alert("One of the textfield is empty!");
} else {
final String METHOD_NAME = "ValidateCredentials";
final String NAMESPACE = "http://tempuri.org/";
final String SOAP_ACTION = NAMESPACE + METHOD_NAME;
final String URL = "http://prerel.track24elms.com/Android/T24AndroidLogin.asmx";
SoapObject resultRequestSOAP = null;
HttpConnection httpConn = null;
HttpTransport httpt;
System.out.println("The username" + uname + "password" + pwd );
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
//String usernamecode = Base64.encode(username.getBytes());
//String pwdEncodeString = Base64.encode(passwd.getBytes());
request.addProperty("Username", "abc");//First parameter is tag name provided by web service
request.addProperty("Password", "xyz");
System.out.println("The request is=======" + request.toString());
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut = request;
envelope.dotNet = true;
envelope.encodingStyle = SoapSerializationEnvelope.XSD;
envelope.setOutputSoapObject(request);
System.out.println("The envelope has the value++++"+ envelope.toString());
/* URL+ Here you can add paramter so that you can run on device,simulator etc. this will work only for wifi */
httpt = new HttpTransport(URL+ ";deviceside=true;ConnectionUID=S TCP-WiFi");
httpt.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
httpt.debug = true;
try
{
System.out.println("SOAP_ACTION == " + SOAP_ACTION);
httpt.call(SOAP_ACTION, envelope);
System.out.println("the tranport" + httpt.toString());
resultRequestSOAP = (SoapObject) envelope.bodyIn;
System.out.println("result == " + resultRequestSOAP);
}
catch (IOException e) {
System.out.println("The exception is IO==" + e.getMessage());
} catch (XmlPullParserException e) {
System.out.println("The exception xml parser example==="
+ e.getMessage());
}
System.out.println( resultRequestSOAP);
UiApplication.getUiApplication().pushScreen(new InfoScreen()); //Open a new Screen
}
}
};
//To display a dialog box when a BlackBerry device user
//closes the app, override the onClose() method.
public boolean onClose()
{
if(checkBox1.equals("true"))
{
persistentObject = PersistentStore.getPersistentObject(KEY);
if (persistentObject.getContents() == null) {
persistentHashtable = new Hashtable();
persistentObject.setContents(persistentHashtable);
}
else {
persistentHashtable = (Hashtable)persistentObject.getContents();
}
if (persistentHashtable.containsKey("EditData")) {
username.setText((String)persistentHashtable.get("EditData"));
}
if (persistentHashtable.containsKey("BoolData")) {
Boolean booleanObject = (Boolean)persistentHashtable.get("BoolData");
checkBox1.setChecked(booleanObject.booleanValue());
if(booleanObject.booleanValue()==true){
saveChecked();
}
}
}
Dialog.alert("Goodbye!");
System.exit(0);
return true;
}
//Create a menu item for BlackBerry device users to click to see more
//information about the city they select.
private MenuItem _viewItem = new MenuItem("More Info", 110, 10)
{
public void run()
{
//Store the index of the city the BlackBerry device user selects
select = choiceField.getSelectedIndex();
//Display a new screen with information about the
//city the BlackBerry device user selects
_infoScreen = new InfoScreen();
UiApplication.getUiApplication().pushScreen(_infoScreen);
}
};
//Create a menu item for BlackBerry device users to click to close
//the app.
private MenuItem _closeItem = new MenuItem("Close", 200000, 10)
{
public void run()
{
onClose();
}
};
//To add menu items to the menu of the app,
//override the makeMenu method.
//Create an inner class for a new screen that displays
//information about the city a BlackBerry device user selects.
private class InfoScreen extends MainScreen
{
public InfoScreen()
{
super();
setTitle("Itinerary");
LabelField login = new LabelField("Employee Itinerary", LabelField.FIELD_HCENTER);
Bitmap bitmap = Bitmap.getBitmapResource("img1.jpg");
EditField statusMsg = new EditField("Status Message", "Update status here");
}
}
}
In the code you posted, nothing is ever setup to respond to your login button being pressed.
First of all, let's remove this anonymous class that implements FieldChangeListener:
FieldChangeListener btnlistener = new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
and make it like this:
private class LoginButtonListener implements FieldChangeListener {
public void fieldChanged(Field field, int context) {
// no change to the content of this method!
}
}
and in the constructor for LoginTestScreen, instantiate it, and hook it up to the login button:
loginBtn = new ButtonField("Login", ButtonField.CONSUME_CLICK);
loginBtn.setChangeListener(new LoginButtonListener());
it looks like you were close, in the commented out code. Just needed a little more. Try that, and report back!
Note: you could make it work with the anonymous button listener class you originally had. I just don't like the readability of anonymous classes when they get that big, especially since your btnListener member was declared in a totally different place than all your other ones. The real missing piece was the call to setChangeListener. I just wanted to differentiate what I'm recommending, from what's needed.
I am creating an application that will post a link onto Twitter. The following code refuses to package up for me, throwing the following error:
Error: Cannot run program "jar": CreateProcess error=2, The system cannot find the file specified
Here is the code:
public class ShowAuthBrowser extends MainScreen implements OAuthDialogListener
{
private final String CONSUMER_KEY = "<Consumer>";
private final String CONSUMER_SECRET = "<Secret>";
private LabelField _labelStutus;
private OAuthDialogWrapper pageWrapper = null;
public StoreToken _tokenValue;
public BrowserField b = new BrowserField();
Manager _authManager;
Manager _pinManager;
ButtonField authButton;
TextField authPin;
public ShowAuthBrowser()
{
_authManager = new VerticalFieldManager(NO_VERTICAL_SCROLL |
NO_VERTICAL_SCROLLBAR);
_pinManager = new HorizontalFieldManager(NO_VERTICAL_SCROLL |
NO_VERTICAL_SCROLLBAR);
authButton = new ButtonField("OK");
authPin = new TextField(Field.EDITABLE);
_authManager.add(_labelStutus );
_authManager.add(b);
_pinManager.add(authButton);
_pinManager.add(authPin);
pageWrapper = new BrowserFieldOAuthDialogWrapper(b,CONSUMER_KEY,
CONSUMER_SECRET,null,this);
pageWrapper.setOAuthListener(this);
add(_pinManager);
add(_authManager);
authButton.setChangeListener( new FieldChangeListener( ) {
public void fieldChanged( Field field, int context ) {
if( field == authButton ) {
doAuth(authPin.getText());
}
}
} );
}
public void doAuth( String pin )
{
try
{
if ( pin == null )
{
pageWrapper.login();
}
else
{
this.deleteAll();
add(b);
pageWrapper.login( pin );
}
}
catch ( Exception e )
{
final String message = "Error logging into Twitter: " +
e.getMessage();
Dialog.alert( message );
}
}
public void onAccessDenied(String response ) {
updateScreenLog( "Access denied! -> " + response );
}
public void onAuthorize(final Token token) {
final Token myToken = token;
_tokenValue = StoreToken.fetch();
_tokenValue.token = myToken.getToken();
_tokenValue.secret = myToken.getSecret();
_tokenValue.userId = myToken.getUserId();
_tokenValue.username = myToken.getUsername();
_tokenValue.save();
UiApplication.getUiApplication().invokeLater( new Runnable() {
public void run() {
deleteAll();
Credential c = new Credential(CONSUMER_KEY,
CONSUMER_SECRET,
myToken);
PostTweet tw = new PostTweet();
String message="Testing BB App";
boolean done=false;
done=tw.doTweet(message, c);
if(done == true)
{
Dialog.alert( "Tweet succusfully..." );
close();
}
}
});
}
public void onFail(String arg0, String arg1) {
updateScreenLog("Error authenticating user! -> " + arg0 + ", " + arg1);
}
private void updateScreenLog( final String message )
{
UiApplication.getUiApplication().invokeLater( new Runnable() {
public void run() {
_labelStutus.setText( message );
}
});
}
}
The odd thing is, if I remove the following lines, it packages just fine:
authButton.setChangeListener( new FieldChangeListener( ) {
public void fieldChanged( Field field, int context ) {
if( field == authButton ) {
doAuth(authPin.getText());
}
}
} );
Any help would be appreciated as I really need the field listener attached to this screen.
With code like authButton.setChangeListener(null), it does package successfully however I do need code with FieldChangeListener to do something.
Make sure your java bin path is set in environment variable.
http://docs.oracle.com/javase/tutorial/essential/environment/paths.html
and take a look at the last 3 posts in the following website:
http://supportforums.blackberry.com/t5/Java-Development/I-O-Error-Cannot-run-program-quot-jar-quot-CreateProcess-error-2/td-p/522638
Also make sure The Java® software development kit (Java SDK/JDK) is installed on the computer, and a correct version of the Java SDK is used.
http://supportforums.blackberry.com/t5/Java-Development/I-O-Error-CreateProcess/ta-p/445949
As mentioned in Scott Boettger comment below, this post could be helpful as well:
http://supportforums.blackberry.com/t5/Java-Development/why-cause-more-then-100-compiled-classes-packaging-I-O-error/m-p/520282