How to read Android switch widget - switch-statement

I added an andriod switch widget to my graphic.xml file in andriod, and it moves and changes color so the widget works, but I dont know how to read the value, it is on/off switch so I would expect off=0 and on=1 however when I look at the switch.java file I do not see and GetSwitchValue or SetSwitchValue type method in this library. how do I actually read the value?

You can set setOnCheckedChangeListener as following:
((Switch)findViewById(R.id.switchId)).setOnCheckedChangeListener(
new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
Everytime switch is toggled, isChecked parameter contains the updated value.Based on the isChecked boolean 0/1 can be returned.

Related

What to do with the boolean return of the OnTouchListener (MapView)?

I'm working on an app that uses a MapView instance called map. At a certain point I want to know if the map has been touched. To that purpose Android Studio generated this boolean return callback method (see below) for the OnTouchListener.
MapView map;
map = findViewById(R.id.view_map);
map.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch (View v) {
return false;
}
});
As you can see, unlike in a simple OnClickListener, you are apparently not free to write the method that should follow a touch event. That method appears to be fixed at return false. You cannot change it to e.g. a void method.
What is the purpose of that return? To where/what will false be returned? Is it perhaps stored in the object map, as a field of the MapView class? If I knew, I could initialize that field/variable to true, wait for the OnTouchListener to change it to false, and then use that information elsewhere in the app (e.g. to suspend the app's instruction to continuously center the map on the current GPS position).

Action listeners not firing

I've been developing with codenameone for over a year, and I never ran into this problem before, I feel like I'm losing my mind. I just redesigned one part of an app I'm working on, and now the ActionListeners aren't firing. I'm attaching them to a Button and a SpanButton in the code:
ActionListener goToDoc = new ActionListener() {
String mDocId = docId;
#Override
public void actionPerformed(ActionEvent evt) {
mStateMachine.currentExpertId = mDocId;
mStateMachine.showForm("DoctorDetails", null);
}
};
name.addActionListener(goToDoc);
Util.downloadImageToStorage(mStateMachine.URL_PREFIX+"images/doctors/"+(String)value.get("doc_pic"),
"doc_post_pic_"+(String)value.get("doc_id")+".png", new Callback<Image>() {
#Override
public void onSucess(Image img) {
pic.setIcon(img.scaledWidth(mStateMachine.getProportionalWidth(.23)));
StateMachine.applyGreenBorder(pic);
pic.addActionListener(goToDoc);
pic.getParent().revalidate();
}
#Override
public void onError(Object sender, Throwable err, int errorCode, String errorMessage) {
System.out.println("Unable to download expert profile picture");
}
});
When I debug the code, the components do show that the ActionListener is attached, but the actionPerformed method is never reached, no matter how many times I click on the buttons. I experience this problem both on the simulator and on an Android device. I have yet to test on an iPhone.
Did you set a parent to be a lead component or focusable?
The reason the click event wasn't firing was because the Components weren't enabled, possibly a bug in the BUI Builder. After checking off the 'Enabled' and 'Focusable' checkboxes in the GUI Builder, and seeing they were unchecked every time I went back to that form, I just used component.setFocusable(true) and component.setEnabled(true) in the code, and it worked fine after that.

Persistent booleans Android Studio

I've been poking around the web (including SO), and have found lots of information on having persistent data. I've found strings, ints, doubles, calendars, just about everything. The ones I haven't seen a specific guide or tutorial for are booleans.
I've created an app which has a switch located on the main activity. I do not have a settings button, window, or even a pane, because the entire app is accessed from the main activity. I want to have the switch be persistent as well as the affects it holds (ie, when the app is closed, it will remember if the user disable or enable the vibrate function).
I have the switch to work where it does enable the vibration depending on which position the switch is in. I can't seem to get the switch to remain in the off position when the app is recreated.
Here's my code to save:
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_main);
dBell = MediaPlayer.create(this, R.raw.doorbell);
if ((bundle != null) && (bundle.getBoolean("vibetoggle") != false)) {
vibeOn = false;
} else {
vibeOn = true;
}
}
protected void onRestoreInstanceState(Bundle bundle) {
super.onRestoreInstanceState(bundle);
vibeOn = bundle.getBoolean("vibetoggle");
}
protected void onSaveInstanceState(Bundle bundle) {
super.onSaveInstanceState(bundle);
bundle.putBoolean("vibetoggle", vibeOn);
}
public void onToggleClicked(View view) {
Vibrator vibe = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibeOn = ((Switch) view).isChecked();
if (vibeOn) {
vibe.vibrate(100);
} else {
// No vibrate
}
}
public void playSound(View view) {
dBell.start();
if (vibeOn) {
Vibrator vibe = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibe.vibrate(300);
} else {
// No vibrate
}
}
The shorter duration vibrate (100ms) is occurs when the switch is flipped from disabled to enabled. The longer one is what actually causes the button to vibrate when clicked.
I've kind of gotten the boolean logic to work, but the IO switch would still be set to default and wouldn't function correctly until it had been switched. The issue I have regarding the switch, is that I want the switch to be in the correct position when loaded (ie, if the boolean is saved false, then the switch will load in the off position). I can't figure out how to make the two communicate. I would assume the switch would have to change based on the boolean, rather than the other way around. I just can't figure out how to make the xml switch communicate with the one I have in java and visa versa.
Here's the xml code for the switch:
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Vibration"
android:id="#+id/switch1"
android:layout_alignBottom="#+id/dBellButton"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:clickable="true"
android:checked="true"
android:onClick="onToggleClicked" />
I know the android:checked="true" causes the switch to be created in a default on position. I tried making a new boolean inside of the values xml (so rather than the code saying android:checked="true", it would say something along the lines of android:checked="#bool/vibeConvert), but found I didn't know how to edit the boolean through the java when it was there as well.
I've tried a few different methods to get this data to be persistent, but none of them worked for me. If I could get some help with persistent data, specifically regarding booleans, that would be fantastic.
EDIT: showing my attempt to use SharedPreferences.
protected void onRestoreInstanceState(Bundle bundle) {
super.onRestoreInstanceState(bundle);
vibeOn = bundle.getBoolean("vibetoggle");
// preferenceSettings = getPreferences(PREFERENCE_MODE_PRIVATE);
// vibeOn = preferenceSettings.getBoolean("on", true);
}
protected void onSaveInstanceState(Bundle bundle) {
super.onSaveInstanceState(bundle);
bundle.putBoolean("vibetoggle", vibeOn);
// preferenceSettings = getPreferences(PREFERENCE_MODE_PRIVATE);
// preferenceEditor = preferenceSettings.edit();
// preferenceEditor.putBoolean("on", vibeOn);
// preferenceEditor.apply();
}
I'm not quite sure how how to use the SharedPreferences, and I couldn't find anywhere which specified where to place them. They are commented out here for obvious reasons. Not sure where to go from here.
Thanks!
Nathan
EDIT:
I tried using the following code:
public static final String PREFS_NAME = "MyPrefsFile";
MediaPlayer dBell;
boolean vibeOn;
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_main);
dBell = MediaPlayer.create(this, R.raw.doorbell);
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean vibeSave = settings.getBoolean("vibeSave", vibeOn);
vibeOn = vibeSave;
Switch ("+id/switch1") = vibeSave;
}
#Override
protected void onStop() {
super.onStop();
// Let Editor make preference changes
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("vibeSave", vibeOn);
editor.commit();
}
Here's my XML:
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Vibration"
android:id="#+id/switch1"
android:layout_alignBottom="#+id/dBellButton"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:clickable="true"
android:checked="true"
android:onClick="onToggleClicked" />
I'm not sure if:
The boolean value is being saved.
The switch can be edited inside of the java code.
I've tried to play with the idea with the following line of code: Switch ("+id/switch1") = vibeSave;, but that didn't work. I'm not sure how to proceed from here. I want my XML to be able to start in the correct position based on the value in the boolean, but I'm not sure how to make my XML and my java talk to each other.
You can use SharedPreferences to store primitive values.
The best place to do this, is right after the value is changed.
So add the saving to the logic of your switch listener, and the loading to the logic of your switch initializer.
To get a SharedPreferences object for your application, use one of two
methods:
getSharedPreferences() - Use this if you need multiple preferences
files identified by name, which you specify with the first parameter.
getPreferences() - Use this if you need only one preferences file for
your Activity. Because this will be the only preferences file for your
Activity, you don't supply a name.
To write values:
Call edit() to get a SharedPreferences.Editor.
Add values with methods such as putBoolean() and putString().
Commit the new values with commit()
To read values, use SharedPreferences methods such as getBoolean() and getString().
The code in your onCreate should look something like this:
#Override
protected void onCreate(Bundle bundle) {
(...)
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean vibeSave = settings.getBoolean("vibeSave", false);
Switch switch = (Switch) findViewById(R.id.switch1);
switch.setChecked(vibeSave);
}

What is the proper way to handle a screen rotation and the media route button and the existing session?

The example on https://developers.google.com/cast/cast_2nd-screen_app_tutorial shows a onDestroy method which calls unregisterMediaRouteProvider. This causes the MediaRouter.Callback.onRouteUnselected method to get called which in turn ends the session. This leads to the app getting disconnected from the chromecast device and the MediaRouteButton stops being blue. Below is the onDestroy method from the example:
#Override
protected void onDestroy() {
MediaRouteHelper.unregisterMediaRouteProvider(mCastContext);
mCastContext.dispose();
super.onDestroy();
}
So my question is, what is the proper way to handle screen rotation when using the chromecast device from an app?
You can try using isFinishing() method of Activity to figure out if onDestroy is called due to application really "finishing" or is called for other reasons. Another option is to handle orientation change yourself.
You can see the guidelines for handling setup/destruction of the Chromecast (such as when orientation change is happening) on https://developers.google.com/cast/docs/android_sender
The relevant sections of code are the following ones:
#Override
protected void onResume() {
super.onResume();
mMediaRouter.addCallback(mMediaRouteSelector, mMediaRouterCallback,
MediaRouter.CALLBACK_FLAG_REQUEST_DISCOVERY);
}
#Override
protected void onPause() {
if (isFinishing()) {
mMediaRouter.removeCallback(mMediaRouterCallback);
}
super.onPause();
}
And also the following code:
#Override
protected void onStart() {
super.onStart();
mMediaRouter.addCallback(mMediaRouteSelector, mMediaRouterCallback,
MediaRouter.CALLBACK_FLAG_REQUEST_DISCOVERY);
}
#Override
protected void onStop() {
mMediaRouter.removeCallback(mMediaRouterCallback);
super.onStop();
}
It is also a good idea to have a boolean value in your program, for instance "wasLaunched" or "isConnected" to keep track of whether the connection to the chromecast is active or not. I use this variable in my code to check if I can send messages to the receiver or not. Then simply remember to save this variable and restore it when there is an orientation change on the device. This works for me in my chromecast enabled app. The code for saving/restoring my variable, so it survices orientation change is shown below:
protected void onSaveInstanceState(Bundle bundle) {
if (bundle!=null)
{
bundle.putBoolean("wasLaunched", wasLaunched);
}
super.onSaveInstanceState(bundle);
}
protected void onRestoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState!=null)
{
wasLaunched = savedInstanceState.getBoolean("wasLaunched");
}
super.onRestoreInstanceState(savedInstanceState);
};
Of course you can also put other stuff in your bundle that needs to survive an orientation change. I am not using the onDestroy override you describe there, nor is it mentioned in the google documentation I link to. But I use the teardown() method described in that document I link to for cleaning up, but this only happens when I close the connection, because I dont want to close the connection to the chromecast upon orientation change.

How can I develop a custom "non-fullscreen" softkeyboard for tablets?

I have the sample of softkeyboard. When I install it on a android 2.x, it has the following non-fullscreen view:
But when I install it on tablet 10in it gets whole of the screen like this:
How can I change the sample to have a non-fullscreen custom keyboard on tablet pcs like this image (default keyboard of tablet)?
The following code in InputMethodService solved my problem:
#Override
public boolean onEvaluateFullscreenMode() {
return false;
}
overide the following two methods from InputmethodService as bellow, this works always
#Override
public void onUpdateExtractingVisibility(EditorInfo ei) {
// TODO Auto-generated method stub
setExtractViewShown(false);
}
#Override
public boolean onEvaluateFullscreenMode() {
return false;
}
This worked for me :) and if you want to show keyboard in fullscreen mode always then change both false to true.

Resources