Network error on some devices after build - java

I installed the app after build on different devices (Android) the app opens up fine but when sending network request only one of the device is able to send successfully the others remain unresponsive.
Am using the Rest.post() to send that particular request.
Using codename one 6.0 but updated it this morning so I will be using the recent version.
Note: the situation happened before the update. i added a bunch of things while trying to locate the problem.
Here is the code:
//...Login button ActionListner
gui_Button_login.addActionListener((ae)->{
gui_Infinite_Progress.setVisible(true);
gui_Infinite_Progress.setEnabled(true);
gui_Button_login.setEnabled(false);
gui_Text_Field_username.setEnabled(false);
gui_Text_Field_Password.setEnabled(false);
if(doLogin()){
Handle.UserFeed = new UserFeedForm();
Handle.UserFeed.show();
}else{
gui_Button_login.setEnabled(true);
gui_Text_Field_username.setEnabled(true);
gui_Text_Field_Password.setEnabled(true);
gui_Infinite_Progress.setVisible(false);
gui_Infinite_Progress.setEnabled(false);
}
});
//...Do login function
private boolean doLogin(){
String usr_username = gui_Text_Field_username.getText();
String usr_password = gui_Text_Field_Password.getText();
Map<String, Object> signInData = new HashMap<>();
signInData.put("usr_username", usr_username);
signInData.put("usr_password", usr_password);
String signInDataJSON = JSONParser.mapToJson(signInData);
gui_Span_Label_Debug.setText(gui_Span_Label_Debug.getText() +"\nData:\n"+ signInDataJSON);
gui_Span_Label_Debug.setText(gui_Span_Label_Debug.getText() +"\nSending...");
Response<Map> response = Rest.post(Data.API_SIGNIN_URL)
.jsonContent()
.body(signInDataJSON)
.acceptJson()
.onErrorCodeJSON(err->{
ToastBar.showErrorMessage(err.getResponseErrorMessage(), Data.MESSAGE_ERROR_TIMEOUT);
//gui_Span_Label_Debug.setText(gui_Span_Label_Debug.getText() +"\nError:\n"+ err.getResponseErrorMessage());
}).getAsJsonMap();
Map<String, Object> responseData = response.getResponseData();
if(response.getResponseCode() == 0){
ToastBar.showErrorMessage("Please check your internet!", Data.MESSAGE_ERROR_TIMEOUT);
}
gui_Span_Label_Debug.setText(gui_Span_Label_Debug.getText() +"\nResponse Code:\n"+ response.getResponseCode());
gui_Span_Label_Debug.setText(gui_Span_Label_Debug.getText() +"\nResponse Error Msg:\n"+ response.getResponseErrorMessage());
if(responseData == null){
return false;
}
if(((String)responseData.get("status")).equalsIgnoreCase("error")){
ToastBar.showErrorMessage((String)responseData.get("msg"), Data.MESSAGE_ERROR_TIMEOUT);
return false;
}
if(((String)responseData.get("status")).equalsIgnoreCase("success")){
ToastBar.showMessage((String)responseData.get("msg"), FontImage.MATERIAL_CHECK_CIRCLE, Data.MESSAGE_SUCCESS_TIMEOUT);
Handle.LoggedInUserData = (Map<String, Object>) responseData.get("data");
Handle.Authority = (String)Handle.LoggedInUserData.get("jwt");
return true;
}
return false;
}
//...
Data.API_SIGNIN_URL is a string containing address accessible via internet e.g. http://94.543.23.4/

I'm guessing you are trying to connect via an IP to a specific machine and it isn't working. This machine is probably visible only within your internal network and the other devices aren't connected to the internal network or choose a route via cell towers.

well i added the build hint android.xpermissions and set the value to android.permission.INTERNET\=true,android.permission.WRITE_EXTERNAL_STORAGE\=true,android.permission.READ_EXTERNAL_STORAGE\=true.
Its working but seems redundant to me since according to codenameone docs Internet permission is inserted by default. i added the storage just to avert possible similar situation

Related

How to get Google Ads impressions based on location

I am working with Google Ads API. Based on my use case, I need to get the impressions, clicks, and other statistics about the products based on location(Without creating the campaign).
I contacted the Google Ads API team to address the issue but the doc reference they provided me didn't work in my case. (I'm not using keywords also)
generate forecast metrics
And also the query I used to access the data is...
public void queryTest(long customerId,String campaignId) {
try (GoogleAdsServiceClient googleAdsServiceClient =
googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) {
SearchGoogleAdsStreamRequest request =
SearchGoogleAdsStreamRequest.newBuilder()
.setCustomerId(Long.toString(customerId))
.setQuery("SELECT metrics.clicks, metrics.impressions,geographic_view.country_criterion_id FROM geographic_view WHERE geographic_view.country_criterion_id = 1009919")
.build();
ServerStream<SearchGoogleAdsStreamResponse> stream =
googleAdsServiceClient.searchStreamCallable().call(request);
for (SearchGoogleAdsStreamResponse response : stream) {
for (GoogleAdsRow googleAdsRow : response.getResultsList()) {
System.out.println("outPut"+googleAdsRow.getGeographicView());
}
}
}
}
Can someone please help me to resolve this issue??
Thank you!!

OSPermissionSubscriptionState : Cannot resolve symbol

I'm trying to add push notification to my mobile native chat app. I'm trying to use OneSignal.
I can send manual push notification, so I think gradle part is okay
idsAvaiable method is deprecated, I started to looking for how can I get userId.
OSPermissionSubscriptionState status = OneSignal.getPermissionSubscriptionState();
String userId = status.getSubscriptionStatus().getUserId();
In here, I'm trying to get userId with status, but it's saying:
Cannot resolve symbol 'OSPermissionSubscriptionState'
How can I get userId?
Root cause
From OneSignal API 4.0.0, there are many APIs that have been removed including OSPermissionSubscriptionState.
Solution 1
Use OneSignal.getDeviceState()
OSDeviceState device = OneSignal.getDeviceState();
String userId = device.getUserId();
Solution 2
Use OneSignal.addSubscriptionObserver()
OneSignal.addSubscriptionObserver(new OSSubscriptionObserver() {
#Override
public void onOSSubscriptionChanged(OSSubscriptionStateChanges stateChanges) {
if (!stateChanges.getFrom().isSubscribed() && stateChanges.getTo().isSubscribed()) {
// Get user id
String userId = stateChanges.getTo().getUserId();
}
}
});
For more information, see the change log here.

"Unsupported protocol element" when creating Interactions programmatically

I am attempting to create new Interactions programmatically on Genesys Platform SDK 8.5 for Java.
I use the example on the API reference
public void createInteraction(String ixnType, String ixnSubtype, String queue) throws Exception
{
RequestSubmit req = RequestSubmit.create();
req.setInteractionType(ixnType);
req.setInteractionSubtype(ixnSubtype);
req.setQueue(queue);
req.setMediaType("email");
Message response = mPMService.getProtocol("IxnSrv").request(req);
if(response == null || response.messageId() != EventAck.ID) {
// For this sample, no error handling is implemented
return;
}
EventAck event = (EventAck)response;
mInteractionId = event.getExtension().getString("InteractionId");
}
However, this gives me an Unsupported protocol element error.
'EventError' (126) attributes:
attr_error_desc [str] = "Unsupported protocol element"
attr_ref_id [int] = 2
attr_error_code [int] = 4
How do I create a new Interaction programmatically?
Interaction server should be connected with ClientType as either MediaServer or AgentApplication for this request(RequestSubmit).
First of all, you must open your protocol as Media Server. After that you must submit your interaction to interaction server.
Firstly your protocol config must be like this;
interactionServerConfiguration.ClientName = "TestClient";
interactionServerConfiguration.ClientType = InteractionClient.MediaServer;
// Register this connection configuration with Protocol Manager
protocolManagementService.Register(interactionServerConfiguration);
Note : You must have MediaServer type application definition on your Configuration Env., you must see it in CME.
After open you connection to ixn server. You can submit your interaction what you like. Even you can create new type interaction just like i do. I did for our coopate sms system. Its name is not important. We defined it on our bussiness attribute, so our agent can send coopate 3rd party sms system from their agent desktop. Without new extension or new license :) Just tricked it system. Also genesys allows it. i know it because we are genesys official support team in our country :) (But agent seat license may be required depends on agent head count).
RequestSubmit request = RequestSubmit.Create();
request.TenantId = 1;
request.MediaType = "email";
request.Queue = c_inboundQueue;
request.InteractionType = "Inbound";
request.InteractionSubtype = "InboundNew";
// Prepare the message to send. It is inserted in the request as UserData
KeyValueCollection userData =
new KeyValueCollection();
// Prepare the message to send
userData.Add("Subject", "subject goes here");
request.UserData = userData; protocolManagementService[c_interactionServerConfigurationIdentifier].Send(request);
Turns out I needed to set ClientType to InteractionClient.ReportingEngine.

How can I send from the server-side (Google App Engine, Cloud Endpoints) the information to my client?

I have an Android Application that is stored in the Cloud, with Google App Engine. I use Cloud Endpoints. My problem is that I cannot send the data from the server to my client(Android Device), or better said, so far, I have no idea how to do that.
So far, I have managed to insert data in the datastore, by creating an endpoint and calling the method that is in charge with adding a record in the database(that's located on the server side, in myProject - AppEngine) , using the following code (on the client):\
Noteendpoint.Builder endpointBuilder = new Noteendpoint.Builder(
AndroidHttp.newCompatibleTransport(),
new JacksonFactory(),
new HttpRequestInitializer() {
public void initialize(HttpRequest httpRequest) { }
});
Noteendpoint endpoint = CloudEndpointUtils.updateBuilder(
endpointBuilder).build();
try {
// Construct the note.
Note note = new Note().setDescription("Note DescriptionRoxana");
String noteID = new Date().toString();
note.setId(noteID);
note.setEmailAddress("E-Mail AddressRoxana");
// Insert the Note, by calling a method that's on the server side - insertNote();
Note result = endpoint.insertNote(note).execute();
} catch (IOException e) {
e.printStackTrace();
}
But I cannot see a way of retrieving data from the datastore and to display it on the server side. I tried to do the same, create an endpoint, that will call the method that retrieves all the records in the database (method that is located on the server), but my application crashes.
The code for the method that retrieves data from the datastore is the following:
public CollectionResponse<Note> listNote(
#Nullable #Named("cursor") String cursorString,
#Nullable #Named("limit") Integer limit) {
EntityManager mgr = null;
Cursor cursor = null;
List<Note> execute = null;
try {
mgr = getEntityManager();
Query query = mgr.createQuery("select from Note as Note");
if (cursorString != null && cursorString != "") {
cursor = Cursor.fromWebSafeString(cursorString);
query.setHint(JPACursorHelper.CURSOR_HINT, cursor);
}
if (limit != null) {
query.setFirstResult(0);
query.setMaxResults(limit);
}
execute = (List<Note>) query.getResultList();
cursor = JPACursorHelper.getCursor(execute);
if (cursor != null)
cursorString = cursor.toWebSafeString();
// Tight loop for fetching all entities from datastore and accomodate
// for lazy fetch.
for (Note obj : execute)
;
} finally {
mgr.close();
}
return CollectionResponse.<Note> builder().setItems(execute)
.setNextPageToken(cursorString).build();
}
You see, the returned type is collection response. You have access to this type of data, after performing the following import:
import com.google.api.server.spi.response.CollectionResponse;
I inferred that this is a data type characteristic to the server side, thus, I have no idea how I can cast it into a List, ArrayList, or any other type of collection, that can be used on the client side.
How should I do it then? Since adding data was so easy and so straight forward, I have assumed that retrieving data would be performed in the same manner, but apparently I am missing something essential for this matter.
Thank you in advance!
The classes you use in the backend are not the same as the classes you'll use in the client. Endpoints will generate a set of libraries for you, either on the command line or with tooling like Google Plugin for Eclipse. See Using Endpoints in an Android Client.
The generated class representing the collection of Notes in your example will be named something like NotesCollection. This object will have a method getItems, which provides you a List<Note> you can iterate on in your Android application.
Similar to having an endpoint for inserting data into a datastore model(methods of type POST), you need to have an endpoint for querying the data from the datastore model (methods of type GET). After you define both these methods, you need generate your discovery document and client library so that clients know about both these methods and can call them. If your speaking about displaying the data in the web itself then you can build a Javascript client by using the required client library.

how to identify whether the OS is Linux desktop or Android? [duplicate]

This question already has answers here:
How do I programmatically determine operating system in Java?
(22 answers)
Closed 3 years ago.
I have an app that runs on several mobile devices running either Fedora or Android. To consolidate my codebase and distribution I would like to determine which OS I am on. I tried System.getProperty("os.name"), but that just returns "Linux". Is there something unique to Android in the System properties?
Thanks
There are several properties you could check. Candidates are:
java.vendor.url --> http://www.android.com
java.vm.name --> Dalvik (I don't know, which one Fedora is using...)
java.vm.vendor --> The Android Project
java.vendor --> The Android Project
Maybe you want to check by yourself?
Properties p = System.getProperties();
Enumeration keys = p.keys();
while(keys.hasMoreElements()) {
String key = (String) keys.nextElement();
String value = (String) p.get(key);
System.out.println(key + " >>>> " + value);
}
I do not know Android but if you do not find some unique system property you can sometimes identify the system if some specific class exists there. So you can do the following:
boolean isAndroid() {
try {
Class.forName("the class name");
return true;
} catch(ClassNotFoundException e) {
return false;
}
}
Here is some code that I wrote using the information from this page, in case you want to copy-paste:
private static YLogger ylogger;
public static YLogger getLogger() {
if (ylogger == null){
// need to find a new logger. Let's check if we have Android running
if (System.getProperty("java.vm.name").equalsIgnoreCase("Dalvik")){
ylogger = new AndroidLogger();
ylogger.d("YLoggerFactory", "Instantiating Android-based logger");
} else {
// fallback option, system logger.
ylogger = new SystemLogger();
ylogger.d("YLoggerFactory", "Instantiating System-based logger");
}
}
return ylogger;
}
The list of defined system properties is here: https://developer.android.com/reference/java/lang/System#getProperties()
I'm using
boolean android = "The Android Project".equals(System.getProperty("java.specification.vendor"));
I use this in my processing sketch to determine in which mode I'm running i.e. where I'm running it.
enum Mode {
java, android
}
Mode getMode() {
return System.getProperty("java.runtime.name").equals("Android Runtime") ? Mode.android : Mode.java;
}
if (getMode() == Mode.java){
// do something
// eg: do something that android can't handle
} else {
// do android stuff
// eg: scale the sketch by 2 to improve visibility
}

Categories

Resources