错误java.lang.IndexOutOfBoundsException:索引0无效,视图中的大小为0 by viewPager

时间:2016-09-08 16:43:43

标签: android google-maps arraylist indexoutofboundsexception

我在tab(viewPager)中使用map,我想在地图中搜索位置为此目的我正在使用EditText字段和数组列表,但我仍然收到此错误。我无法找到它的问题所在。请有人建议我,我该怎么办?

FATAL EXCEPTION: main    Process: com.example.saroosh.masjidnow, PID: 10465
    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
com.example.saroosh.masjidnow.Tabs.AddMasjid$1.onClick(AddMasjid.java:61) at
    android.view.View.performClick(View.java:5184)    at
    android.view.View$PerformClick.run(View.java:20910)    at
    android.os.Handler.handleCallback(Handler.java:739)    at
    android.os.Handler.dispatchMessage(Handler.java:95)    at
    android.os.Looper.loop(Looper.java:145)    at
    android.app.ActivityThread.main(ActivityThread.java:5942)    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:1389)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1184)

我的java类如下所示。

AddMasjid.java

package com.example.saroosh.masjidnow.Tabs;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Geocoder;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.content.Context;
import android.widget.Button;
import android.widget.EditText;

import com.example.saroosh.masjidnow.R;
import com.google.android.gms.identity.intents.Address;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import java.io.IOException;
import java.util.List;

public class AddMasjid extends Fragment implements OnMapReadyCallback {

    MapView gMapView;
    GoogleMap gMap = null;
    Button sButton;
    String location;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.add_masjid, container, false);
        EditText sLocation = (EditText) v.findViewById(R.id.editText1);
        location = sLocation.getText().toString();
        sButton = (Button) v.findViewById(R.id.generalId);
        sButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                List<android.location.Address> addressList= null;

                if (location != null || !location.equals(""))
                {
                    Geocoder geocoder = new Geocoder(getActivity().getApplicationContext());
                    try {
                        addressList = geocoder.getFromLocationName(location, 1);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    android.location.Address address = addressList.get(0);
                    LatLng latlng = new LatLng(address.getLatitude(),address.getLatitude());
                    gMap.addMarker(new MarkerOptions().position(latlng).title("Marker"));
                    gMap.animateCamera(CameraUpdateFactory.newLatLng(latlng));
                }

            }
        });

        gMapView = (MapView) v.findViewById(R.id.map);
        gMapView.getMapAsync(this);
        gMapView.onCreate(savedInstanceState);
        gMapView.onResume(); // needed to get the map to display immediately
        try {
            MapsInitializer.initialize(getActivity().getApplicationContext());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return v;
    }


    @Override
    public void onMapReady(GoogleMap map) {
        gMap = map;
        gMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new
                LatLng(0, 0), 0));


        if (gMap != null) {
            gMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
            if (ActivityCompat.checkSelfPermission(getActivity().getApplicationContext()
                    , Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity().getApplicationContext()
                    , Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            gMap.setMyLocationEnabled(true);
            gMap.getUiSettings().setMyLocationButtonEnabled(true);


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

    }

    public void onSearch(View view) throws IOException{

    }

    @Override
    public void onPause() {
        super.onPause();
        gMapView.onPause();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        gMapView.onDestroy();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        gMapView.onLowMemory();
    }


}

3 个答案:

答案 0 :(得分:0)

此处的地址列表为空:addressList.get(0)

请注意,并非每个位置都有有效地址。你的代码必须处理这个事实。

答案 1 :(得分:0)

List<android.location.Address> addressList= null;

然后你

android.location.Address address = addressList.get(0);

尝试登录以检查添加位置

if (location != null || !location.equals(""))
            {
                Geocoder geocoder = new Geocoder(getActivity().getApplicationContext());
                try {
                    addressList = geocoder.getFromLocationName(location, 1);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

因为这可能不会给你任何记录,并且使用addressList.get(0)你取位置0因为你知道在java位置从0,1,2开始如果没有位置0你将得到错误BoundOfException

答案 2 :(得分:0)

我已经解决了我的问题。我在editText方法中通过onCreat字段传递了我的位置字符串,这是我的addressList无法在列表中找到位置而我收到错误的方式。当我在editText方法中声明我的setOnClickListener时,我的列表会在其中找到其中的位置:

sButton =(Button) v.findViewById(R.id.generalId);
        sButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                hideSoftKeyboard(v);
                EditText sLocation = (EditText)getActivity().findViewById(R.id.editText1);
                location = sLocation.getText().toString();

                List<android.location.Address> addressList= null;

                if (location != null || location.length()>0) {
                    Geocoder geocoder = new Geocoder(getActivity().getApplicationContext());
                    try {
                        addressList = geocoder.getFromLocationName(location, 1);

                    } catch (IOException e) {

                            e.printStackTrace();
                    }

                    android.location.Address address = addressList.get(0);
                    String locality = address.getLocality();
                    Toast.makeText(getActivity(), locality, Toast.LENGTH_LONG).show();
                    double latitude = address.getLatitude();
                    double longitude = address.getLongitude();
                    LatLng latLng = new LatLng(latitude, longitude);
                    gMap.addMarker(new MarkerOptions().position(latLng).title("Marker"));
                    gMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));

                }

            }
        });