stop application with TIMER AND TIMERTASK - timer

I am doing my app on android, when I run my application I can see the screen but when I give click show the message "THE APLICATION STOP", when i give click automatically run each time a random where the number that shown a color. I am using Timer and TimerTask.
public class HolaMundo extends AppCompatActivity {
ImageView fondoImg;
Button entrada;
int valorfinal;
TimerTask tareatiempo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hola_mundo);
fondoImg=(ImageView)findViewById(R.id.fondoPantalla);
entrada=(Button)findViewById(R.id.btnEncen);
final Timer tarea=new Timer();
entrada.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tareatiempo = new TimerTask() {
#Override
public void run() {
busqueda();
}
};
tarea.scheduleAtFixedRate(tareatiempo,0,5000);
}
});
}
public void busqueda()
{
valorfinal=(int)(Math.random()*4+1);
switch (valorfinal)
{
case 1:
fondoImg.setImageResource(R.drawable.amarillo);
break;
case 2:
fondoImg.setImageResource(R.drawable.negro);
break;
case 3:
fondoImg.setImageResource(R.drawable.rojo);
break;
case 4:
fondoImg.setImageResource(R.drawable.verde);
break;
}
}

Related

android studio change color on click infinite loop

so i trying to make a button that on ever click is change color in that order red yellow green and the
it repeat itself and it dosnt work for my do you got tips for my ??
enter code here
package com.example.colorbender;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//for need to be not ending need to be infinite loop
for (int i = 0; i < 10; i++) {
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btn.setBackgroundColor(Color.parseColor("red"));
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btn.setBackgroundColor(Color.parseColor("YELLOW"));
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btn.setBackgroundColor(Color.parseColor("green"));
}
});
}
});
}
});
}
}
}
so sould i try different way or sould i work on my loop becouse it the only thing that dosnt work in my code
sorry about my eng and have a great day :)
public class MainActivity extends AppCompatActivity {
protected Button btn;
protected int count;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
count = 0;
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
switch(count % 3) {
case 0:
btn.setBackgroundColor(Color.RED);
case 1:
` btn.setBackgroundColor(Color.YELLOW);
case 2:
btn.setBackgroundColor(Color.GREEN);
}
count ++;
}
}
}
}

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

Why do i never enter in specific callback functions in native interface?

I'm making an application which has to detect a bluetooth card reader and if a card is inserted or removed from this one.
I'm using an API for the android part in my native interface so I implement two callback functions from an interface which concerns the bluetooth card reader detection and two other callback functions which concerns the detection of cards in the bluetooth card reader.
Two callback functions which are called when the bluetooth card reader is detected and the two others which are called when a card is inserted or removed from the device.
I have no problem with the callback which are called when the bluetooth card reader is detected but the application never calls the functions which must be called when the card are inserted or removed.
public class FtReaderNativeImpl implements BluetoothRead.CardListener,BluetoothRead.ReaderListener{
private BluetoothRead btRead;
ArrayList<BluetoothDevice> listRead;
public String scanBluetooth(){
String chaine ="";
if (Looper.myLooper() == null)
{
Looper.prepare();
}
Log.p("btread avant init:"+btRead);
btRead = new
BluetoothRead(com.codename1.impl.android.AndroidNativeUtil.getContext());
btRead.setCardListener(this);
btRead.setReaderListener(this);
ReturnCode rc = btRead.btInitLib();
Log.p("btread après init:"+btRead);
Log.p("rc:"+rc);
return chaine;
}
#Override
public void CardInserted()
{
//showMessage("onCardInserted");
String chaine="";
//Toast.makeText(com.codename1.impl.android.AndroidNativeUtil.getActivity(), "INSERTED", Toast.LENGTH_SHORT).show();
chaine+=btRead.getName();
chaine+=btRead.getFirstName();
eidReader.showDialog("INSERTED "+chaine);
Log.p("btInsertOK");
}
#Override
public void CardRemoved()
{
String chaine="";
//Toast.makeText(com.codename1.impl.android.AndroidNativeUtil.getActivity(), "REMOVED", Toast.LENGTH_SHORT).show();
EidReader.showDialog("REMOVED "+chaine);
Log.p("btRemoveNOK");
}
#Override
public void ReaderConnected(BluetoothDevice bluetoothDevice)
{
/*Toast.makeText(com.codename1.impl.android.AndroidNativeUtil.getActivity(), "CONNECTED", Toast.LENGTH_SHORT).show();*/
EidReader.showDialog("CONNECTED");
Log.p("onReaderConnected: " + bluetoothDevice.getName());
if (btRead.btOpen(bluetoothDevice) == ReturnCode.OK) {
Log.p("btOpen OK");
} else {
Log.p("btOpen NOK");
}
Log.p("btread après listener:"+btRead);
}
#Override
public void ReaderDisconnected(BluetoothDevice bluetoothDevice)
{
//Toast.makeText(com.codename1.impl.android.AndroidNativeUtil.getActivity(), "DISCONNECTED", Toast.LENGTH_SHORT).show();
EidReader.showDialog("DISCONNECTED");
}}
ScanBluetooth is just a initialization method which is called in the beginning of the form:
public class EidReader extends Form implements HasLogger {
Container loggatt = new Container();
private Bluetooth bt;
private static Container devicesCnt;
private Map devices = new HashMap();
Form main = this;
FtReaderNative frn;
public EidReader(Form parent)
{
this.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
Display dis = Display.getInstance();
frn = (FtReaderNative)NativeLookup.create(FtReaderNative.class);
if(dis.getPlatformName().compareTo("and")==0){
LocationManager lm = LocationManager.getLocationManager();
}
bt = new Bluetooth();
frn.scanBluetooth();
//combo.setRenderer(new GenericListCellRenderer<>(new MultiButton(),new MultiButton()));
this.add(new Button(new Command("enable bluetooth")
{
#Override
public void actionPerformed(ActionEvent evt){
try {
if (!bt.isEnabled()) {
bt.enable();
}
if (!bt.hasPermission()) {
bt.requestPermission();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}));
this.add(new Button(new Command("initialize")
{
#Override
public void actionPerformed(ActionEvent evt)
{
try {
bt.initialize(true, false, "bluetoothleplugin");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}));
Button bttest = new Button("DISPLAY READER");
bttest.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ev)
{
DeleteUI();
StringTokenizer st = new StringTokenizer(frn.infoDevices());
while (st.hasMoreTokens()) {
MultiButton mb = new MultiButton(st.nextToken());
mb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
devicesCnt.add(new SpanLabel(frn.readerStatus( mb.getTextLine1())));
}});
devicesCnt.add(mb);
}
}
});
this.add(bttest);
devicesCnt = new Container(new BoxLayout(BoxLayout.Y_AXIS));
devicesCnt.setScrollableY(true);
this.add(devicesCnt);
this.show();
}
private void DeleteUI()
{
devicesCnt.removeAll();
devicesCnt.revalidate();
}
#Override
public String getLogName()
{
// TODO Auto-generated method stub
return null;
}
public static void showDialog(String txt)
{
//Display.getInstance().callSerially(()->
//{
devicesCnt.add(new SpanLabel(txt));
devicesCnt.forceRevalidate();
//});
}
}

i am trying to autoconnect to bluetooth and return back from bluetooth settings to main activity ?can any one help me?

hello i am trying to autoconnect to bluetooth and return back to main activity,but i am not able to auto connect and return back from current activity to main activty....
Of course if there are more easy ways to do it I would appreciate it very much.
here is code==>
public class SimpleUiActivity extends Activity {
private static final String TAG = SimpleUiActivity.class.getSimpleName();
private static final int RESULT_OK = 1;
private static final int RQS_IMAGE = 2;
private static final int RQS_I = 3;
private BluetoothAdapter BA;
private Map<String, Gpio> mGpioMap = new LinkedHashMap<>();
Button ble;
Button campre;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
LinearLayout gpioPinsView = (LinearLayout) findViewById(R.id.gpio_pins);
LayoutInflater inflater = getLayoutInflater();
PeripheralManagerService pioService = new PeripheralManagerService();
for (String name : pioService.getGpioList()) {
View child = inflater.inflate(R.layout.list_item_gpio, gpioPinsView, false);
Switch button = (Switch) child.findViewById(R.id.gpio_switch);
button.setText(name);
gpioPinsView.addView(button);
Log.d(TAG, "Added button for GPIO: " + name);
try {
final Gpio ledPin = pioService.openGpio(name);
ledPin.setEdgeTriggerType(Gpio.EDGE_NONE);
ledPin.setActiveType(Gpio.ACTIVE_HIGH);
ledPin.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);
button.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
try {
ledPin.setValue(isChecked);
} catch (IOException e) {
Log.e(TAG, "error toggling gpio:", e);
buttonView.setOnCheckedChangeListener(null);
// reset button to previous state.
buttonView.setChecked(!isChecked);
buttonView.setOnCheckedChangeListener(this);
}
}
});
mGpioMap.put(name, ledPin);
} catch (IOException e) {
Log.e(TAG, "Error initializing GPIO: " + name, e);
// disable button
button.setEnabled(false);
}
//-----------------
ble=(Button)findViewById(R.id.autobluetooth);
ble.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
ble.postDelayed(new Runnable() {
#Override
public void run() {
BA = BluetoothAdapter.getDefaultAdapter();
BA.enable();
Intent intent=new Intent(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS);
Log.i("aaa","i am here");
// startActivityForResult(intent, RQS_IMAGE);// Activity is started with requestCode 2
finish();
}
}, 10000);
}
});
//-----------------
//-----------------
campre=(Button)findViewById(R.id.camerapreview);
campre.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent1=new Intent(SimpleUiActivity.this,MainActivity.class);
startActivityForResult(intent1, RQS_I);// Activity is started with requestCode 3
}
});
//----------------
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==RESULT_OK) {
switch (requestCode) {
case RQS_IMAGE:
Log.i("abc", "i am here");
Toast.makeText(getApplicationContext(), "Bluetooth switched ON", Toast.LENGTH_LONG).show();
finish();
// textsource.setText(source.toString());
break;
case RQS_I:
break;
}
}
}
#Override
protected void onDestroy() {
super.onDestroy();
for (Map.Entry<String, Gpio> entry : mGpioMap.entrySet()) {
try {
entry.getValue().close();
} catch (IOException e) {
Log.e(TAG, "Error closing GPIO " + entry.getKey(), e);
}
}
mGpioMap.clear();
}
}

Unable to display toast messages

I have download and use the code form the following URL
https://github.com/Pmovil/Toast to display toast message.
Initially I got NativeToastImpl Not implemented error. I have resolved by coping the native related code to my project. Now the System throws Runtime Exception "Toast is not supported in this platform."
Here is my code to display toast message.
public class MyApplication {
private Form current;
private static Object context;
public void init(Object context) {
MyApplication.context = context;
}
public static Object getContext() {
return context;
}
public void start() {
if (current != null) {
current.show();
return;
}
showLoginForm();
}
public void stop() {
current = Display.getInstance().getCurrent();
}
public void destroy() {
}
private void showLoginForm() {
Form form = new Form("WelCome ...");
Button b = new Button(" Login ");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Log.p(" Came hgere ");
Log.p(" *** " + MyApplication.getContext());
Toast.makeText(MyApplication.getContext(), "HI", Toast.LENGTH_LONG);
}
});
form.addComponent(b);
form.show();
}}
I have used Net Beans IDE for development, OS : windows 8.1
Please let me know I am doing wrong in this code and
Is there any other way to display toast messages using codename one?.
Thanks in advance
please edit the following code and please test the toast in device . Toast is not available in emulator.
public void init(Object context) {
this.context = context;
}
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Log.p(" Came hgere ");
Toast.makeText(context, "HI", Toast.LENGTH_LONG);
}
});
You missed the show() method on Toast.
Toast.makeText(MyApplication.getContext(), "HI", Toast.LENGTH_LONG).show();

Resources