In my application I have a log in Screen. When the user enter the correct user name and password I have to collect the information from the website and navigate to main Screen.
I tried following code. But this code is not working. How to achieve it?
public final class MyScreen extends MainScreen {
public MyScreen() {
BrowserFieldConfig myBrowserFieldConfig = new BrowserFieldConfig();
myBrowserFieldConfig.setProperty(BrowserFieldConfig.NAVIGATION_MODE,
BrowserFieldConfig.NAVIGATION_MODE_POINTER);
BrowserField browserField = new BrowserField(myBrowserFieldConfig);
BrowserFieldListener list = new BrowserFieldListener() {
public void documentLoaded(BrowserField browserField, Document document) throws Exception {
String url = document.getBaseURI();
String val = "http://demo.....";
//i am checking the correct url and i will navigate to main screen
if (url.equals(new String(val))) {
UiApplication.getUiApplication().pushScreen(new Main());//here i got IllegalStateException ..
}
System.out.println(" Login URL " + url);
//super.documentLoaded(browserField, document);
}
};
browserField.addListener(list);
add(browserField);
String URL = "http://demo.....";
if (DeviceInfo.isSimulator()) {
URL = URL + ";deviceSide=true";
}
browserField.requestContent(URL);
}
}
in place of
UiApplication.getUiApplication().pushScreen(new Main());
use
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
UiApplication.getUiApplication().pushScreen(new Main());
}
});
you need to do it under ui Thread.
Check it.
Related
I am trying to handle an event in BrowserField when the user actually clicks a link.
I studied BrowserFieldListener, tried its documentCreated() method but that gives me a response when the page starts loading. I want a trigger the moment user clicks a link inside browserField.
What am i missing here?
Override handleNavigationRequest() of ProtocolController like
ProtocolController controller = new ProtocolController(browserField) {
public void handleNavigationRequest(BrowserFieldRequest request) throws Exception {
/*
Here you get the redirection link using
request.getURL()
and do what you want to do
*/
// to display url in browserfield use
InputConnection inputConnection = handleResourceRequest(request);
browserField.displayContent(inputConnection, request.getURL());
}
};
browserField.getConfig().setProperty(BrowserFieldConfig.CONTROLLER, controller);
Use the following class that was I used
public class CacheProtocolController extends ProtocolController{
public CacheProtocolController() {
super(browserField);
}
/**
* Handle navigation requests (e.g., link clicks)
*/
public void handleNavigationRequest(final BrowserFieldRequest request) throws Exception {
UiApplication.getUiApplication().invokeAndWait(new Runnable() {
public void run() {
// TODO Auto-generated method stub
Logger.debug("*******URL*******",request.getURL() );
});
}
/**
* Handle resource request (e.g., images, external css/javascript resources)
*/
public InputConnection handleResourceRequest(BrowserFieldRequest request) throws Exception {
return super.handleResourceRequest(request);
}
}
I have solved this problem using the following class:
public class CacheProtocolController extends ProtocolController{
private SparseList sparseList = null;
private int imageIndex ;
private int click = 0;
private BrowserField browserField = null;
public CacheProtocolController(BrowserField browserField,SparseList sparseList,int imageIndex ) {
super(browserField);
this.sparseList = sparseList;
this.imageIndex = imageIndex;
}
/**
* Handle navigation requests (e.g., link clicks)
*/
public void handleNavigationRequest(final BrowserFieldRequest request) throws Exception {
UiApplication.getUiApplication().invokeAndWait(new Runnable() {
public void run() {
Logger.debug("*******URL*******",request.getURL() );
String requestUrl = null;
requestUrl = FileManipulations.replaceAll(request.getURL(), "file:///SDCard/BlackBerry/pictures/", "../");
Logger.debug("*******requestUrl*******",requestUrl );
Enumeration enumeration = sparseList.elements();
while (enumeration.hasMoreElements()) {
final News news = (News) enumeration.nextElement();
if(news.getDetailsURL().equalsIgnoreCase(requestUrl)){
if(click == 1){
click = 0;
UiApplication.getUiApplication().pushScreen(new DetailedNewsScreen(news.getImageURL() , imageIndex));
} else
click++;
}
}
}
});
}
/**
* Handle resource request (e.g., images, external css/javascript resources)
*/
public InputConnection handleResourceRequest(BrowserFieldRequest request) throws Exception {
return super.handleResourceRequest(request);
}
}
And in the MainScren use the following
browserField = new BrowserField();
browserField.getConfig().setProperty(BrowserFieldConfig.CONTROLLER, new CacheProtocolController(browserField,List,index));
I tried to create a simple example of callback from Javascript to Java, based on the last example in WebEngine's javadoc (Calling back to Java from JavaScript). But when I click the link in the WebView, the Java method is not called and the page disappears.
public class TestOnClick extends Application {
#Override
public void start(Stage stage) throws Exception {
try {
final WebView webView = new WebView();
final WebEngine webEngine = webView.getEngine();
Scene scene = new Scene(webView);
stage.setScene(scene);
stage.setWidth(1200);
stage.setHeight(600);
stage.show();
String webPage = "<html>\n"
+ " <body>\n"
+ " Click here\n"
+ " </body>\n"
+ "</html>";
System.out.println(webPage);
webView.getEngine().loadContent(webPage);
JSObject window = (JSObject) webEngine.executeScript("window");
window.setMember("app", new JavaApp());
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
public static class JavaApp {
public void onClick() {
System.out.println("Clicked");
}
}
}
Note: I don't see any exceptions being thrown in the WebView when monitoring the load worker with webView.getEngine().getLoadWorker().exceptionProperty().addListener(...).
You are trying to access webview DOM model before it was created.
Wrap your JavaApp related code to the page load listener to achieve your goal:
webEngine.getLoadWorker().stateProperty().addListener(new ChangeListener<Worker.State>() {
#Override
public void changed(ObservableValue<? extends State> ov, State t, State t1) {
if (t1 == Worker.State.SUCCEEDED) {
JSObject window = (JSObject) webEngine.executeScript("window");
window.setMember("app", new JavaApp());
}
}
});
I am trying to handle an event in BrowserField when the user actually clicks a link.
I studied BrowserFieldListener, tried its documentCreated() method but that gives me a response when the page starts loading. I want a trigger the moment user clicks a link inside browserField.
What am i missing here?
Override handleNavigationRequest() of ProtocolController like
ProtocolController controller = new ProtocolController(browserField) {
public void handleNavigationRequest(BrowserFieldRequest request) throws Exception {
/*
Here you get the redirection link using
request.getURL()
and do what you want to do
*/
// to display url in browserfield use
InputConnection inputConnection = handleResourceRequest(request);
browserField.displayContent(inputConnection, request.getURL());
}
};
browserField.getConfig().setProperty(BrowserFieldConfig.CONTROLLER, controller);
Use the following class that was I used
public class CacheProtocolController extends ProtocolController{
public CacheProtocolController() {
super(browserField);
}
/**
* Handle navigation requests (e.g., link clicks)
*/
public void handleNavigationRequest(final BrowserFieldRequest request) throws Exception {
UiApplication.getUiApplication().invokeAndWait(new Runnable() {
public void run() {
// TODO Auto-generated method stub
Logger.debug("*******URL*******",request.getURL() );
});
}
/**
* Handle resource request (e.g., images, external css/javascript resources)
*/
public InputConnection handleResourceRequest(BrowserFieldRequest request) throws Exception {
return super.handleResourceRequest(request);
}
}
I have solved this problem using the following class:
public class CacheProtocolController extends ProtocolController{
private SparseList sparseList = null;
private int imageIndex ;
private int click = 0;
private BrowserField browserField = null;
public CacheProtocolController(BrowserField browserField,SparseList sparseList,int imageIndex ) {
super(browserField);
this.sparseList = sparseList;
this.imageIndex = imageIndex;
}
/**
* Handle navigation requests (e.g., link clicks)
*/
public void handleNavigationRequest(final BrowserFieldRequest request) throws Exception {
UiApplication.getUiApplication().invokeAndWait(new Runnable() {
public void run() {
Logger.debug("*******URL*******",request.getURL() );
String requestUrl = null;
requestUrl = FileManipulations.replaceAll(request.getURL(), "file:///SDCard/BlackBerry/pictures/", "../");
Logger.debug("*******requestUrl*******",requestUrl );
Enumeration enumeration = sparseList.elements();
while (enumeration.hasMoreElements()) {
final News news = (News) enumeration.nextElement();
if(news.getDetailsURL().equalsIgnoreCase(requestUrl)){
if(click == 1){
click = 0;
UiApplication.getUiApplication().pushScreen(new DetailedNewsScreen(news.getImageURL() , imageIndex));
} else
click++;
}
}
}
});
}
/**
* Handle resource request (e.g., images, external css/javascript resources)
*/
public InputConnection handleResourceRequest(BrowserFieldRequest request) throws Exception {
return super.handleResourceRequest(request);
}
}
And in the MainScren use the following
browserField = new BrowserField();
browserField.getConfig().setProperty(BrowserFieldConfig.CONTROLLER, new CacheProtocolController(browserField,List,index));
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.
When i click a button, in next screen i've loaded browserfield requestcontent() using thread.
and i've added browserfield listener.
when click back button , i came to first screen. But in background, requestContent is executing. how to stop it.?
i write the code on onClose() method
public boolean onClose()
{
for(int i=0;i<=Thread.activeCount();i++)
{
if(Thread.currentThread().isAlive())
{
Thread.currentThread().interrupt();
}
}
return super.onClose();
}
My code is.,
new Thread(new Runnable()
{
public void run()
{
loadWebContent(path);
}
}).start();
private void loadWebContent(String path)
{
final VerticalFieldManager vfm = new VerticalFieldManager(HORIZONTAL_SCROLL|VERTICAL_SCROLL)
{
protected void sublayout(int maxWidth, int maxHeight)
{
super.sublayout(maxWidth, (Display.getHeight()-47));
setExtent(maxWidth, (Display.getHeight()-47));
}
};
BrowserFieldConfig myBrowserFieldConfig = new BrowserFieldConfig();
myBrowserFieldConfig.setProperty(BrowserFieldConfig.NAVIGATION_MODE,BrowserFieldConfig.NAVIGATION_MODE_POINTER);
myBrowserField = new BrowserField(myBrowserFieldConfig);
myBrowserField.addListener(new BrowserFieldListener()
{
public void documentLoaded(BrowserField browserField,Document document) throws Exception
{
UiApplication.getApplication().invokeLater(new Runnable()
{
public void run()
{
try
{
mainlayout.delete(spinner);
mainlayout.add(myBrowserField);
myBrowserField.setZoomScale(1.0f);
}
catch (Exception e)
{
System.out.println("++ "+e);
}
}
});
}
});
myBrowserField.requestContent(path);
}
Pls help how to stop execution when back to first screen.
I think this is Enough:
public class LoadingScreen extends MainScreen
{
ButtonField click;
String url;
BrowserField browserField;
public LoadingScreen()
{
url="http://www.google.com";
browserField=new BrowserField();
add(browserField);
browserField.requestContent(url);
}
}
In onClose method:
public boolean onClose()
{
return super.close();
}
If you have any doubbts come on chat room named "Knowledge sharing center for blackberry and java" to clarify your and our doubts.