Categories
discuss

Android map v2 error on second inflating

I’m trying to use new android maps in my app.

I’ve got a FragmentActivity which layout contains (among other things):

<LinearLayout a:id="@+id/fragment_container"
    a:layout_width="fill_parent"
    a:layout_height="100dp"
    a:layout_weight="1"/>

It also has a button which changes this fragment using (mostly copied from sample project):

if (condition) {
    fragment = new Fragment1();
} else {
    fragment = new LocationFragment();
}
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();

and LocationFragment is:

public class LocationFragment extends SupportMapFragment{
private GoogleMap mMap;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    view = inflater.inflate(R.layout.map_fragment, container, false);
    setUpMapIfNeeded();
    return view;
}

@Override
public void onResume() {
    super.onResume();
    setUpMapIfNeeded();
}

private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the map.
    if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        mMap = ((SupportMapFragment)  getActivity().getSupportFragmentManager().findFragmentById(R.id.map))
                .getMap();
        // Check if we were successful in obtaining the map.
        if (mMap != null) {
            setUpMap();
        }
    }
}

private void setUpMap() {
    mMap.addMarker(new MarkerOptions().position(new LatLng(60.02532, 30.370552)).title(getString(R.string.map_current_location)));
}
}

xml layout is:

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
      android:id="@+id/map"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      class="com.google.android.gms.maps.SupportMapFragment"/>

The problem is that when we replacing fragment with LocationFragment for the second time android is unable to inflate from xml. It crashes on line:

view = inflater.inflate(R.layout.map_fragment, container, false);

with exception:

12-17 01:47:31.209: ERROR/AndroidRuntime(4679): FATAL EXCEPTION: main
    android.view.InflateException: Binary XML file line #4: Error inflating class fragment
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:587)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:386)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
    at my.package.LocationFragment.onCreateView(LocationFragment.java:29)
    ...

And I have no Idea how to solve it. I think that it could be connected with an old issue that you cannot use more than one map view (found questions on android map v1). But in case of v2 and fragments support it must be the way to replace fragment container with map fragment, am I right?

Answer

You are extending SupportMapFragment. That is perfectly fine, though I am uncertain how common that pattern will be (this is all a bit too new).

However, SupportMapFragment is a fragment and knows how to display a map. You should not be overriding onCreateView() in most cases, and you certainly should not be overriding onCreateView() and trying to inflate a layout file that contains a <fragment> element pointing back to SupportMapFragment.

Here is a sample app that uses SupportMapFragment from the Maps V2 library. The activity loads a layout that has SupportMapFragment:

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/map"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  class="com.google.android.gms.maps.SupportMapFragment"/>
Categories
discuss

Javascript Getting specific element (of parent) by name

I’m using custom tags to define sections in an application, so I have something like this:

<mysection>

   <form>
       <input name="myfield">
   </form>

</mysection>

I’m using the following and able to get the tag (printed to console, everything is groovy)

var parent = document.getElementsByTagName('mysection');

The issue I’m having is finding the child field by name:

var myfield = parent.getElementsByName("myfield");

…as I don’t want to pick up on any other ‘sections’ that might have an input with the name ‘myfield’.

EDIT:

var parent = document.getElementsByTagName('mysection')[0];

was suggested and returns to console the section contents, however, getElementsByName throws an error:

Uncaught TypeError: Object #<NodeList> has no method 'getElementsByName' 

Answer

Using getElementsByTagName() and getElementsByName() will return a NodeList, you need to get the first element of the list like this:

var parent = document.getElementsByTagName('mysection')[0];
var myfield = parent.getElementsByName("myfield")[0];

Edit

You were correct, getElementsByName is not valid for an element. I am unsure how to localize the functionality of it as you are trying to do. It seems that it will only work for document. You may have to write your own implementation of getElementsByName if you want to use it in a localized scope.

Second Edit

To be nice, I made that implementation for you 😀 Here it is in all its “glory”.

Element.prototype.getElementsByName = function (arg) {
    var returnList = [];
    (function BuildReturn(startPoint) {
        for (var child in startPoint) {
            if (startPoint[child].nodeType != 1) continue; //not an element
            if (startPoint[child].getAttribute("name") == arg) returnList.push(startPoint[child]);
            if (startPoint[child].childNodes.length > 0) {
                BuildReturn(startPoint[child].childNodes);
            }
        }
    })(this.childNodes);
    return returnList;
};
var parent = document.getElementsByTagName('mysection')[0];
var myfield = parent.getElementsByName("myfield")[0];

Small fix

I was incorrectly passing the element and not its children into the recursion. The code above has been edited with the proper argument passed now. See working fiddle: http://jsfiddle.net/js6NP/5/

Categories
discuss

Passing Parameters of AJAX POST to Grails Controller

I´m building a social network with Grails and got stucked on giving users inner their editprofile page the chance to paste an youtube-Url into a textfield and by clicking a button a JS regexxes the id out of the URL pasted, an ajax post is fired updating a div with a preview image of the youtube video

the html looks like :

                    <g:textField name="videoinput" class="videoinput reLef" value="" />
                    <span class="daten_videouploadbtn reLef" ></span>

        <g:render template="/forms/storedVideos" />

the JS looks like :

    $('.daten_videouploadbtn').click(function() {

        var string = document.editProfileForm.videoinput.value;
        var neu = string.replace(/http[s]?://(?:[^.]+.)*(?:youtube.com/(?:v/|watch?(?:.*?&)?v=|embed/)|youtu.be/)([w-_]+)/i, '$1'); 
        var id = RegExp.$1;

        jQuery.ajax({
        type:'POST',
        data:RegExp.$1, 
        url:'${createLink(action: 'addVideo')}',
        success:function(data,textStatus){jQuery('#storedvideos').html(data);},
        error:function(XMLHttpRequest,textStatus,errorThrown){}
        });
});

the controller looks like :

def addVideo() {
    def videoitems = !!%%-- HOW TO PARSE YOUTUBE-ID HERE -%%!!
    render(template:"/forms/storedVideos", model: [newVideo:videoitems])
}

and stored videos looks :

    <div id="storedvideos"><span><img src="http://img.youtube.com/vi/${newVideo}/default.jpg" width="225px" height="130px"/></span></div>

i just dont get it how to catch the data of the Ajax Post and update the div with the preview image with the id inside,

can someone give a hint ? it is killing me

Answer

You should post the data like this:

jQuery.ajax({
  type: 'POST',
  data: { value: RegExp.$1 },
  ...

After that you can access the posted data inside your grails controller with params.value.

Categories
discuss

Spring Data MongoDB Indexed(unique=true)

I’m having a lot of problems with Spring Data and MongoDB when it comes to an Indexed field.

I’ve gone over the docs, but they aren’t very good at explaining the difference between @Indexed(unique=true) and @Indexed(unique=false).

I have a field that I wanted indexed so I can execute fast queries against it. In this case it’s email address which generally should be unique, but it’s possible for the emailAddress to be null for a period.

However, once one record as a null emailAddress I can’t have any other records with a null emailAddress. Spring Data refuses to insert any additional records with null emailAddresses. And it fails to throw anything that it didn’t work.

Right now I have it set to unique=true, but I’m contemplating setting it to unique=false to get around this problem.

Will this fix the problem?

And what other problems could I be adding by relaxing this?

Will MongoDB allow me to have multiple email addresses that are equal and still be fast at querying?

Answer

From mongodb docs:
http://docs.mongodb.org/manual/core/indexes/#unique-indexes

So if you have a unique key, don’t set it to null.

To be honest, in your use case(email field), I believe you don’t need to use unique key, you could use sparse key, instead, so, docs that don’t have email wont take up your btree index, which is going to save you space, and increase the lookup speed.

Categories
discuss

How to get center of map for v2 android maps?

In Google Maps for Android v1, MapView had a convenience method: getMapCenter(). Now I cannot figure out how to get map center with v2 of this api. I have perused the API documentation, but there is no mention of such a feature. Please advise.

Thanks, Igor

Answer

I had the same problem. It seems you can get the center this way:

mMap.getCameraPosition().target

where mMap is the GoogleMap instance from your activity. This will return a LatLng object which basically represents the center of the map.

Note that the GeoPoint class is not available anymore.

According to http://developer.android.com/reference/com/google/android/gms/maps/model/CameraPosition.html

target is “The location that the camera is pointing at.” (I tested it with the sample code and it worked okay for me)

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..