【问题标题】:Error java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 in fragment by viewPager错误 java.lang.IndexOutOfBoundsException:无效索引 0,viewPager 在片段中的大小为 0
【发布时间】:2016-09-08 16:43:43
【问题描述】:

我在 tab(viewPager) 中使用地图,我想为此在地图中搜索位置我正在使用 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();
    }


}

【问题讨论】:

  • 你在什么代码上得到这个错误?
  • 在地址列表中,我找不到如何在位置中传递值。

标签: android google-maps arraylist indexoutofboundsexception


【解决方案1】:
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

【讨论】:

  • 对 OP 来说,将 try-catch 之后的 4 行移动到其中(try-catch)是有意义的,因为如果我们没有得到 addressList,我们为什么要试图处理它?
  • @Rodriquez 那么,我怎样才能在其中传递价值呢?
【解决方案2】:

这里的地址列表是空的:addressList.get(0)

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

【讨论】:

  • 如何通过有效地址传递价值?
【解决方案3】:

我已经解决了我的问题。我通过onCreatmethod 中的editText 字段传递我的位置字符串,这就是我的addressList 无法在列表中找到位置并且出现错误。当我在setOnClickListener 方法中声明我的editText 时,我的列表会像这样在其中找到位置:

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));

                }

            }
        });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-11
    • 1970-01-01
    • 2012-12-09
    • 1970-01-01
    • 1970-01-01
    • 2021-07-12
    • 1970-01-01
    相关资源
    最近更新 更多