Packaging Blackberry OAuth app throwing error - blackberry

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

Related

Auto-provisioning device under an enrolment group does not work (java SDK)

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.

Sending a tweet from Blackberry -- working in simulator, but not working on device

I am working on Blackberry Twitter integration to tweet a message on twitter.
The app is working fine in simulator but giving exception when I am running it on a device.
Here is the exception I am getting every time I run the app on the device{
OAuth_IO_Exception
I have done some research and saw a solution to set the correct date time on device, but it still is not working.
Here is my code:
import com.kc.twitter.activity.TweetToFriend;
import com.twitterapime.rest.Credential;
import com.twitterapime.xauth.Token;
import com.twitterapime.xauth.ui.OAuthDialogListener;
import com.twitterapime.xauth.ui.OAuthDialogWrapper;
import net.rim.device.api.browser.field2.BrowserField;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.MainScreen;
public class TwitterScreen extends MainScreen {
private final String CONSUMER_KEY = "{redected}";
private final String CONSUMER_SECRET = "{redected}";
private final String CALLBACK_URL = "http://kingdomconnectng.net/redirect.php";
private LabelField _labelStutus;
public static OAuthDialogWrapper pageWrapper = null;
private ShowAuthBrowser showAuthBrowserScreen;
private String adminMessage;
public String adminMessages[];
boolean done=false;
Credential c ;
TweetToFriend tw;
public static StoreToken _tokenValue;
public static boolean isTweetPosted=false;
public static boolean isTweeterScreen =false ;
public TwitterScreen(final String adminMessage)
{
this.adminMessage=adminMessage;
isTweeterScreen = true ;
showAuthBrowserScreen = new ShowAuthBrowser();
_tokenValue = StoreToken.fetch();
/*if(_tokenValue.token.equalsIgnoreCase("nothing"))
{*/
showAuthBrowserScreen.doAuth(null);
UiApplication.getUiApplication().pushScreen(showAuthBrowserScreen);
/*}
else
{
final Token t = new Token(_tokenValue.token, _tokenValue.secret,
_tokenValue.userId, _tokenValue.username);
Credential c = new Credential(CONSUMER_KEY, CONSUMER_SECRET, t);
TweetToFriend tw=new TweetToFriend();
boolean done=tw.doTweet(adminMessage, c);
if(done==true){
Dialog.alert("Tweet posted.");
UiApplication.getUiApplication().invokeLater(new Runnable(){
public void run(){
UiApplication.getUiApplication().popScreen();
}
});
isTweetPosted=true;
}
else{
Dialog.alert("Tweet not posted.");
UiApplication.getUiApplication().invokeLater(new Runnable(){
public void run(){
UiApplication.getUiApplication().popScreen();
}
});
isTweetPosted=true;
}
}*/
}
class ShowAuthBrowser extends MainScreen implements OAuthDialogListener
{
BrowserField b = new BrowserField();
public ShowAuthBrowser()
{
//if(isTweetPosted==false){
UiApplication.getUiApplication().invokeLater(new Runnable(){
public void run(){
UiApplication.getUiApplication().popScreen();
}
});
//}
_labelStutus = new LabelField("KingdomConnect App" );
//add(_labelStutus );
add(b);
pageWrapper = new BrowserFieldOAuthDialogWrapper(b,CONSUMER_KEY,CONSUMER_SECRET,CALLBACK_URL,this);
pageWrapper.setOAuthListener(this);
}
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 loggin Twitter: " + e.getMessage();
Dialog.alert( message );
}
}
public void onAccessDenied(String response ) {
System.out.println("Access denied! -> " + response );
updateScreenLog( "Acceso denegado! -> " + response );
}
public void onAuthorize(final Token token) {
UiApplication.getUiApplication().invokeLater(new Runnable(){
public void run(){
UiApplication.getUiApplication().popScreen();
}
});
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() {
try{
deleteAll();
c = new Credential(CONSUMER_KEY, CONSUMER_SECRET, myToken);
tw = new TweetToFriend();
/*done=tw.doTweet("KingdomConnect App: "+adminMessage, c);
if(done == true)
{
Dialog.alert( "Buzz posted successfully." );
close();
}
*/
prepareMessage(adminMessage);
}catch(NullPointerException e){
}catch(Exception e){
}
}
});
}
public void onFail(String arg0, String arg1) {
updateScreenLog("Error authenticating user! -> " + arg0 + ", " + arg1);
}
}
//TWEET METHOD
public void tweet(String message){
done=tw.doTweet("KingdomConnect: "+message, c);
/*if(done == true){
Dialog.alert( "Shared successfully." );
close();
} */
}
//PREPARE MESSAGE TO TWEET
public void prepareMessage(String msg){
int charLimit = 120;
int _msgSize = msg.length();
int i=0;
int parts = _msgSize/124;
try {
if(_msgSize > charLimit){
int temp1=0,temp2=charLimit;
while(i<parts+1){
String data = null;
if(i==parts){
data = msg.substring(temp1, _msgSize);
}else{
data = msg.substring(temp1, temp2);
temp1=temp2;
temp2=temp2+charLimit;
}
i++;
tweet(data);
}
Dialog.alert( "Shared successfully." );
}else{
tweet(msg);
//System.out.println("Data:======================"+msg);
}
}catch (Exception e) {
System.out.println("e = "+e);
}
}
private void updateScreenLog( final String message )
{
UiApplication.getUiApplication().invokeLater( new Runnable() {
public void run() {
_labelStutus.setText( message );
}
});
}
}

BrowserField and lost connection

I have an app that uses a browserfield to connect to a web-page.
All is working ok and the simulator shows the right page.
If I set the simulator Network Properties to "Out of Coverage" and click on a link in my web-page then I get an exception - in the BrowserFieldConnectionManagerImpl
How can catch this exception so I can take appropriate action?
The app is using BlackBerry SDK
The code is here:
public final class example_Screen extends MainScreen {
// Create the ErrorHandler class
public class MyBrowserFieldErrorHandler extends BrowserFieldErrorHandler {
protected MyBrowserFieldErrorHandler(BrowserField browserField){
super(browserField);
}
public void displayContentError(String url, String errorMessage) {
System.out.println("JERRY: displayContentError" + url);
System.out.println("JERRY: displayContentError" + errorMessage);
}
public void displayContentError(String url, InputConnection connection, Throwable t) {
displayContentError(url, t.getMessage());
}
public void navigationRequestError(BrowserFieldRequest request, Throwable t) {
displayContentError(request.getURL(), t.getMessage());
}
public void requestContentError(BrowserFieldRequest request, Throwable t) {
displayContentError(request.getURL(), t.getMessage());
}
public InputConnection resourceRequestError(BrowserFieldRequest request, Throwable t) {
displayContentError(request.getURL(), t.getMessage());
InputConnection connection = null;
return connection;
}
}
/**
* Creates a new example_Screen object
*/
public example_Screen() {
GIFEncodedImage ourAnimation = (GIFEncodedImage) GIFEncodedImage.getEncodedImageResource("2.gif");
AnimatedGIFField _ourAnimation = new AnimatedGIFField(ourAnimation, Field.FIELD_HCENTER + Field.FIELD_VCENTER);
this.add(_ourAnimation);
LabelField _ourLabelField = new LabelField("Updating ...", Field.FIELD_HCENTER + Field.FIELD_VCENTER);
this.add(_ourLabelField);
int anim_ht = _ourAnimation.getPreferredHeight();
int label_ht = _ourLabelField.getPreferredHeight();
EncodedImage ei = EncodedImage.getEncodedImageResource("img/menu.png");
int currentWidthFixed32 = Fixed32.toFP(ei.getWidth());
int currentHeightFixed32 = Fixed32.toFP(ei.getHeight());
int displayWidthFixed32 = Fixed32.toFP(Display.getWidth());
int displayHeightFixed32 = Fixed32.toFP((Display.getHeight() - anim_ht - label_ht));
int scaleXFixed32 = Fixed32.div(currentWidthFixed32, displayWidthFixed32);
int scaleYFixed32 = Fixed32.div(currentHeightFixed32, displayHeightFixed32);
ei = ei.scaleImage32(scaleXFixed32, scaleYFixed32);
BitmapField bmp = new BitmapField(ei.getBitmap(), Field.FIELD_HCENTER + Field.FIELD_VCENTER);
add(bmp);
BrowserFieldConfig myBrowserFieldConfig = new BrowserFieldConfig();
myBrowserFieldConfig.setProperty(BrowserFieldConfig.NAVIGATION_MODE, BrowserFieldConfig.NAVIGATION_MODE_POINTER);
BrowserField browserField = new BrowserField(myBrowserFieldConfig);
add(browserField);
browserField.requestContent("http://www.bbc.co.uk");
BrowserFieldListener listener = new BrowserFieldListener() {
public void documentAborted(BrowserField browserField, Document document) {
System.out.println("JERRY: documentAborted");
}
public void documentCreated(BrowserField browserField, ScriptEngine scriptEngine, Document document) {
System.out.println("JERRY: documentCreated");
}
public void documentError(BrowserField browserField, Document document) {
System.out.println("JERRY: documentError");
}
public void documentLoaded(BrowserField browserField, Document document) {
System.out.println("JERRY: documentLoaded");
Node node = document.getFirstChild();
String nodeText = node.getTextContent();
int index = -1;
if (nodeText != null) {
String errorText = "Error requesting content for:";
index = nodeText.indexOf(errorText);
}
Screen screen = browserField.getScreen();
try {
synchronized (Application.getEventLock()) {
if (index == -1) {
System.out.println("JERRY: documentLoaded: no error");
int count = screen.getFieldCount();
if (count > 1) {
screen.deleteRange(0, (count-1));
System.out.println("JERRY: documentLoaded: " + (count-1) + " fields deleted");
} else {
System.out.println("JERRY: documentLoaded: only 1 field so none deleted");
}
} else {
System.out.println("JERRY: documentLoaded: error");
}
}
} catch (final Exception ex) {
System.out.println("example_Screen: documentLoaded: exception caught: " + ex.toString());
}
}
public void documentUnloading(BrowserField browserField, Document document) {
System.out.println("JERRY: documentUnloading");
}
public void downloadProgress(BrowserField browserField, ContentReadEvent event) {
System.out.println("JERRY: downloadProgress");
}
};
browserField.addListener(listener);
// Attach the Error Handler to the BrowserField
BrowserFieldErrorHandler eHandler = new MyBrowserFieldErrorHandler(browserField);
browserField.getConfig().setProperty(BrowserFieldConfig.ERROR_HANDLER, eHandler);
}
}
BrowserField contains a method, addListener() which takes a reference to BrowserFieldListener implementation.
Extend BrowserFieldListener and process errors in methods documentError() and documentAborted() of this implementation.
Then add a reference of your class instance that extends BrowserFieldListener to your browser field via browserField.addListener(browserFieldListener);.
EDIT:
If this does not work, then use BrowserFieldErrorHandler class from RIM API. Build your own error handler and pass its instance to the browserfield configuration.
Below, there's sample code:
// Create the ErrorHandler class
public class MyBrowserFieldErrorHandler extends BrowserFieldErrorHandler {
public void displayContentError(String url, String errorMessage) {
String error = "Error: (url=" + url + "): " + t.getMessage();
Dialog.ask(Dialog.D_OK, error);
logMessage(“BrowserFieldError: “ + error );
}
public void displayContentError(String url, InputConnection connection, Throwable t) {
displayContentError(url, t.getMessage());
}
public void requestContentError(BrowserFieldRequest request, Throwable t){
displayContentError(request.getURL(), t.getMessage());
}
}
// Attach the Error Handler to the BrowserField
BrowserFieldErrorHandler eHandler = new MyBrowserFieldErrorHandler();
browserField.getConfig().setProperty(BrowserFieldConfig.ERROR_HANDLER,eHandler);
I get this sample code from DevCon2010 presentation of BrowserField capabilities. You can get it here: http://dev.tuyennguyen.ca/wp-content/uploads/2011/02/DEV49.pdf

Please wait screen appearing after the login button

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);
}
}
}

Stuck up with MessageList in Blackberry

I am try to do MessageList in blackberry using midlet, but whatever I do some expection comes up. Right now am getting NullPointerException. Here is the code
EncodedImage indicatorIcon = EncodedImage.getEncodedImageResource("img/indicator.png");
ApplicationIcon applicationIcon = new ApplicationIcon(indicatorIcon);
ApplicationIndicatorRegistry.getInstance().register(applicationIcon, false, false);
ApplicationMessageFolderRegistry reg = ApplicationMessageFolderRegistry.getInstance();
MessageListStore messageStore = MessageListStore.getInstance();
if(reg.getApplicationFolder(INBOX_FOLDER_ID) == null)
{
ApplicationDescriptor daemonDescr = ApplicationDescriptor.currentApplicationDescriptor();
String APPLICATION_NAME = "TestAPP";
ApplicationDescriptor mainDescr = new ApplicationDescriptor(daemonDescr, APPLICATION_NAME, new String[] {});
ApplicationFolderIntegrationConfig inboxIntegration = new ApplicationFolderIntegrationConfig(true, true, mainDescr);
ApplicationFolderIntegrationConfig deletedIntegration = new ApplicationFolderIntegrationConfig(false);
ApplicationMessageFolder inbox = reg.registerFolder(MyApp.INBOX_FOLDER_ID, "Inbox", messageStore.getInboxMessages(),
inboxIntegration);
ApplicationMessageFolder deleted = reg.registerFolder(MyApp.DELETED_FOLDER_ID, "Deleted Messages", messageStore.getDeletedMessages(), deletedIntegration);
messageStore.setFolders(inbox, deleted);
}
DemoMessage message = new DemoMessage();
String name = "John";
message.setSender(name);
message.setSubject("Hello from " + name);
message.setMessage("Hello Chris. This is " + name + ". How are you? Hope to see you at the conference!");
message.setReceivedTime(System.currentTimeMillis());
messageStore.addInboxMessage(message);
messageStore.getInboxFolder().fireElementAdded(message);
Can someone suggest me a simple MessageList sample for midlet to just show a String in MessageList and custom ApplicationIndicator value. If possible OnClick of message bring back the midlet from background.
use the following code:
static class OpenContextMenu extends ApplicationMenuItem {
public OpenContextMenu( int order ) {
super( order );
}
public Object run( Object context ) {
if( context instanceof NewMessage ) {
try {
NewMessage message = (NewMessage) context;
if( message.isNew() ) {
message.markRead();
ApplicationMessageFolderRegistry reg = ApplicationMessageFolderRegistry.getInstance();
ApplicationMessageFolder folder = reg.getApplicationFolder( Mes
sageList.INBOX_FOLDER_ID );
folder.fireElementUpdated( message, message );
//changeIndicator(-1);
}
Inbox inbox = message.getInbox();
Template template = inbox.getTemplate();
//Launch the mainscreen
UiApplication.getUiApplication().requestForeground();
}
catch (Exception ex) {
Dialog.alert();
}
}
return context;
}
public String toString() {
return "Name of the menu item";
}
}

Resources