Java IndexoutOfbound异常使用Artroid中的ArrowList[英] Java IndexOutOfBound exception Using arraylist in Android

问题描述

我是Android开发的新手.我在这个代码中使用名为捐赠者的userdefined arraylist,但它给了我错误.我看到了同样的错误在这里发布了很多时间,但我仍然无法找到我的解决方案.请帮忙.谢谢

05-01 23:45:10.855 1756-3399/com.donateblood.blooddonation E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #2
                                                                             Process: com.donateblood.blooddonation, PID: 1756
                                                                             java.lang.RuntimeException: An error occured while executing doInBackground()
                                                                                 at android.os.AsyncTask$3.done(AsyncTask.java:300)
                                                                                 at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
                                                                                 at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
                                                                                 at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                                                                                 at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
                                                                                 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                                                                                 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                                                                                 at java.lang.Thread.run(Thread.java:818)
                                                                              Caused by: 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.donateblood.blooddonation.MainGUI.getOtherLatLong(MainGUI.java:136)
                                                                                 at com.donateblood.blooddonation.MainGUI$dbAsync.doInBackground(MainGUI.java:89)
                                                                                 at com.donateblood.blooddonation.MainGUI$dbAsync.doInBackground(MainGUI.java:84)
                                                                                 at android.os.AsyncTask$2.call(AsyncTask.java:288)
                                                                                 at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                                 at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
                                                                                 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
                                                                                 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
                                                                                 at java.lang.Thread.run(Thread.java:818) 
05-01 23:45:11.525 1756-1756/com.donateblood.blooddonation E/WindowManager: android.view.WindowLeaked: Activity com.donateblood.blooddonation.MainGUI has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{28ea9195 V.E..... R......D 0,0-1026,348} that was originally added here
                                                                                at android.view.ViewRootImpl.<init>(ViewRootImpl.java:382)
                                                                                at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:261)
                                                                                at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
                                                                                at android.app.Dialog.show(Dialog.java:298)
                                                                                at com.donateblood.blooddonation.MainGUI$dbAsync.onPreExecute(MainGUI.java:100)
                                                                                at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
                                                                                at android.os.AsyncTask.execute(AsyncTask.java:535)
                                                                                at com.donateblood.blooddonation.MainGUI$1.onClick(MainGUI.java:63)
                                                                                at android.view.View.performClick(View.java:4785)
                                                                                at android.view.View$PerformClick.run(View.java:19858)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:155)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5696)
                                                                                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:1028)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
05-01 23:45:47.083 1756-3399/com.donateblood.blooddonation D/Process: killProcess, pid=1756
05-01 23:45:47.083 1756-3399/com.donateblood.blooddonation D/Process: com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException:138 java.lang.ThreadGroup.uncaughtException:693 java.lang.ThreadGroup.uncaughtException:690 
package com.donateblood.blooddonation;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by YouCaf Iqbal on 4/6/2016.
 */
public class MainGUI extends AppCompatActivity {
    public static List<DonorPerson> Donors = new ArrayList<DonorPerson>();
    @InjectView(R.id.findppl) Button _findButton;
    GPSTracker gps;
    private double latitude;
    private double longitude;
    DB db; String test="";
    DBCursor cursor;
    DBCollection collection;
    Database dataobj = new Database();
    ArrayList allPPLlat = new ArrayList();
    ArrayList allPPLlong = new ArrayList();
    ArrayList allPPLNumbers = new ArrayList();
    ArrayList allPPLNames = new ArrayList();
    ArrayList allPPLImages = new ArrayList();
    ArrayList allPPLEmails = new ArrayList();
    ArrayList SelectedPPLlat = new ArrayList();
    ArrayList SelectedPPLlong = new ArrayList();
    public Spinner mySpinner;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.maingui);
        ButterKnife.inject(this);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        Spinner spinner =(Spinner) findViewById(R.id.spinner);
        String[] list = getResources().getStringArray(R.array.blood_type);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.spinner_layout,R.id.txt,list);
        spinner.setAdapter(adapter);
        _findButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getCurrentLatLong();
                dbAsync thrd = new dbAsync();
                thrd.execute();
            }
            //distance=Distance(lablat, lablong, curlat, curlong);
        });
    }
    public void getCurrentLatLong(){
        gps = new GPSTracker(MainGUI.this);
        if (gps.canGetLocation()) {
            latitude = gps.getLatitude();
            longitude = gps.getLongitude();
        }
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId()==android.R.id.home){
            finish();
        }
        return super.onOptionsItemSelected(item);
    }


    public class dbAsync extends AsyncTask<Void,Void,Void>{
        private ProgressDialog pDialog;

        @Override
        protected Void doInBackground(Void... voids) {
            getOtherLatLong();
            return null;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainGUI.this);
            pDialog.setMessage("Searching people nearby...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @Override
        protected void onPostExecute(Void aVoid) {

            super.onPostExecute(aVoid);
            pDialog.dismiss();
            Intent intent = new Intent(getApplicationContext(), PeopleList.class);
            startActivity(intent);
           // Toast.makeText(getBaseContext(), "Near by latitudes "+SelectedPPLlat, Toast.LENGTH_LONG).show();
           // Toast.makeText(getBaseContext(), "Near by longitudes "+SelectedPPLlong, Toast.LENGTH_LONG).show();
        }
    }

    public void getOtherLatLong() {
        db = dataobj.getconnection();
        collection = db.getCollection("UserDetails");
        cursor = collection.find();
        while (cursor.hasNext()) {
            DBObject doc = cursor.next();
            // Lats longs used in the next for Loop for calculation distances
            allPPLlat.add(doc.get("lat"));
            allPPLlong.add(doc.get("long"));
            // All these other arraylists are used to store object of a donor person
            allPPLEmails.add(doc.get("number").toString());
            allPPLNames.add(doc.get("Name").toString());
            allPPLImages.add(doc.get("image").toString());
            allPPLEmails.add(doc.get("email").toString());

        }

        for(int i =0;i<allPPLlat.size();i++){
           double Dist= Distance((double)allPPLlat.get(i),(double)allPPLlong.get(i),latitude,longitude);
            Dist=Dist/1000;
            if(Dist<20){
                Donors.add(new DonorPerson(""+allPPLNames.get(i)+"", ""+allPPLEmails.get(i)+"" ,""+allPPLNumbers.get(i)+"" ,""+allPPLImages.get(i)+""));
            }
        }
    }

    public double Distance(double lat1, double lon1, double lat2, double lon2) {
        double R = 6371.0; // km
        double dLat = (lat2 - lat1) * Math.PI / 180.0;
        double dLon = (lon2 - lon1) * Math.PI / 180.0;
        lat1 = lat1 * Math.PI / 180.0;
        lat2 = lat2 * Math.PI / 180.0;

        double a = Math.sin(dLat / 2.0) * Math.sin(dLat / 2.0) +
                Math.sin(dLon / 2.0) * Math.sin(dLon / 2.0) * Math.cos(lat1) * Math.cos(lat2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        double d = R * c;
        return d * 1000; // return distance in m
    }
}

推荐答案

在本部分:

for(int i =0;i<allPPLlat.size();i++){
           double Dist= Distance((double)allPPLlat.get(i),(double)allPPLlong.get(i),latitude,longitude);
            Dist=Dist/1000;
            if(Dist<20){
                Donors.add(new DonorPerson(""+allPPLNames.get(i)+"", ""+allPPLEmails.get(i)+"" ,""+allPPLNumbers.get(i)+"" ,""+allPPLImages.get(i)+""));
            }
        }

您正在为空阵列的位置get执行一个get,它不存在并抛出您所看到的错误.堆栈跟踪实际上指向您的确切位置.

本文地址:https://www.itbaoku.cn/post/978663.html