【问题标题】:Error after not altering code不修改代码后出错
【发布时间】:2015-07-09 01:53:54
【问题描述】:

在数周内我什至没有接触代码并说它与 Arraylist 相关后,我得到了这个错误。这是我得到的错误。

java.lang.RuntimeException:无法启动活动 组件信息{com.example.android.login/com.example.android.login.MainActivity}: java.lang.IndexOutOfBoundsException:索引 0 无效,大小为 0 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2712) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2777) 在 android.app.ActivityThread.access$900(ActivityThread.java:179) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1462) 在 android.os.Handler.dispatchMessage(Handler.java:102) 在 android.os.Looper.loop(Looper.java:145) 在 android.app.ActivityThread.main(ActivityThread.java:5972) 在 java.lang.reflect.Method.invoke(本机方法) 在 java.lang.reflect.Method.invoke(Method.java:372) 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1388) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183) 引起:java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 在 java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255) 在 java.util.ArrayList.get(ArrayList.java:308) 在 com.example.android.login.MainActivity.onCreate(MainActivity.java:66) 在 android.app.Activity.performCreate(Activity.java:6289) 在 android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119) 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2777) 在 android.app.ActivityThread.access$900(ActivityThread.java:179) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1462) 在 android.os.Handler.dispatchMessage(Handler.java:102) 在 android.os.Looper.loop(Looper.java:145) 在 android.app.ActivityThread.main(ActivityThread.java:5972) 在 java.lang.reflect.Method.invoke(本机方法) 在 java.lang.reflect.Method.invoke(Method.java:372) 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1388) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)

这是我的代码:

package com.example.android.login;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.location.Address;
import android.location.Geocoder;
import android.os.BatteryManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.parse.LogOutCallback;
import com.parse.Parse;
import com.parse.ParseObject;
import com.parse.ParseUser;

import com.parse.ParseException;

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


public class MainActivity extends ActionBarActivity {

    private Toolbar toolbar;
    public Button logoutButton;
    public int level;
    Button btnShowLocation;
    GPSTracker gps;
    public Button request_battery;


    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_appbar);
        gps = new GPSTracker(MainActivity.this);
        if(gps.canGetLocation()){
            double latitude = gps.getLatitude();
            double longitude = gps.getLongitude();
            Geocoder geocoder;
            List<Address> addresses = null;
            geocoder = new Geocoder(this, Locale.getDefault());

            try {
                addresses = geocoder.getFromLocation(latitude, longitude, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
            } catch (IOException e) {
                e.printStackTrace();
            }

            String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
            String city = addresses.get(0).getLocality();
            String state = addresses.get(0).getAdminArea();
            String country = addresses.get(0).getCountryName();
            String postalCode = addresses.get(0).getPostalCode();
            String knownName = addresses.get(0).getFeatureName();
            // final TextView mTextView = (TextView) findViewById(R.id.location);
            //mTextView.setText("Latitude "+latitude+" Longitude "+longitude);
            final TextView mAdressTextView = (TextView) findViewById(R.id.addressNum);
            mAdressTextView.setText(address);
            final TextView mStateTextView = (TextView) findViewById(R.id.stateNum);
            mStateTextView.setText(city+ ", "+ state+", " + postalCode);
        }else{
            gps.showSettingsAlert();
        }
        request_battery= (Button) findViewById(R.id.request_battery);
        request_battery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(MainActivity.this, Payment.class);

                startActivity(i);
            }
        });
       /* btnShowLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gps = new GPSTracker(MainActivity.this);
                if(gps.canGetLocation()){
                    double latitude = gps.getLatitude();
                    double longitude = gps.getLongitude();
                    final TextView mTextView = (TextView) findViewById(R.id.location);
                    mTextView.setText("Latitude "+latitude+" Longitude "+longitude);

                }else{
                    gps.showSettingsAlert();
                }*/

        batteryTxt = (TextView) this.findViewById(R.id.percent);
        this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        toolbar = (Toolbar) findViewById(R.id.app_bar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        NavigationDrawerFragment drawerFragment = (NavigationDrawerFragment)
                getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
        drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawerLayout), toolbar);

        logoutButton = (Button) findViewById(R.id.logoutButton);
        logoutButton.setOnClickListener(new View.OnClickListener() {
            @Override
             public void onClick(View v) {
                // Set up a progress dialog
                final ProgressDialog logout = new ProgressDialog(MainActivity.this);
                logout.setTitle("Please wait.");
                logout.setMessage("Logging out.  Please wait.");
                logout.show();
                ParseUser.logOutInBackground(new LogOutCallback() {

                    public void done(ParseException e) {
                        logout.dismiss();
                        if (e == null) {
                            Intent logoutDone = new Intent(MainActivity.this, DispatchActivity.class);
                            startActivity(logoutDone);
                        } else {
                            Toast.makeText(MainActivity.this, "Logout Unsuccessful", Toast.LENGTH_LONG).show();
                        }
                    }
                });
            }
        });


    }

    private TextView batteryTxt;
    private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context ctxt, Intent intent) {
            int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
            batteryTxt.setText(String.valueOf(level) + "%");
        }
    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

}

【问题讨论】:

    标签: java android


    【解决方案1】:

    嗯,很明显的代码:

    addresses = geocoder.getFromLocation(latitude, longitude, 1);
    

    正在返回一个空列表。在此之后添加一条日志语句以确保打印列表的大小。

    Log.i(TAG, "The size is: " + addresses.size());
    

    【讨论】:

      【解决方案2】:

      您似乎在这里得到了一个大小为零的列表:

       addresses = geocoder.getFromLocation(latitude, longitude, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
      

      因此您访问其第 0 个元素的行会抛出 ArrayIndexOutOfBoundsException:

       String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
      

      您应该在代码中进行安全检查,以确保列表不为 NULL 且大小大于 0

      【讨论】:

        猜你喜欢
        • 2015-04-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-02
        • 1970-01-01
        • 2018-06-26
        • 1970-01-01
        相关资源
        最近更新 更多