ConnectionRequest issue - codenameone

I called 'new NewForm(res).show()' in postResponse but though the connection succeed, the particular form is not seen. I found out that if I comment out 'cr.setDisposeOnCompletion(d)', then it works fine.
But infinite progress runs infinitely if any exception occurs and so on. Is this a bug? It occured after I updated to new cn1 library update. If you want to see the project, its here:
https://drive.google.com/file/d/0B8ATnICIY2S8LUdta0F5NXYzamM/view?usp=sharing
Button checkButton = new Button("Check");
checkButton.addActionListener(e -> {
ConnectionCheck cc = new ConnectionCheck(theme);
cc.connectionCheckMethod();
});
ConnectionCheck class
public class ConnectionCheck {
Resources res;
Dialog d;
public ConnectionCheck(Resources res) {
this.res = res;
}
public void connectionCheckMethod() {
ConnectionRequest cr = new ConnectionRequest() {
#Override
protected void readResponse(InputStream input) throws IOException {
JSONParser jsonp = new JSONParser();
Map<String, Object> parser = jsonp.parseJSON(new InputStreamReader(input));
System.out.println("bibek " + parser);
}
#Override
protected void postResponse() {
new NewForm(res).show();
// d.dispose();
}
#Override
protected void handleErrorResponseCode(int code, String message) {
System.out.println("login ErrorResponseCode " + code + "msg: " + message);
// d.dispose();
}
#Override
protected void handleException(Exception err) {
System.out.println("login Exception " + err);
// d.dispose();
}
#Override
protected void handleIOException(IOException err) {
System.out.println("login IOException " + err);
// d.dispose();
}
#Override
protected void handleRuntimeException(RuntimeException err) {
System.out.println("login RuntimeException " + err);
// d.dispose();
}
};
cr.setPost(true);
cr.setUrl("http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo");
cr.setTimeout(30000);
cr.addRequestHeader("Accept", "application/json");
InfiniteProgress ip = new InfiniteProgress();
d = ip.showInifiniteBlocking();
cr.setDisposeOnCompletion(d); //if this line is commented, the newForm is shown
NetworkManager.getInstance().addToQueueAndWait(cr);
}
}
NewForm class
public class NewForm extends Form{
public NewForm(Resources res){
setTitle("new Form");
add(new Label("new Form"));
}
}

You need to dispose the dialog before calling the show of the new form. Dispose on completion will dispose the dialog when the connection is done which is sometimes unpredictable.
When a dialog is disposed it returns to the previous form i.e. the one shown before the dialog was shown.

Related

Getting the next turn/direction in Mapbox

I'm trying to get the direction of the upcoming turn while travelling, i.e. I want to trigger an event in my app according to the direction of the upcoming turn.
I've tried using event listeners, taking help of the documentation and the provided examples but as I'm pretty new to android studio and mapbox, I've not been successful (my app either crashed or the function would never get triggered). I've also tried searching for getting the voice commands into text form or log form but have failed.
While my current code does display directions and gives voiced instructions, I can't figure out how to access either of them. I'd like to know if there's a simple way of achieving what I'm after without using any event listeners.
private MapView mapView;
private MapboxMap mapboxMap;
private PermissionsManager permissionsManager;
private LocationComponent locationComponent;
private DirectionsRoute currentRoute;
private static final String TAG = "DirectionsActivity";
private NavigationMapRoute navigationMapRoute;
private MapboxNavigation navigation;
private Button button;
private NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this, getString(R.string.access_token));
setContentView(R.layout.activity_main);
mapView = findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
// Toast.makeText(this, "Hello", Toast.LENGTH_SHORT).show();
}
#Override
public void onMapReady(#NonNull final MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
//Toast.makeText(this, "Hello", Toast.LENGTH_SHORT).show();
mapboxMap.setStyle(getString(R.string.navigation_guidance_day), new Style.OnStyleLoaded() {
#Override
public void onStyleLoaded(#NonNull Style style) {
enableLocationComponent(style);
addDestinationIconSymbolLayer(style);
mapboxMap.addOnMapClickListener(MainActivity.this);
button = findViewById(R.id.startButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean simulateRoute = true;
NavigationLauncherOptions options = NavigationLauncherOptions.builder()
.directionsRoute(currentRoute)
.shouldSimulateRoute(simulateRoute)
.build();
NavigationLauncher.startNavigation(MainActivity.this, options);
}
});
}
});
}
private void addDestinationIconSymbolLayer(#NonNull Style loadedMapStyle) {
loadedMapStyle.addImage("destination-icon-id",
BitmapFactory.decodeResource(this.getResources(), R.drawable.mapbox_marker_icon_default));
GeoJsonSource geoJsonSource = new GeoJsonSource("destination-source-id");
Log.d(TAG, "addDestinationIconSymbolLayer: " + geoJsonSource);
loadedMapStyle.addSource(geoJsonSource);
SymbolLayer destinationSymbolLayer = new SymbolLayer("destination-symbol-layer-id", "destination-source-id");
destinationSymbolLayer.withProperties(
iconImage("destination-icon-id"),
iconAllowOverlap(true),
iconIgnorePlacement(true)
);
loadedMapStyle.addLayer(destinationSymbolLayer);
}
#SuppressWarnings( {"MissingPermission"})
#Override
public boolean onMapClick(#NonNull LatLng point) {
Point destinationPoint = Point.fromLngLat(point.getLongitude(), point.getLatitude());
Point originPoint = Point.fromLngLat(locationComponent.getLastKnownLocation().getLongitude(),
locationComponent.getLastKnownLocation().getLatitude());
GeoJsonSource source = mapboxMap.getStyle().getSourceAs("destination-source-id");
Log.d(TAG, "Does this even work");
Log.d(TAG, "onMapClick: " + source.toString());
if (source != null) {
source.setGeoJson(Feature.fromGeometry(destinationPoint));
}
getRoute(originPoint, destinationPoint);
button.setEnabled(true);
button.setBackgroundResource(R.color.mapboxBlue);
return true;
}
private void getRoute(Point origin, Point destination) {
NavigationRoute.builder(this)
.accessToken(Mapbox.getAccessToken())
.origin(origin)
.destination(destination)
.build()
.getRoute(new Callback<DirectionsResponse>() {
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
Log.d(TAG, "Response code: " + response.code());
if (response.body() == null) {
Log.e(TAG, "No routes found, make sure you set the right user and access token.");
return;
} else if (response.body().routes().size() < 1) {
Log.e(TAG, "No routes found");
return;
}
currentRoute = response.body().routes().get(0);
if (navigationMapRoute != null) {
navigationMapRoute.removeRoute();
} else {
navigationMapRoute = new NavigationMapRoute(null, mapView, mapboxMap, R.style.NavigationMapRoute);
}
navigationMapRoute.addRoute(currentRoute);
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable throwable) {
Log.e(TAG, "Error: " + throwable.getMessage());
}
});
}
#SuppressWarnings( {"MissingPermission"})
private void enableLocationComponent(#NonNull Style loadedMapStyle) {
if (PermissionsManager.areLocationPermissionsGranted(this)) {
locationComponent = mapboxMap.getLocationComponent();
locationComponent.activateLocationComponent(this, loadedMapStyle);
locationComponent.setLocationComponentEnabled(true);
locationComponent.setCameraMode(CameraMode.TRACKING);
} else {
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
public void onExplanationNeeded(List<String> permissionsToExplain) {
Toast.makeText(this, R.string.user_location_permission_explanation, Toast.LENGTH_LONG).show();
}
#Override
public void onPermissionResult(boolean granted) {
if (granted) {
enableLocationComponent(mapboxMap.getStyle());
} else {
Toast.makeText(this, R.string.user_location_permission_not_granted, Toast.LENGTH_LONG).show();
finish();
}
}
// Add the mapView's own lifecycle methods to the activity's lifecycle methods
#Override
public void onStart() {
super.onStart();
mapView.onStart();
}
#Override
public void onResume() {
super.onResume();
mapView.onResume();
// Toast.makeText(this, "Hello", Toast.LENGTH_SHORT).show();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onStop() {
super.onStop();
mapView.onStop();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
}
It sounds like you might want to look at using an event listener for a custom milestone. Here's a link to the docs:
https://docs.mapbox.com/android/navigation/overview/milestones/#milestone-event-listener

cn1 - Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference

I've a error thrown I can't figure out how it happens. It doesn't occur all the time but once in a while. The error message thrown is "Java.lang.nullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference". I've used connectionRequest for parsing the json data. When the error is thrown I've checked if there's problem in url but it gives the proper json data as always. After trying few times, the error is solved automatically.
if (!regNOField.getText().equals("") && !newPasswordField.getText().equals("")) {
ArrayList<Map<String, String>> argumentsArrayList = new ArrayList<>();
Map argumentMap1 = new HashMap();
argumentMap1.put("argument", "reg_no");
argumentMap1.put("value", regNOField.getText().trim());
argumentsArrayList.add(argumentMap1);
Map argumentMap2 = new HashMap();
argumentMap2.put("argument", "token");
argumentMap2.put("value", newPasswordField.getText().trim());
argumentsArrayList.add(argumentMap2);
CommonMethod.connectionMethod(res, true, url, "Verification", argumentsArrayList, true, null);
}
CommonMethod.connectionMethod:
public static void connectionMethod(Resources res, Boolean postBoolean, String urlString, String form, ArrayList<Map<String, String>> arguments,
Boolean ipFlag, String extraData) {
ConnectionRequest cr = new ConnectionRequest() {
#Override
protected void readResponse(InputStream input) throws IOException {
JSONParser jp = new JSONParser();
parser = jp.parseJSON(new InputStreamReader(input));
response = null;
if (parser != null && !parser.isEmpty()) {
if (parser.get("status").equals("true")) {
message = (String) parser.get("data");
ToastBar.getInstance().setPosition(Component.TOP);
ToastBar.showErrorMessage(message, 5000);
if (form.equals("Verification")) {
if (d != null) {
d.dispose();
}
new LoginAndSignUp(res, message).show();
}
}
}
}
#Override
protected void handleErrorResponseCode(int code, String message) {
System.out.println("login ErrorResponseCode " + code + "msg: " + message);
}
#Override
protected void handleException(Exception err) {
System.out.println("login Exception " + err);
}
#Override
protected void handleIOException(IOException err) {
System.out.println("login IOException " + err);
}
#Override
protected void handleRuntimeException(RuntimeException err) {
System.out.println("RuntimeException " + err);
}
};
cr.setPost(postBoolean);
cr.setUrl(urlString);
cr.setTimeout(80000);
if (arguments != null && !postBoolean.equals(false)) {
for (Map<String, String> entrySet : arguments) {
String argument1 = (String) entrySet.get("argument");
String value1 = (String) entrySet.get("value");
cr.addArgument(argument1, value1);
}
}
InfiniteProgress ip = new InfiniteProgress();
d = ip.showInifiniteBlocking();
cr.setDisposeOnCompletion(d);
cr.addRequestHeader("accept", "application/json");
NetworkManager.getInstance().addToQueueAndWait(cr);
}
Error msg:

ConnectionRequest is not working in iOS

I've a year & a half old app to update. It was written in statemachine. Now I added a few things but the connectionRequest doesn't seem to work in iOS (which was built for iOS debug). I built it in android and it works very well.
public void connectionForLogin(String username, String password) {
ConnectionRequest cr = new ConnectionRequest() {
#Override
protected void readResponse(InputStream input) throws IOException {
JSONParser jSONParser = new JSONParser();
Map<String, Object> parsedData = jSONParser.parseJSON(new InputStreamReader(input));
ArrayList<Map<String, Object>> response = (ArrayList<Map<String, Object>>) parsedData.get("root");
if (response != null) {
for (Map<String, Object> element : response) {
success = (String) element.get("login");
msg = (String) element.get("msg");
ArrayList<Map<String, Object>> userInfoArray = (ArrayList) element.get("user_info");
Storage.getInstance().writeObject("userInfo", userInfoArray);
}
}
}
#Override
protected void postResponse() {
super.postResponse();
}
#Override
protected void handleErrorResponseCode(int code, String message) {
}
#Override
protected void handleException(Exception err) {
}
#Override
protected void handleIOException(IOException err) {
}
#Override
protected void handleRuntimeException(RuntimeException err) {
}
};
cr.setPost(true);
cr.setDuplicateSupported(true);
cr.setTimeout(30000);
AllUrl au = new AllUrl();
InfiniteProgress ip = new InfiniteProgress();
Dialog d = ip.showInifiniteBlocking();
cr.setDisposeOnCompletion(d);
cr.setUrl(http://zzz.com/api/logins/match? + "username=" + username + "&password=" + password);
NetworkManager.getInstance().addToQueueAndWait(cr);
}
This may be due to new Apple regulations that prevents apps from fetching data from non secure URL http. You can fix this temporarily by adding below build hint:
ios.plistInject=<key>NSAppTransportSecurity</key><dict><key>NSAllowsArbitraryLoads</key><true/></dict><key>CFBundleURLTypes</key><array><dict><key>CFBundleURLName</key><string>com.mycompany.myapp</string></dict><dict><key>CFBundleURLSchemes</key><array><string>MyApp</string></array></dict></array>
Note that your app may be rejected if connected to a non secure URL.

Codenameone closing a socket

There seems to be no way of disconnecting a socket without causing a connection reset error on the server side.
I'm using the com.codename1.io.Socket and com.codename1.io.SocketConnection implementations within a tester app. My code is as follows:
private SpanLabel lblStatus;
private SpanLabel lblIncoming;
private CustomSocketConnection con;
private Thread tIncoming;
public ConnectForm() {
con = getSocketConnection();
Button btnConnect = getConnectButton();
Button btnDisconnect = getDisconnectButton();
Button btnSendMessage = getSendMessageButton();
lblStatus = getInfoLabel();
lblIncoming = getIncomingLabel();
setLayout(new BoxLayout(BoxLayout.Y_AXIS));
addComponent(btnConnect);
addComponent(btnDisconnect);
addComponent(btnSendMessage);
addComponent(lblStatus);
addComponent(lblIncoming);
}
private Button getConnectButton() {
Button btn = new Button("Connect (localhost)");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Socket.connect("localhost", 8687, con);
}
});
return btn;
}
private Button getDisconnectButton() {
Button btn = new Button("Disconnect");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//??? I don't know how to do this
try {
tIncoming.join();
} catch (Exception e) {
e.printStackTrace();
tIncoming.interrupt();
}
}
});
return btn;
}
private Button getSendMessageButton() {
Button btn = new Button("Send Message");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
try {
con.os.write("Hello".getBytes());
con.os.write(Integer.parseInt("04", 16)); //end of transmit
con.os.flush();
lblStatus.setText("Message Sent");
} catch (Exception e) {
e.printStackTrace();
}
}
});
return btn;
}
private SpanLabel getInfoLabel() {
return new SpanLabel("Disconnected");
}
private SpanLabel getIncomingLabel() {
return new SpanLabel("...");
}
private CustomSocketConnection getSocketConnection() {
return new CustomSocketConnection();
}
class CustomSocketConnection extends SocketConnection {
public OutputStream os;
public InputStream is;
#Override
public void connectionError(int errorCode, String message) {
lblStatus.setText("Error Connecting. ErrorCode: " + errorCode + " Message: " + message);
}
#Override
public void connectionEstablished(InputStream is, OutputStream os) {
lblStatus.setText("Connected :)");
this.is = is;
this.os = os;
spawnIncomingMessageWatcher();
}
}
private void spawnIncomingMessageWatcher() {
tIncoming = new Thread(new Runnable() {
public void run() {
String s = "";
int eot = Integer.parseInt("04", 16);
while (con.isConnected()) {
try {
int temp;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while (((temp = con.is.read()) != -1) && (temp != eot)) {
baos.write(temp);
}
lblIncoming.setText(new String(baos.toByteArray()));
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
tIncoming.start();
}
With the getDisconnectButton() method, I do not know how to properly disconnect from the server, as the SocketConnection object does not seem to have an appropriate method for this.
If you call close() on either the Input- or OutputStream then you close the Socket, code from Socket.SocketInputStream class link.
public void close() throws IOException {
closed = true;
if(Util.getImplementation().isSocketConnected(impl)) {
Util.getImplementation().disconnectSocket(impl);
con.setConnected(false);
}
}
So first send close instruction to Server and then close a stream.
Hope this helps,

org.openqa.selenium.InvalidElementStateException: Element is read-only and so may not be used for actions

n my page there are lots of drop down boxes and text fields.while testing the page in eclipse IDE its showing the above exception. I am not able to find any solution for this Exception
This is my code:
public class QuoteNewEntry {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "http:///";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testQuoteNewEntry() throws Exception {
driver.get(baseUrl + "");
System.out.println("The current Url: "+ driver.getCurrentUrl());
assertEquals("", driver.getTitle());
driver.findElement(By.id("RdbtnLight")).click();
driver.findElement(By.id("txtUserName")).clear();
driver.findElement(By.id("txtUserName")).sendKeys("tom");
driver.findElement(By.id("txtpassword")).clear();
driver.findElement(By.id("txtpassword")).sendKeys("tom");
driver.findElement(By.id("btnSubmit")).click();
assertEquals("", driver.getTitle());
driver.findElement(By.id("btnTrade")).click();
System.out.println("The current Url: "+ driver.getCurrentUrl());
assertEquals("", driver.getTitle());
driver.findElement(By.id("btnQuote")).click();
System.out.println("The current Url: "+ driver.getCurrentUrl());
assertEquals("Quote", driver.getTitle());
driver.findElement(By.id("ContentPlaceHolder1_btnNew")).click();
System.out.println("The current Url: "+ driver.getCurrentUrl());
new Select(driver.findElement(By.id("ContentPlaceHolder1_ddlLineOfBus"))).selectByVisibleText("FCL");
driver.findElement(By.id("ContentPlaceHolder1_txtCaptured")).clear();
driver.findElement(By.id("ContentPlaceHolder1_txtCaptured")).sendKeys("3");
driver.findElement(By.id("ContentPlaceHolder1_rbtn3rdParty")).click();
Thread.sleep(5000);
driver.findElement(By.id("ContentPlaceHolder1_txtTotalTransitDays")).clear();
driver.findElement(By.id("ContentPlaceHolder1_txtTotalTransitDays")).sendKeys("10");
driver.findElement(By.id("ContentPlaceHolder1_txtVoyageFrequency")).clear();
driver.findElement(By.id("ContentPlaceHolder1_txtVoyageFrequency")).sendKeys("weekly");
Thread.sleep(5000);
driver.findElement(By.id("ContentPlaceHolder1_txtExternal")).clear();
driver.findElement(By.id("ContentPlaceHolder1_txtExternal")).sendKeys("ex");
Thread.sleep(5000);
driver.findElement(By.id("ContentPlaceHolder1_btnSave")).click();
try{
driver.findElement(By.xpath("//input[#value = 'alert']")).click();
Thread.sleep(5000);
}
catch(WebDriverException we){
}
}
#After
public void tearDown() throws Exception {
//driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alert.getText();
} finally {
acceptNextAlert = true;
}
}
}
The exception suggests your are trying to perform an edit action on an element that is read-only. This includes actions such as SendKeys() and Click(). You can either make these elements writable in your application, or you must check if they are read-only prior to accessing them; if they are you cannot perform the action.

Resources