Connecting to Bluetooth when trying to get Current Geographic Location in J2ME - java-me

I had done A Simple Application to Record Current Geographic Location and Display it on Mobile Screen then its working fine in j2me emulator but when application installed in mobile(Nokia Asha 210) it installed and opening directly to connecting to bluetooth. It is opening the bluetooth settings where the problem i cant understand so i need help regarding this issue..
This is my Entire Code....
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.location.Location;
import javax.microedition.location.LocationListener;
import javax.microedition.location.LocationProvider;
import javax.microedition.location.QualifiedCoordinates;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class LocationWithPolling extends MIDlet implements Runnable, CommandListener {
Form mainform;
Thread t;
LocationProvider lp;
Display display;
StringItem latitude;
StringItem longitude;
Command exitCommand=new Command("Exit",Command.OK,0);
protected void destroyApp(boolean arg0) {}
protected void pauseApp() {}
protected void startApp() throws MIDletStateChangeException
{
mainform=new Form("Location Polling");
latitude=new StringItem("Latitude:","N/A");
longitude=new StringItem("Longitude:","N/A");
Display.getDisplay(this).setCurrent(mainform);
mainform.append(latitude);
mainform.append(longitude);
mainform.addCommand(exitCommand);
mainform.setCommandListener(this);
t=new Thread(this);
t.start();
}
public void run()
{
try{
lp = LocationProvider.getInstance(null);
while(true)
{
Location loc=lp.getLocation(5000);
QualifiedCoordinates c=loc.getQualifiedCoordinates();
latitude.setText(String.valueOf(c.getLatitude()));
longitude.setText(String.valueOf(c.getLongitude()));
Thread.sleep(5000);
}
}catch(Exception e)
{
Alert alert =
new Alert("Error", "Could not retrieve location!", null, AlertType.ERROR);
display.setCurrent(alert);
}
}
public void providerStateChanged(LocationProvider provider, int newState) { }
public void commandAction(Command cmd, Displayable arg1)
{
if(cmd==exitCommand)
{
notifyDestroyed();
}
}
}

Asha phones do not have internal GPS, so it attempts to connect to a bluetooth GPS, and you apparently have none paired with the phone. That is why I think it opens BT settings. If you had one, it would connect to it.

Related

Android Studio - Creating a Loading/Splash Screen for WebView

I have followed through this tutorial (I am completely new to Android Studio): Loading/Splash Screen Tutorial
and I am unsure why my code isn't working correctly.
I get the loading circle come up on the app I have created, but it does not go away when the app loads the webpage.
I have gone over my code a few times now and I cannot see any errors (obviously there are some somewhere!) Just seems as if it isn't recognising that my webpage has loaded within the app.
Here is my code from my MainActivity.java file:
import android.net.http.SslError;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.graphics.Bitmap;
import android.view.View;
import android.widget.ProgressBar;
public class MainActivity extends AppCompatActivity {
String ShowOrHideWebViewInitialUse = "show";
private WebView myWebView;
private ProgressBar spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myWebView = (WebView) findViewById(R.id.webView);
spinner = (ProgressBar)findViewById(R.id.progressBar1);
myWebView.setWebViewClient(new CustomWebViewClient());
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.getSettings().setDomStorageEnabled(true);
myWebView.getSettings().setDatabaseEnabled(true);
myWebView.getSettings().setMinimumFontSize(1);
myWebView.getSettings().setMinimumLogicalFontSize(1);
myWebView.setWebChromeClient(new WebChromeClient());
myWebView.loadUrl("https://node-red-test.ftp21.net:1024/ui");
myWebView.setWebViewClient(new WebViewClient() { #Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error){ handler.proceed(); } });
}
// This allows for a splash screen
// (and hide elements once the page loads)
private class CustomWebViewClient extends WebViewClient {
#Override
public void onPageStarted(WebView myWebView, String url, Bitmap favicon) {
// only make it invisible the FIRST time the app is run
if (ShowOrHideWebViewInitialUse.equals("show")) {
myWebView.setVisibility(myWebView.INVISIBLE);
}
}
#Override
public void onPageFinished(WebView view, String url) {
ShowOrHideWebViewInitialUse = "hide";
spinner.setVisibility(View.GONE);
view.setVisibility(myWebView.VISIBLE);
super.onPageFinished(view, url);
}
}
#Override
public void onBackPressed() {
if (myWebView.canGoBack()) {
myWebView.goBack();
} else {
super.onBackPressed();
}
}
}
I am currently running Android Studio version 2.1.2 - due to problems with later versions that I came across when following another tutorial.
Thanks,

OnDataChanged is not called

I have a problem with comunication between my phone and wear device. I decided to add wear module to my app. Wear app has just one class (MainActivity)
package cz.johrusk.myapplication;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.wearable.view.WatchViewStub;
import android.util.Log;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.wearable.DataApi;
import com.google.android.gms.wearable.DataEventBuffer;
import com.google.android.gms.wearable.PutDataMapRequest;
import com.google.android.gms.wearable.PutDataRequest;
import com.google.android.gms.wearable.Wearable;
public class MainActivity extends Activity implements GoogleApiClient.OnConnectionFailedListener,DataApi.DataListener {
GoogleApiClient mGoogleApiClient;
private TextView mTextView;
static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
#Override
public void onLayoutInflated(WatchViewStub stub) {
mTextView = (TextView) stub.findViewById(R.id.text);
}
});
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(Bundle connectionHint) {
Log.d(TAG, "onConnected: " + connectionHint);
sendNumber(1);
Log.d(TAG,"BBBBBBBB");
}
#Override
public void onConnectionSuspended(int cause) {
Log.d(TAG, "onConnectionSuspended: " + cause);
}
})
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
Log.d(TAG,"mGoogleApiClient connected;");
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.d(TAG,"FAILE" + connectionResult);
}
public void sendNumber(int number) {
PutDataMapRequest putDataMapRequest = PutDataMapRequest.create("/number");
putDataMapRequest.getDataMap().putInt("number",number);
putDataMapRequest.getDataMap().putLong("Time",System.currentTimeMillis());
PutDataRequest putDataReq = putDataMapRequest.asPutDataRequest();
putDataReq.setUrgent();
Wearable.DataApi.putDataItem(mGoogleApiClient, putDataReq)
.setResultCallback(new ResultCallback<DataApi.DataItemResult>() {
#Override
public void onResult(#NonNull DataApi.DataItemResult dataItemResult) {
if (!dataItemResult.getStatus().isSuccess()) {
Log.d(TAG,"Fail");
}
else{
Log.d(TAG,"Succes");
}
}
});
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
public void onDataChanged(DataEventBuffer dataEventBuffer) {
Log.d(TAG,"TEST");
}
}
I quess that "Wearable.DataApi.putDataItem" should call WearableListenerService in my phone app. Here is that service:
package cz.johrusk.showsmscode.service;
import android.util.Log;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.wearable.DataEvent;
import com.google.android.gms.wearable.DataEventBuffer;
import com.google.android.gms.wearable.DataMap;
import com.google.android.gms.wearable.DataMapItem;
import com.google.android.gms.wearable.Wearable;
import com.google.android.gms.wearable.WearableListenerService;
public class WatchListener_service extends WearableListenerService {
#Override
public void onCreate() {
super.onCreate();
GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onDataChanged(DataEventBuffer dataEventBuffer) {
Log.d("prijato","number is: ");
for (DataEvent dataEvent : dataEventBuffer) {
if (dataEvent.getType() == DataEvent.TYPE_CHANGED) {
DataMap dataMap = DataMapItem.fromDataItem(dataEvent.getDataItem()).getDataMap();
String path = dataEvent.getDataItem().getUri().getPath();
if (path.equals("/number")){
int number = dataMap.getInt("numa");
long time = dataMap.getInt("timestamp");
Log.d("received","number is: " + number);
}
}
}
}
}
However, onDataChanged method in WatchListener_service isn't called. onResult method inside ResultCallbacks print "Succes" so it seems that DataItem is send correctly.
I already find many similar problems on Stackoverlflow so I checked all these things:
Both modules has same applicationId
Both modules use 'com.google.android.gms:play-services-wearable:9.0.0'
SetUrgent is used to putDataRequest so there shouldnt be any delay.
WearableListenerService has declared correct intent filter in Manifest :
action android:name="com.google.android.gms.wearable.DATA_CHANGED"
data android:scheme="wear" android:host="*"
Both phone and Wear app run on physical device. My question is... What should I do to fix this issue?
Thanks
Check if both apps have the same debug key. I had some problems with that and problem was different keys for both apps (wear and mobile).
PS: The Android Wear API is ridiculous. I quit developing for Wear because of how terrible is that API that doest not work as they say this should.

Update JavaFX 2 GUI at intervals?

I've spent like the last 24 hours trying to learn JavaFX. I'm trying to build a GUI that will display values from a data source (for example a database). My question is what the preferred way is to do this. So far I've come up with this code to build a simple GUI and get some data from a data source:
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class AvcHmi extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
Text t = new Text(10, 50, "Replace/update this text periodically with data");
Group root = new Group();
root.getChildren().add(t);
primaryStage.setScene(new Scene(root, 400, 300));
primaryStage.show();
new Thread() {
private DataSource dataSource = new DataSource();
{ setDaemon(true); }
#Override
public void run() {
try {
for(;;) {
Thread.sleep(100);
Platform.runLater(new Runnable() {
#Override
public void run() {
System.out.println(dataSource.getDataMap().get("key1"));
}});
}
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}
}
Datasource:
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class DataSource {
Map<String,String> dataMap = new HashMap<>();
public DataSource() {
dataMap.put("key1", "value1");
dataMap.put("key2", "value2");
dataMap.put("key3", "value3");
}
public Map<String, String> getDataMap() {
Random generator = new Random();
int randInt = generator.nextInt();
dataMap.put("key1", "value"+randInt);
return dataMap;
}
}
100 ms is OK interval to update this GUI as far as I'm concerned. But is this a viable solution?
The next step is to replace the text with a value from the data source. Been looking at Collections and ObservableMap and wondering if it's a preferred way of doing the actual GUI updates? I'm aving some problems with inner classes and final variables but might reason that out after some sleep.
Also, the target machine is not that powerful (somewhere between 350-512 mb RAM). Could this be an issue? My simple tests so far seems to run fine.
Thank you for any feedback on this.
This Oracle example shows how to achieve concurrency loading in data table, with source code; it might help you
You could also look at reading about javafx.concurrent.Task<V> API.
The code on the Oracle example is as follows:
public class UpdateCustomerTask extends Task<Customer> {
private final Customer customer;
public UpdateCustomerTask(Customer customer) {
this.customer = customer;
}
#Override protected Customer call() throws Exception {
// pseudo-code:
// query the database
// read the values
// Now update the customer
Platform.runLater(new Runnable() {
#Override public void run() {
customer.setF setFirstName(rs.getString("FirstName"));
// etc
}
});
return customer;
}
}

nokia device vibration in a game using j2me

I want to make my phone vibrate when my game ends. I tried using
Display display = Display.getDisplay(midlet);
display.vibrate(2000);
but display.vibrate(2000) returns false and the device does not vibrate.
Can anyone help.
I am trying it on Nokia C7 device. (Symbian^3)
According to Display.vibrate documentation "The return value indicates if the vibrator can be controlled by the application." If you are calling vibrate during destroyApp the VM might be ignoring the vibrate request.
Try calling Display.vibrate before you call MIDlet.notifyDestroyed
Try this code and see if it works.
It worked for me on nokia e63
package ravi.vibrationClass;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class Vibrate extends MIDlet implements CommandListener{
Form form;
Display disp;
Command vib,exit;
public void startApp() {
form = new Form("Vibration");
disp = Display.getDisplay(this);
exit = new Command("Exit", Command.EXIT, 1);
vib = new Command("Vibrate", Command.OK, 1);
form.append("Press \"vibrate\" to make the phone vibrate");
form.addCommand(vib);
form.addCommand(exit);
form.setCommandListener(this);
disp.setCurrent(form);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
notifyDestroyed();
}
public void commandAction(Command c, Displayable arg1) {
if(c == vib){
disp.vibrate(125);
}else if(c == exit){
destroyApp(true);
}
}
}

How to show parent midlet from another java program in j2me

I am developing a j2me application where there is one parent midlet which calls other java programs. Parent midlet is of implicit list which contains 4 elements. On clicking any of the elements an appropriate java program is called. Everything is working fine, but i don't understand how to show parent midlet from java program on clicking of back button.
Please provide examples.
this is my parent midlet code
package hello;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;
public class Contacts extends MIDlet implements CommandListener,Runnable {
Display display=null;
private Form form=new Form("Contacts");
private List menu=new List("Contact Menu",Choice.IMPLICIT);
private Command exit = new Command("Exit", Command.EXIT, 2);
private Command ok=new Command("Ok",Command.SCREEN,1);
private Command back = new Command("Back", Command.BACK, 1);
private Alert alert;
public Contacts()
{
display = Display.getDisplay(this);
try{
menu.append("Add Contact", Image.createImage("/contact_new.png"));
menu.append("Delete Contact",Image.createImage("/delete-icon.png"));
menu.append("Get Contact",Image.createImage("/document-edit.png"));
menu.append("View Contacts",Image.createImage("/view.png"));
menu.addCommand(ok);
menu.addCommand(exit);
menu.setCommandListener(this);
}
catch(IOException ie)
{
}
}
public void startApp() {
display.setCurrent(menu);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command command, Displayable displayable) {
if (command == exit) {
destroyApp(true);
notifyDestroyed();
return;
}
switch (menu.getSelectedIndex ()) {
case 0:
new ac (this);//call to java program
break;
case 1:
new dc (this);
break;
case 2:
new gc(this);
break;
case 3:
new vc(this);
break;
default:
System.err.println ("Unexpected choice...");
break;
}
}
}
I don't know any API in standard J2ME to interact between MIDlets. At least that is already released. There is some Nokia private API to do some such kind of operations.

Resources