Make TvInputService display an overlay - android-tv

I'm trying to write a most simple TvInputService, that will display an overlay using TIF Companion Library.
The Live Channels application already recognizes my channel Simple Channel declared in my EpgSyncJobService subclass.
My Program is displayed in the Live Channels application's EPG as currently presented one.
However, all I can see is the blue spinner, as if the channel didn't "tune".
What am I doing wrong?
public class MyTvInputService extends BaseTvInputService {
#Override
public final BaseTvInputService.Session onCreateSession(String inputId) {
BaseTvInputService.Session session = new MyTvInputSession(this, inputId);
session.setOverlayViewEnabled(true);
return super.sessionCreated(session);
}
class MyTvInputSession extends BaseTvInputService.Session {
public MyTvInputSession(Context context, String inputId) {
super(context, inputId);
}
#Override
public View onCreateOverlayView() {
mTextView = new TextView(MyTvInputService.this);
mTextView.setText("This is an example overlay");
mTextView.setTextColor(Color.RED);
mTextView.setVisibility(View.VISIBLE);
mTextView.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
return mTextView;
}
#Override
public boolean onPlayProgram(Program program, long startPosMs) {
return true;
}
#Override
public boolean onPlayRecordedProgram(RecordedProgram recordedProgram) {
return true;
}
#Override
public void onSetCaptionEnabled(boolean enable) {}
#Override
public TvPlayer getTvPlayer() { return null; }
}
private TextView mTextView;
}

According to TvInputService.Session.notifyVideoAvailable() documentation:
The TV input service must call this method as soon as the content
rendered onto its surface is ready for viewing. This method must be
called each time onTune(Uri) is called.
So it is enough to call notifyVideoAvailable() in BaseTvInputService.Session.onTune(Uri) method override, like so:
#Override
public boolean onTune(Uri channelUri) {
notifyVideoAvailable();
return true;
}
I must say, that using the TV Companion Library's BaseTvInputService makes finding such issues harder than when using bare TvInputService, as an onTune() method is non-abstract in BaseTvInputService.Session.

Related

JavaFX Property's invalidate() method not called with binding

I'm trying to make a custom control in JavaFX using some binding feature. This is my problem: I have a class with a DoubleProperty that I use to calculate the position of an element inside my custom control. Here is the code:
public class CustomControl extends Region {
private DoubleProperty positionProperty;
public CustomControl() {
positionProperty= new DoublePropertyBase(0.0) {
#Override public Object getBean() { return CustomControl.this; }
#Override public String getName() { return "position"; }
#Override protected void invalidated() { updatePostion(); }
};
}
public DoubleProperty positionProperty() { return positionProperty; }
public double getPosition() { return positionProperty.get(); }
public void setPosition(double value) { positionProperty.set(value); }
private void updatePosition() {
double value = doubleProperty.get();
//compute the new position using value
}
}
In my application i have two CustomControls and i want that when i call the method setPosition() on the first of them, the second one updates the position of its component as well. To do so I binded the positionProperty of the two CustomControls like this:
CustomControl control1 = new CustomControl();
CustomControl control2 = new CustomControl();
control2.positionProperty.bind(control1.positionProperty);
Then when I call for example
control1.setPosition(50.0);
only the position of the component of control1 is updated, indeed when i call the method setPosition(), the method invalidated() of the positionProperty of control1 is actually called, but not the one of the positionProperty of contol2 as I espected. How shoul i achieve what i want? Thank you!
PS: I also noticed that using the method bindBidirectional() instead of bind() works, but shouldn't it work using only bind() too?
EDIT: example code is available here: https://luca_bertolini#bitbucket.org/luca_bertolini/customcontrolexample.git
JavaFX uses lazy evaluation for all bindings, which means that when a change occurs on your out.positionProperty object, the new value is not immediately taken into account. This happens later, if and only when the value is subsequently requested.
Try this:
out.positionProperty().addListener(new InvalidationListener() {
#Override
public void invalidated(final Observable observable) {
// System.out.println("It must go now.");
}
});
and you will see that this time your code works as you want.

Eclipse Scout Neon unit test of execChangedMasterValue

I have two fields that are connected with master-slave relationship :
public class Slave extends AbstractListBox<String> {
#Override
protected Class<? extends IValueField> getConfiguredMasterField() {
return Master.class;
}
#Override
protected void execChangedMasterValue(final Object newMasterValue) {
this.function() // -> here I put debugging break point
}
}
public class Master extends AbstractBooleanField {
#Override
protected void execChangedValue() {
super.execChangedValue(); // -> Break point 2
}
}
I write unit test for this relationship, but inside unit test execChangedMasterValue is never called.
My unit test looks like :
#Test
public void test() {
this.box.getMaster.setValue(true)
Assert.assertFalse(... something from function Slave ...)
}
Unit tests always failed, and if I put breakpoints as described above, debugger stops only on second break point but never on first one.
In "real" world, function is called and everything works as it should.
Is there a reason that execChangedMasterValue is not called? Is behaviour of execChangedMasterValue different from changedValue()?
I cannot reproduce what you are describing. I took the Scout HelloWorld Project (the one that is generated when you create a new project).
In the HelloWorldForm I have added this "slave" field in the MainBox:
#Order(2000)
public class LengthField extends AbstractIntegerField {
#Override
protected String getConfiguredLabel() {
return TEXTS.get("Length");
}
#Override
protected Class<? extends IValueField<?>> getConfiguredMasterField() {
return MessageField.class;
}
#Override
protected void execChangedMasterValue(Object newMasterValue) {
if(newMasterValue instanceof String) {
String s = (String) newMasterValue;
setValue(s.length());
} else {
setValue(0);
}
}
}
And in the example Unit Test HelloWorldFormTest, I have added an additional check to testMessageCorrectlyImported():
/**
* Tests that the {#link MessageField} is correctly filled after start.
*/
#Test
public void testMessageCorrectlyImported() {
HelloWorldForm frm = new HelloWorldForm();
frm.start();
Assert.assertEquals("Message field", MESSAGE_VALUE, frm.getMessageField().getValue());
Assert.assertEquals("Length field", Integer.valueOf(MESSAGE_VALUE.length()) , frm.getLengthField().getValue());
frm.getMessageField().setValue("abcdef");
Assert.assertEquals("Length field (after update)", Integer.valueOf("abcdef".length()), frm.getLengthField().getValue());
}
Everything works as expected…

React-native inside a Fragment

How to Start react-native inside of a fragment?
While putting react-native inside Fragment, onCreateView function is unable to return View from mReactRootView.
View view = inflater.inflate(mReactRootView. , container, false);
I've managed to figure this out with much trial and error. I've seen this question asked around the internet and thought that this was the best place to post the answer. Here is how to do with the latest version of React (0.29 as of this writing):
The first thing we'll do is create an abstract ReactFragment class that we will use throughout our app:
public abstract class ReactFragment extends Fragment {
private ReactRootView mReactRootView;
private ReactInstanceManager mReactInstanceManager;
// This method returns the name of our top-level component to show
public abstract String getMainComponentName();
#Override
public void onAttach(Context context) {
super.onAttach(context);
mReactRootView = new ReactRootView(context);
mReactInstanceManager =
((MyApplication) getActivity().getApplication())
.getReactNativeHost()
.getReactInstanceManager();
}
#Override
public ReactRootView onCreateView(LayoutInflater inflater, ViewGroup group, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
return mReactRootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mReactRootView.startReactApplication(
mReactInstanceManager,
getMainComponentName(),
null
);
}
}
We'll now be able to create fragments that render React Native components, e.g.:
public class HelloFragment extends ReactFragment {
#Override
public String getMainComponentName() {
return "hellocomponent"; // name of our React Native component we've registered
}
}
A little more work is required, though. Our parent Activity needs to pass some things into the ReactInstanceManager in order for the React Native lifecycle to work properly. Here's what I ended up with:
public class FragmentActivity extends AppCompatActivity implements DefaultHardwareBackBtnHandler {
/*
* Get the ReactInstanceManager, AKA the bridge between JS and Android
* We use a singleton here so we can reuse the instance throughout our app
* instead of constantly re-instantiating and re-downloading the bundle
*/
private ReactInstanceManager mReactInstanceManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
/**
* Get the reference to the ReactInstanceManager
*/
mReactInstanceManager =
((MyApplication) getApplication()).getReactNativeHost().getReactInstanceManager();
/*
* We can instantiate a fragment to show for Activity programmatically,
* or using the layout XML files.
* This doesn't necessarily have to be a ReactFragment, any Fragment type will do.
*/
Fragment viewFragment = new HelloFragment();
getFragmentManager().beginTransaction().add(R.id.container, viewFragment).commit();
}
#Override
public void invokeDefaultOnBackPressed() {
super.onBackPressed();
}
/*
* Any activity that uses the ReactFragment or ReactActivty
* Needs to call onHostPause() on the ReactInstanceManager
*/
#Override
protected void onPause() {
super.onPause();
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostPause();
}
}
/*
* Same as onPause - need to call onHostResume
* on our ReactInstanceManager
*/
#Override
protected void onResume() {
super.onResume();
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostResume(this, this);
}
}
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU && mReactInstanceManager != null) {
mReactInstanceManager.showDevOptionsDialog();
return true;
}
return super.onKeyUp(keyCode, event);
}
}
Finally, you'll notice the reference to (MyApplication) throughout the code; this is a global Application object to contain our ReactInstanceManager, AKA the bridge between Android and React Native. This is the pattern that the React Native projects use internally, so I simply copied it. Here's how it's implemented:
public class MyApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
#Override
public boolean getUseDeveloperSupport() {
return true;
}
#Override
public List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage()
);
}
};
#Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
}
The trickiest bit was figuring out the lifecycle between the Fragment and the Activity; the ReactRootView needs a reference to the Activity context in order to instantiate, so making sure that getActivity() would not be null was important. Also, registering the onHostPause() and onHostResume() in the parent Activity was unintuitive at first, but ultimately proved simpler once the ReactNativeInstanceManager was abstracted away into a global instead of keeping it on the Activity or Fragment.
Hope this helps someone else out there!
There are libraries available that handle this for you.
One that I use is react-native-android-fragment
As per the instructions on the linked GitHub repository:
Add the following line to your build.gradle compile 'com.github.hudl:react-native-android-fragment:v0.43.2'.
e.g.
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
dependencies {
// Version will correspond to its dependnecy on React Native
compile 'com.github.hudl:react-native-android-fragment:v0.43.2'
}
Build you react code into the fragment
Fragment reactFragment = new ReactFragment.Builder()
.setComponentName("HelloWorld")
.setLaunchOptions(launchOptions) // A Bundle of launch options
.build();
Place the Fragment in a FrameLayout that you would have in your XML layout file. In my case, the FrameLayout ID is react_holder.
getSupportFragmentManager()
.beginTransaction()
.add(R.id.react_holder, reactFragment)
.commit();
There is now an official ReactFragment available here that can be used to host react native inside a fragment.
Just make sure you have your react native host setup correctly, as the fragment tries to access the react native host on the application level, or overload it in a subclass:
// inside the ReactFragment
protected ReactNativeHost getReactNativeHost() {
return ((ReactApplication) getActivity().getApplication()).getReactNativeHost();
}
you can then create the fragment using:
val reactNativeProcessFragment = ReactFragment.Builder()
.setComponentName("nameUsedIn_AppRegistry.registerComponent")
.build()

Add action to a cancel button in an editable grid in vaadin

I'm working with an editable Grid with Vaadin 7. When a row is in edit mode, it shows two buttons: save and cancel.
(Just in case, the image was taken from here Book of Vaadin)
With the:
grid.getEditorFieldGroup().addCommitHandler(new CommitHandler() {
private static final long serialVersionUID = 1L;
#SuppressWarnings("unchecked")
#Override
public void preCommit(CommitEvent commitEvent) throws CommitException{}
#Override
public void postCommit(CommitEvent commitEvent) throws CommitException{}
});
I can do something in the save action.
But, can I do something like that with the cancel action?
Thank you.
This is a serious deficiency of the component. According to the forum, they're working on it, but for the time being it seems that the most straightforward way is to extend the Grid component and override the doCancelEditor method. Here's a snippet:
public class MyGrid extends Grid {
protected Object newRow;
#Override
protected void doCancelEditor() {
super.doCancelEditor();
getContainerDataSource().removeItem(newRow);
setEditorEnabled(false);
}
public void setNewRow(Object newRow) {
this.newRow = newRow;
}
Note that you have to tell the MyGrid object when you create the row. Also, note that you're extending the server side, so you don't have to alter the client (widget code), but you do need to refer to the new component in your UI design.
Actually, saveEditor() should be also overridden, as doCancelEditor() seems to be invoked on save action, too. My code:
public class MyGrid extends Grid {
private boolean addingMode = false;
private JPAContainer<SomeEntity> container;
private Object recentlyAddedItemID;
public MyGrid(Indexed indexed) {
container = indexed;
}
#Override
protected void doCancelEditor() {
Object id = getEditedItemId();
super.doCancelEditor();
if (addingMode) {
getContainerDataSource().removeItem(id);
recentlyAddedItemID = null;
}
addingMode = false;
}
#Override
public void saveEditor() throws FieldGroup.CommitException {
if (addingMode) recentlyAddedItemID = getEditedItemId();
addingMode = false;
super.saveEditor();
}
public Object getRecentlyAddedItemID() {
return recentlyAddedItemID;
}
public void addNewElement(SomeEntity entity) {
addingMode = true;
editItem(container.addEntity(entity));
}
}
MyGrid grid = new MyGrid(JPAContainerFactory.make(SomeEntity.class, entityManager));
grid.addNewElement(new SomeEntity());
/*
if we want to know the new items's ID (actually the new primary key
in case of JPAContainer), we can check it by:
*/
Object id = grid.getRecentlyAddedItemID();
/*
returns null if editor was cancelled and finally nothing new was persisted
*/

Toolbar with SearchView temporary filtering RecyclerView

I need to implement search functionality inside my android app which uses toolbar, SlidingTabLayout and ViewPager that holds fragments. Inside each fragment there is a RecyclerView with list of items.
RecyclerView data is static defined in separate class (DataAccess.java) and those lists are updated and RecyclerView gets refreshed just by calling (without passing new data)
mRecyclerView.getAdapter().notifyDataSetChanged();
Is there any simple way to temporary filter RecyclerView without changing the data and after the user presses return button inside Toolbar to remove the filter and show inital list.
Before pressing Search icon inside toolbar menu:
So when the user is typing "Josip..." the filter will be active
and after he presses the X button in SearchView the user will get the same data as before without filter.
#Override
public boolean onQueryTextChange(String newText) {
// filter data (temporary remove all items from DataAccess.list that don't .startsWith(newText)
}
#Override
public boolean onQueryTextSubmit(String query)
// Doesn't help if I revert deleted items here
}
#Override
public boolean onQueryTextSubmit(String query){
((ItemAdapter) myRecList.getAdapter()).setFilter(query)
}
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ViewHolder> {
private List<String> visibleObjects;
private List<String> allObjects;
.....
public void flushFilter(){
visibleObjects=new ArrayList<>();
visibleObjects.addAll(allObjects);
notifyDataSetChanged();
}
public void setFilter(String queryText) {
visibleObjects = new ArrayList<>();
constraint = constraint.toString().toLowerCase();
for (String item: allObjects) {
if (item.toLowerCase().contains(queryText))
visibleObjects.add(item);
}
notifyDataSetChanged();
}
}
I wanted to add as comment but due to less reputation...I am answering post.
This method works fine if (item.toLowerCase().contains(queryText)) but what to do if match is not found in first iteration.then it will go in else part without looping throughout allObjects list...
for (RouteByATMList.Route_ATM item: Main_ATMItemList)
{
if (item.ATMNumber.contains(queryText)) {
visibleObjects.add(item);
}else {
Toast.makeText(mContext,"No search result found!",Toast.LENGTH_SHORT).show();
break;
}
}
I got the answer from my superior ,hope it helps.
public void setFilter(String queryText) {
visibleObjects = new ArrayList<>();
for (RouteByATMList.Route_ATM item: Main_ATMItemList)
{
if (item.ATMNumber.contains(queryText))
{
visibleObjects.add(item);
}
}
if(visibleObjects.size()==0){
Toast.makeText(mContext,"No search result found!",Toast.LENGTH_SHORT).show();
}
notifyDataSetChanged();
Log.e("dataset changed","dataset changed");
}
I don't oppose the given and accepted answer. There is a room for possible performance pitfalls. One should make use of Filterabe interface. Having this implemented will behave as ol'good ListView that did the filtering asynchronously. Then all you need is to write your own Filter and instantiate it in the overridden getFilter() method;
In my case I used Filter to sort an adapter of many (yeah, many many) items. It was junky sorting it on UI-thread.
So I had this abstract class
public abstract class BaseFilterableRecyclerViewAdapter<VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH> implements Filterable {
private Context mContext;
public BaseFilterableRecyclerViewAdapter(Context context) {
this.mContext = context;
}
public abstract void sort(SortingFilter.Sort sortingStrategy);
//...Other methods
}
And the class that inherit:
public class ItemAdapter extends BaseFilterableRecyclerViewAdapter<RecyclerView.ViewHolder>{
//... RecyclerView methods
#Override
public Filter getFilter() {
return new SortingFilter(mData) {
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results.values != null) {
int last = mData.size();
mData = (List<Product>) results.values;
notifyDataSetChanged();
}
}
};
}
#Override
public void sort(SortingFilter.Sort sortingStrategy) {
getFilter().filter(sortingStrategy.toString());
}
}

Resources