I'm writing an app and I'm not really getting anywhere.
I have a class called SettingsFragmentForBLT that derives from PreferenceFragmentCompat. In it I handle user input from onPreferenceChange. Here you have the option of making settings for the Bluetooth device with which the smartphone is already paired when the class is called up. I rule the BLT matters in the class called DeviceControlActivity.
I need to expose THE handling object from DeviceControlActivity in the SettingsFragmentForBLT class so that I can pass the data to the BLT device at the time of input from the user. As far as I know, I have to overload the constructor of the DeviceControlActivity for this. My attempt refers to this website:
https://sciodoo.de/konstruktor-im-java-programm-ein-objekt-uebermachen/#
Here is the code from the SettingsFragmentForBLT class:
public static class SettingsFragmentForBLT extends PreferenceFragmentCompat implements
Preference.OnPreferenceChangeListener {
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
addPreferencesFromResource(R.xml.blt_preferences);
// A listener is used to monitor preference changes in PreferencFragmnt (BLT).
Preference preferenceFeedbackIstAn = findPreference("FeedbackIstAn");
preferenceFeedbackIstAn.setOnPreferenceChangeListener(this);
Preference preferenceSwitchfeedback = findPreference("seek_bar_key");
preferenceSwitchfeedback.setOnPreferenceChangeListener(this);
}
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String preferenceKey = preference.getKey();
DeviceControlActivity deviceControlActivity = new DeviceControlActivity();
DeviceControlActivity msBluetoothLeService = new deviceControlActivity.getmBluetoothLeService(deviceControlActivity);
// BluetoothLeService mBluetoothLeService
Boolean switchOn = (boolean) newValue;
if (preferenceKey.equals("FeedbackIsAn")) {
deviceControlActivity.toggleLEDGren();
Log.w(TAG, "preferenceValue: " + newValue);
if (switchOn) {
if (msBluetoothLeService != null) {
msBluetoothLeService.writeCustomCharacteristic(53);
Log.w(TAG, "Green has been turned on");
}
...
Here is the code from DeviceControlActivity:
public class DeviceControlActivity extends AppCompatActivity{
...
public DeviceControlActivity(BluetoothLeService mBluetoothLeService) {
this.mBluetoothLeService = mBluetoothLeService;//Assignment with this
}
public void getmBluetoothLeService(DeviceControlActivity createdObject){
this.mBluetoothLeService = createdObject.mBluetoothLeService;
}
...
Thank you for your support and I wish you a pleasant time
I tried to create an object from DeviceControllActivity class in SettingsFragmentForBLT class
Related
I extended android.widget.Spinner. and added an int field to my implementation. Now I want it to save the field value on orientation change. My first thought was using Bundle object for that:
override fun onSaveInstanceState(): Parcelable {
val bundle = Bundle()
bundle.putParcelable(SUPER_STATE, super.onSaveInstanceState())
bundle.putInt(PREV_ITEM, this.prevItem) // ... save stuff
return bundle
}
override fun onRestoreInstanceState(state: Parcelable?) {
val newState: Parcelable
if (state is Bundle) {
this.prevItem = state.getInt(PREV_ITEM) // ... load stuff
newState = state.getParcelable<Parcelable>(SUPER_STATE)
super.onRestoreInstanceState(newState)
}
super.onRestoreInstanceState(state)
}
But I get an error:
java.lang.ClassCastException: android.os.Bundle cannot be cast to android.widget.Spinner$SavedState
So I found Spinner source code and figured out that I have to extend inner static class SavedState and use it to save my field value. But I wasn't able to do that. Android Studio suggests that it "Cannot resolve symbol 'Saved State'".
So what do I do to save the state of my custom Spinner?
You cannot actually extend Spinner.SavedState because it created inside Spinner class. Even if you try to override Spinner.onSaveInstanceState you cannot implement this method in your custom class, because you don't have access to private variables of Spinner class.
What you can actually do is to create new class implementing Parcelable and use value returned from base class to construct your own class.
#Override
public Parcelable onSaveInstanceState() {
final MySavedState ss = new MySavedState(super.onSaveInstanceState());
ss.myInt = 100;
return ss;
}
#Override
public void onRestoreInstanceState(Parcelable state) {
MySavedState ss = (MySavedState) state;
super.onRestoreInstanceState(ss.getSuperState());
if(ss.myInt == 100) {
Log.d("TAG", "Success!");
}
}
static class MySavedState extends Spinner.BaseSavedState {
int myInt;
public MySavedState(Parcelable superState) {
super(superState);
}
public MySavedState(Parcel source) {
super(source);
myInt = source.readInt();
}
}
I have a TreeViewer with Object which I want to show information in the default PropertiesView in Eclipse.
I created an AdapterFactory which implements the IAdapterFactory Interface with the Override method:
#Override
public Object getAdapter(Object adaptableObject, Class adapterType)
{
if(adapterType == IPropertySource.class && adaptableObject instanceof UATreeNode)
{
return new UATreeNodeAdapter((UATreeNode) adaptableObject);
}
return null;
}
Then I created an adapter which implements the IPropertySource Interface with my own PropertyDescriptors, for example:
public static final String OBJECT_ID_ACCESSLEVEL = "Obj.accessLevel";
private static final String OBJECT_LABEL_ACCESSLEVEL = "AccessLevel";
protected PropertyDescriptor objectAccessLevelDescriptor = new PropertyDescriptor(OBJECT_ID_ACCESSLEVEL, OBJECT_LABEL_ACCESSLEVEL);
#Override
public IPropertyDescriptor[] getPropertyDescriptors()
{
return new IPropertyDescriptor[] { objectAccessLevelDescriptor };
}
#Override
public Object getPropertyValue(Object id)
{
if(id.equals(OBJECT_ID_ACCESSLEVEL))
return uaTreeNode.getAccessLevel();
}
I got more of those PropertyDescriptors and now I want to show some of them only if the "Show Advanced Properties" menu button in the PropertiesView is activated.
So my question, is this possible to do, if so what do I have to implement to show my Properties only if "Show Advanced Properties" is activated?
Call the PropertyDescriptor.setFilterFlags method to set the expert filter property:
PropertyDescriptor desc = ...
desc.setFilterFlags(new String [] {IPropertySheetEntry.FILTER_ID_EXPERT});
I'm new to Java, I'm trying to build something in Android Studio.
The point is to 'push' a value for TextView baseTickVar in class BaseScreen, from another PACKAGE, where the class CoreFunctionality resides. Each time the tickNumber increases I want that shown in the TextView, so it's not a one time setting of text.
I have tried interfaces, but interfacing won't allow variables, only constants.
I've tried TextView.setText from the CoreFunctionality package, but that gave a nullpointerException and declaring the TextView to counter that didn't seem to help.
public class BaseScreen extends Activity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base_screen);
// some irrelevant code here so i left it out.
TextView baseTickVar = (TextView)findViewById(R.id.baseTickVar);
baseTickVar.setText("1"); // just to not have it empty...
}
Now I want to set value of baseTickVar with a variable from the other package CoreFunctionality
public class CoreFunctionality extends Activity implements Runnable {
Thread tickThread = null;
volatile boolean playingGalactic;
long lastTick;
public int tickNumber;
int tickLength;
TextView baseTickVar;
public void controlTicks() {
tickLength = 2000;
long timeThisTick = (System.currentTimeMillis() - lastTick);
long timeToWait = tickLength - timeThisTick;
if (timeToWait > 0) {
try {
tickThread.sleep(timeToWait);
} catch (InterruptedException e) {
}
}
lastTick = System.currentTimeMillis();
}
#Override
public void run() {
while (playingGalactic) {
controlTicks();
tickNumber++;
Log.i("Tick number ", "" + tickNumber);
updateTick();
}
}
private void updateTick() {
// this is the whole point...
baseTickVar.setText("" + tickNumber);
}
public void resume() {
playingGalactic = true;
tickThread = new Thread(this);
tickThread.start();
}
I guess your BaseScreen is the main screen and CoreFunctionality is some component that is doing some work. Actually CoreFunctionality does not need to be Activity, it better fits to be a service.
You have to somehow pass reference to baseTickVar to the CoreFunctionality.
It is not allowed to mess with UI elements (such as TextView) from within another thread. You should consider using some inter-thread communication (such as Message).
Make BaseScreen to extend Handler or make a Handler object in it then override
public void handleMessage(Message msg) {
baseTickVar.setText("" + msg.obj);
}
In CoreFunctionality
private void updateTick() {
Message msg=new Message();
msg.obj=tickNumber;
h.sendMessage(msg);
}
Of course you'll have to pass the h reference to CoreFunctionality.
Maybe not 100% accurate but it should work with little tweaking.
Hope this will help.
I have a very strange problem with a java class in my android application.
I have some sub classes which extend my abstract class GameDialog
GameDialog class
public abstract class GameDialog extends Sprite
{
private static boolean gd_visible = false;
protected GameDialog(GameScene scene, Camera camera, VertexBufferObjectManager pSpriteVertexBufferObject){
...
}
public boolean display(){
if(!GameDialog.gd_visible) {
...
}
}
protected boolean hide(){
if(GameDialog.gd_visible){
...
}
}
}
PauseDialog class
public class PauseDialog extends GameDialog {
public PauseDialog(GameScene scene, Camera camera, VertexBufferObjectManager pSpriteVertexBufferObject) {
super(scene, camera, pSpriteVertexBufferObject);
...
final ButtonSprite play_button = new ButtonSprite(...);
play_button.setOnClickListener(setPlayButtonListener());
}
private OnClickListener setPlayButtonListener() {
return new OnClickListener() {
#Override
public void onClick(ButtonSprite pButtonSprite, float pTouchAreaLocalX, float pTouchAreaLocalY) {
hide();
}
};
}
}
Each time I want to display a dialog, I write this line :
new PauseDialog(GameScene.this, camera, vbom).display();
The first time, it works well : the dialog is displayed, user make a choice and it's hidden.
But the 2nd time, the dialog is not hidden (after user's choice).
I used the debugger to see what's going on, and the conclusion is :
In the 2nd instance, it calls the hide() method of the first instance !
If some one can explain me what it is doing that ... Thank you.
It is because gd_visible is static. Delete the static keyword and it should work. Static fields doesn't belong to the instances but they belong to the class.
I am developing a multi player game, which have a module which works on the basis of notifications send by server. For example: Action of other player, score update, action to do etc.
I am receiving notification in json format. I am wondering if there is some codding pattern exist which automatically deliver different notifications to their corresponding handlers. Many thanks for your help.
Well, cannot say if this classifies as a pattern:
My take on it would be to simply create a separate class, lets call it JSONGameStateFilter, to filter the JSON object based on the received value plus the state of the game
Something like:
public class JSONGameStateFilter() {
public interface GameInterface1 {
// callback methods for activity 1
// example: public void newPlayerArrived(String name, int score);
// ...
}
public interface GameInterface2 {
// callback methods for activity 2
}
public interface GameInterface3 {
// callback methods for activity 3
}
private GameInterface1 callback1;
private GameInterface2 callback2;
private GameInterface3 callback3;
private JSONGameStateFilter instance;
public static JSONGameStateFilter getInstance() {
if (instance != null) {
return instance = new JSONGameStateFilter();
}
}
private JSONGameStateFilter() {}
public void registerListener(GameInterface1 callback) {
// called by Activity1 implementing GameInterface1
// by JSONGameStateFilter.newInstance().registerListener(this);
this.callback1 = callback;
}
public void registerListener(GameInterface2 callback) {
this.callback2 = callback;
}
public void registerListener(GameInterface3 callback) {
this.callback3 = callback;
}
public void filterJSON(JSONObject object) {
// read JSON and gamestate
// depending on situation call the right callback
// example: if (callback1 != null) callback1.newPlayerArrived(name, score)
}
}
The design of this approach would be to implement varies of callbacks on each activity (known pattern for fragments to communicate back to activity).
This is untested and written just now but I am pretty confident that it would work well.