0

I've created main activity with 2 tabs and I'm trying to implement map on the first tab fragment. Application displays default map with market at (0, 0) but it crashes when I click on button to find new place from text box. OneFragment java code:

public class OneFragment extends Fragment implements OnMapReadyCallback, View.OnClickListener{ // implements OnMapReadyCallback, View.OnClickListener

private GoogleMap mMap;
private EditText mOriginPlace;
private Button mSearchOriginButton;
private View mView;


    public OneFragment() {
        // Required empty public constructor
    }


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public void onMapReady(GoogleMap googleMap) { //when map service started
    mMap = googleMap;
    LatLng hcmus = new LatLng(10.762963, 106.682394); //create position with latitude and longitude
    mMap.addMarker(new MarkerOptions()
            .position(hcmus)
            .title("Title"));
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(hcmus, 10));
}


@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    setUpMapIfNeeded();
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    mView = inflater.inflate(R.layout.fragment_one, container, false);

    mSearchOriginButton = (Button) mView.findViewById(R.id.searchOriginButton);
    mSearchOriginButton.setOnClickListener(this);
    return mView;
}

@Override
public void onClick(View v) {
    mOriginPlace = (EditText) mView.findViewById(R.id.originPlaceText);
    String placeOriginText = mOriginPlace.getText().toString();
    List<Address> addressList = null;
    if (placeOriginText != null || !placeOriginText.equals("")) {
    Geocoder geocoder = new Geocoder(getActivity());
    try {
        addressList = geocoder.getFromLocationName(placeOriginText, 1);
    } catch (IOException e) {
        e.printStackTrace();
    }
    if(addressList.size() > 0) {
        Address address = addressList.get(0);
        LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
        mMap.addMarker(new MarkerOptions()
                .position(latLng)
                .title("Marker"));
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10));
    }
    } else {
        Toast.makeText(getActivity(), "Please enter origin address!", Toast.LENGTH_SHORT).show();
    }
}

public void setUpMapIfNeeded() {
    if (mMap == null) {
        SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager()
                .findFragmentById(R.id.originPlaceMap);
        mapFragment.getMapAsync(this); //it'll start map service, getMapAsync(), чтобы установить обратный вызов для фрагмента
    }
}

}

Log from logcat:

    04-20 18:44:11.154 6485-6485/com.itshareplus.googlemapdemo E/AndroidRuntime: FATAL EXCEPTION: main
                                                                         Process: com.itshareplus.googlemapdemo, PID: 6485
                                                                         java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
                                                                             at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
                                                                             at java.util.ArrayList.get(ArrayList.java:308)
                                                                             at fragments.OneFragment.onClick(OneFragment.java:94)
                                                                             at android.view.View.performClick(View.java:4909)
                                                                             at android.view.View$PerformClick.run(View.java:20390)
                                                                             at android.os.Handler.handleCallback(Handler.java:815)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:104)
                                                                             at android.os.Looper.loop(Looper.java:194)
                                                                             at android.app.ActivityThread.main(ActivityThread.java:5848)
                                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                                             at java.lang.reflect.Method.invoke(Method.java:372)
                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1020)
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815)
04-20 18:44:11.328 6485-6485/com.itshareplus.googlemapdemo I/Process: Sending signal. PID: 6485 SIG: 9
koflox
  • 25
  • 6

2 Answers2

0

Since you didn't add the crash log it's hard to give the solution to your problem. You can make sure that updating the map view is happening on the main UI thread or not(Use the main looper). Depends on the way your screens navigation some times getActivity will be null make sure that too. If you add your crash log i can help you more

Vinod
  • 88
  • 3
  • 8
  • I added logcat output – koflox Apr 20 '17 at 14:48
  • Can you add a check before you retrieve the object from the addressList. if(addessList.size >0){ then do your work } – Vinod Apr 20 '17 at 14:52
  • Thx, now it doesn't crushes. So it mean that geocder cant get address from EditText, could you help with it? – koflox Apr 20 '17 at 15:02
  • I believe your edit text is inside the fragment if that's true, make View view global variable and initialize the edit text with view.findviewById(); and let me know the result, hope it should work – Vinod Apr 20 '17 at 15:11
  • still doesn't work, I update fragment code (look above) as you said – koflox Apr 20 '17 at 15:43
  • In try catch block add the following condition while(addressList.size == 0){ addressList = geocoder.getFromLocationName(placeOriginText, 1);} and make sure placeorigintext is not null or empty – Vinod Apr 20 '17 at 16:01
  • did you try adding the while loop in try catch block? Is placeOriginnText is null or not? – Vinod Apr 20 '17 at 17:04
  • yes, I tried add while loop and provided you error description from logcat in previous comment. placeOriginnText is not null because I displayed it like toast and it's working. – koflox Apr 20 '17 at 17:20
  • try { addressList = geocoder.getFromLocationName(placeOriginText, 1); //did you add the while loop below the above line } catch (IOException e) { e.printStackTrace(); } – Vinod Apr 20 '17 at 17:23
  • yes, I added: while(addressList == null) { addressList = geocoder.getFromLocationName(placeOriginText, 1); }. I can't use .size() cuz addressList initialized as null – koflox Apr 20 '17 at 18:01
  • hope this will help you [GeoCoder](http://stackoverflow.com/questions/15182853/android-geocoder-getfromlocationname-always-returns-null) – Vinod Apr 20 '17 at 18:38
  • it really helped me, tnx – koflox Apr 21 '17 at 14:41
0

Address gets some time to receive results from geocoder so try putting the whole onclick method under try catch block.

Apurv Mahesh
  • 129
  • 4