Categories
discuss

Static data-binding in Android [literals]

I have created custom layout which contains image and title. To reuse this layout I’m using <include> tag. The problem is that I’m not even able to bind string literal into the layout being included. I tried to follow these instructions, but without success.

layout/titlebar.xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>
        <variable name="title" type="String"/>
        <!-- <variable name="imgSrc" type="android.graphics.drawable.Drawable" /> -->
    </data>
    <LinearLayout ... >
        <!-- <ImageView ... android:src="{imgSrc}" /> -->
        <TextView ... android:text="@{title, default=DefaultTitle}" />
    </LinearLayout>
</layout>

layout/otherlayout.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:bind="http://schemas.android.com/apk/res-auto"
              ... 
              >
    <!-- bind:imgSrc="@{@drawable/some_image}" -->
    <include layout="@layout/titlebar"
             bind:title="@{Example}"  <---------- does not work 
             />
    ...
</LinearLayout>

In gradle I have enabled data-binding for module:

android {
    ...
    dataBinding {
        enabled = true
    }
    ...
}

Answer

Fixed layout/otherlayout.xml based on @CzarMatt answer

<?xml version="1.0" encoding="utf-8"?>
<!-- 
layout with bindings has to be wrapped in <layout> tag so {LayoutName}Bindings 
class can be auto-generated for binding purposes 

xmlns:alias="http://schemas.android.com/apk/res-auto" 
creates an "app namespace" for custom attributes
-->
<layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:bind="http://schemas.android.com/apk/res-auto">
    <LinearLayout  ... >
        <!-- 
        // if this layout is also using title "data variable" 
        // and we want to use default value if title is null
        bind:title='@{title ?? "Settings"} 

        // passing literal reference into the binding
        bind:title="@{@string/settings_constant}"
        -->
        <include layout="@layout/titlebar"
                 bind:title='@{"Settings"}'
                 />
        ...
    </LinearLayout>
</layout>

Data-binding requires to set layout via DataBindingUtil as @RaviRupareliya suggested, otherwise data-binding will not work:

public class OtherActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); 
        // setContentView(R.layout.otherlayout);
        DataBindingUtil.setContentView(this, R.layout.otherlayout);
    }
    ...
}
Categories
discuss

Testing Android Instant Apps

I’m developing Android Instant App for my published app. However, published version of my installable app does not include the necessary URLs in application manifest file. Before I release my app, I want to add the URLs into my application manifest file and see how it works when the user directs to the URL I define for the Instant App. Any way to test this scenario without updating my app?

I mean a way to test Instant App without launching URL but going through the user scenario?

Note: I uploaded necessary JSON files to my web server, however, because my installable app does not include the URLs, it didn’t release it. But the test URL verifies that it has been successfully associated with my website.

Answer

You can test the InstantApp process by uploading your APK to the beta environment of the googlePlay (and add yourself as a tester).

You can test your app’s functionality (running as an instant app) by adding the proper Run/Debug Configurations and adding parameters that you need following this guideline:

you have to use the app links assistant in Tools->App Links Assistant

Then check your links and in the Path selector, check whether the pathPrefix option is selected.

Then at the bottom of the OnCreate method of your activity (which is related to the link you recently edited) add this code:

Intent appLinkIntent = getIntent();
String appLinkAction = appLinkIntent.getAction();
Uri appLinkData = appLinkIntent.getData();
// then use appLinkData.getQueryParameter("YourParameter")

You can test and debug this, using the editConfigurations option.Just open that window and edit your instantApp module (the one launched with the Link you recently edited) and in the URL field add the URL parameters that you need. ?Param1=1&Param2=two (then just run that module).

Categories
discuss

load google map without using callback method

i have multiple google map instances on my website,now there are two different google map on a same page, what happens is the first one works and other doesn’t now i know the logical issue let me show you my code first

<script>
    function initMap() {
        var myLatLng = {lat: 43.6222102, lng:-79.6694881};

        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 15,
            center: myLatLng
        });

        var marker = new google.maps.Marker({
            position: myLatLng,
            map: map,
        });
    }
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=my_key&callback=initMap"
        async defer></script>

now as i defined a callback method it always initializes the method named initMap whereas what i want to do is there can be multiple google maps lets suppose initMap2 how can i load them without callback method?

Answer

To load the map without a callback, load the API synchronously/inline (without the async defer), then call your initMap function on the load event.

(Note: FYI: Google changed all their examples to using asynchronous loading to improve the load times)

(Note2: Google has added a “sample” to their documentation describing synchronous loading)

proof of concept fiddle

code snippet:

function initMap() {
  var myLatLng = {
    lat: 43.6222102,
    lng: -79.6694881
  };

  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 15,
    center: myLatLng
  });

  var marker = new google.maps.Marker({
    position: myLatLng,
    map: map,
  });
}
google.maps.event.addDomListener(window, 'load', initMap);
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map"></div>
Categories
discuss

The “document.ready()” function not firing on Chrome Mobile (android)

I have jQuery-2.1.4.min.js called before the tag, but when I write something like:

<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script type="text/javascript">
    jQuery(document).ready(function() {
        alert('hi, world.');
    });
</script>

On my PC it is fired of course, but on ten different Android devices it just does not. This is purely HTML/CSS/jQuery rendered site (no phonegap, or anything).

My goal was to have a button do ajax request after it’s being tapped, but I can’t even test that, because the .ready() function is not firing at all on mobile chrome.

The jQuery is being served from the official CDN, any help would be very much appreciated.

Tried both:

$(function() {
   alert('hi, world.');
});

And

jQuery(document).ready(function() {
    alert('hi, world.');
});

Same thing.

As suggested I also tried:

window.onload = function()
{
    if (window.jQuery)
    {
        alert('jQuery is loaded');
    }
    else
    {
        alert('jQuery is not loaded');
    }
}

And it alerts ‘jQuery is loaded’.

As per jQuery docs it says: “Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute” – which would mean that DOM is not ready for JavaScript code to execute? But when I try like:

<script type="text/javascript">
    alert('hi world');
</script>

It executes on mobile Chrome.

Answer

Okay, after extensive investigation it seems that JS breaks on mobile chrome if you have document.ready() function twice, I had one in my core.js file and one in-line on the page.

It works okay on PC (all browsers), but on mobile it works up to the point of second ready() call and breaks all JS after that.

Hopefully this saves some time to others in the future.

Categories
discuss

RxJava Scheduler to observe on main thread

If I write something like this, then both the operation and notification will be on the current thread…

Observable.fromCallable(() -> "Do Something")
    .subscribe(System.out::println);

If I do the operation on a background thread like this, then both the operation and notification will be on a background thread…

Observable.fromCallable(() -> "Do Something")
    .subscribeOn(Schedulers.io())
    .subscribe(System.out::println);

If I want to observe on the main thread and do in the background in Android I would do…

Observable.fromCallable(() -> "Do Something")
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(System.out::println);

But If I was writing a standard Java program, what is the equivalent to state that you want to observe on the main thread?

Answer

Convert the Observable to a BlockingObservable via .toBlocking(); this gives you blocking methods to wait for completion, get one item, etc.

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..