Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/206.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/215.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android arraylist微调器中的indexoutofboundsexception_Android_Android Spinner - Fatal编程技术网

Android arraylist微调器中的indexoutofboundsexception

Android arraylist微调器中的indexoutofboundsexception,android,android-spinner,Android,Android Spinner,我有一个值为4的旋转器 这是完整的代码 public class MainUpdate extends Activity implements LocationListener{ Spinner fromList; Spinner toList; ArrayAdapter<String> dataAdapter; // membuat combobox manual manufaktur //TextVie

我有一个值为4的旋转器

这是完整的代码

public class MainUpdate extends Activity implements LocationListener{


        Spinner fromList;
        Spinner toList;
        ArrayAdapter<String> dataAdapter;
    // membuat combobox manual manufaktur
        //TextView selection;
        private LocationManager locman;
         public static final int DIALOG_DATE = 5;

        //String[] petak = { "Petak 1", "Petak 2", "Petak 3", "Petak 4" };

        private Uri outputFileUri;
        File outputFile;
        Intent intent = null;
        CDBPetak cDBPetak=null;
        TextView tvStatus=null;
        Spinner spinPetak;
        private String sDirectory="";
        //GPS Value---
        private double dLat=0;
        private double dLon=0;

        private  static final boolean TEST_ONLY_NO_FOTO=false;
        private  static final boolean TAKE_FOTO_HIRES=false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ptk_main_update);

        this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);


        toList = (Spinner) findViewById(R.id.namapetak);
          dataAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, new ArrayList<String>());
          dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
          toList.setAdapter(dataAdapter);
          dataAdapter.add("Petak 1");
          dataAdapter.add("Petak 2");
          dataAdapter.add("Petak 3");
          dataAdapter.add("Petak 4");


        Button button = (Button) findViewById(R.id.btnPupukQuit);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
                LogOut();
                setResult(RESULT_OK, null);
                finish();
            }
        });

        locman = (LocationManager) getSystemService(LOCATION_SERVICE);

        /*View showDlg = findViewById(R.id.jenis);
        showDlg.setOnClickListener(new View.OnClickListener(){
         public void onClick(View v) {
             // Perform action on click
            showDialog(DIALOG_DATE);
         }
        });*/

        tvStatus= (TextView) findViewById(R.id.txtStatus);


        if (CGeneral.nPetakTetap==CGeneral.ACTIVITY_FOR_PETAK) {
            //txt.setText(CGeneral.STRING_LAYOUT_HEADER_PUPUK);
            sDirectory=CGeneral.STRING_DIRECTORY_PETAK;
            cDBPetak=new CDBPetak(this,CGeneral.STRING_DBASE_PETAK,CGeneral.INT_DBASE_VERSION_PETAK);
        }


        button = (Button) findViewById(R.id.btnPetakFoto);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click

                TakeFoto();





            EditText hapus1=(EditText) findViewById(R.id.jenisHama);
            hapus1.setText("");
            EditText hapus2=(EditText) findViewById(R.id.jmlhHama);
            hapus2.setText("");
            EditText hapus3=(EditText) findViewById(R.id.jnsMusuh);
            hapus3.setText("");
            EditText hapus4=(EditText) findViewById(R.id.jmlhMusuh);
            hapus4.setText("");
            EditText hapus5=(EditText) findViewById(R.id.intenTetap);
            hapus5.setText("");
            EditText hapus6=(EditText) findViewById(R.id.luasTerancam);
            hapus6.setText("");

            }
        });

    }//onCreate

    private void TakeFoto(){
        Date dt=new Date();
        long lt=dt.getTime(); lt=lt/10;
        String fname=String.format("%d.jpg", lt);
        File path = Environment.getExternalStoragePublicDirectory(sDirectory);
        path.mkdirs();
        outputFile = new File(path,fname);
        outputFileUri = Uri.fromFile(outputFile);
        if (TEST_ONLY_NO_FOTO) {
            SaveData();
        }
        else{
            if (TAKE_FOTO_HIRES){
                saveFullImage();
            }
            else{
                getThumbailPicture();
            }
        }
        TextView txt = (TextView) findViewById(R.id.txtStatus);
        txt.setText(fname);
    }//TakeFoto

private void LogOut(){

    }//LogOut

private void getThumbailPicture() {
    if (TEST_ONLY_NO_FOTO) return;
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    startActivityForResult(intent, CGeneral.SHOW_SUB_ACTIVITY_TAKE_PICTURE);
}//getThumbailPicture

private void saveFullImage() {
    if (TEST_ONLY_NO_FOTO) return;
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
    startActivityForResult(intent, CGeneral.SHOW_SUB_ACTIVITY_TAKE_PICTURE);
}//saveFullImage

@Override
protected void onDestroy() {
    stopListening();
    super.onDestroy();
}

@Override
protected void onPause() {
    stopListening();
    super.onPause();
}

@Override
protected void onResume() {
    startListening();
    super.onResume();
}

private void startListening() {
    locman.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}

private void stopListening() {
    if (locman != null) {
        locman.removeUpdates(this);
    }
}
@Override
public void onLocationChanged(Location location) {
    // TODO Auto-generated method stub
    boolean flag=ValidLocation(location);
}//onLocationChanged

@Override
public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub

}//onProviderDisabled

@Override
public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub

}//onProviderEnabled

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub

}//onStatusChanged


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    //menu.add(0, CGeneral.MENUID_SEND_PETAK, 0, R.string.mnuSend);
    //menu.add(0, CGeneral.MENUID_OPTION, 0, R.string.mnuOption);
    menu.add(0, CGeneral.MENUID_VIEW_PETAK, 0, R.string.mnuView);

    return true;
}//onCreateOptionsMenu

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    Intent intent=null;
    final TextView tview = (TextView) findViewById(R.id.txtStatus);      
    Resources res=getResources(); 
    switch (item.getItemId()) {

    //case CGeneral.MENUID_SEND:

        //return true;
    case CGeneral.MENUID_OPTION:
        /*CPupukRecord rec=new CPupukRecord();
        for (int i=0; i<recordCount; i++){
            rec.sFilename=cursorSend.getString(4);
        UserFunctions userFunction = new UserFunctions();
        Log.d("Button", "Login");
        JSONObject json = userFunction.sendUser(rec.sFilename);
        }*/
    case CGeneral.MENUID_VIEW_PETAK:
        intent = new Intent(MainUpdate.this, CPetakView.class);
        startActivityForResult(intent, CGeneral.SHOW_SUB_ACTIVITY_VIEW_PETAK);
        tview.setText("menuItem : "+res.getString(R.string.mnuView));
        return true;
    }
    return super.onOptionsItemSelected(item);
}//onOptionsItemSelected(MenuItem item


private boolean ValidLocation(Location location)
{
    dLat=location.getLatitude();
    dLon=location.getLongitude();

    String slat="";
    String slon="";
    String sacc="";
    String sspd="";
    slat=String.format("%+5.12f", dLat);
    slon=String.format("%+5.12f", dLon);
    TextView txt;
    //Menampilkan Latitude longitude
    txt = (TextView) findViewById(R.id.edtLatitude);
    txt.setText(slat);
    txt = (TextView) findViewById(R.id.edtLongitude);
    txt.setText(slon);
    //txt = (TextView) findViewById(R.id.edtPupukAccuracy);
    //txt.setText(sacc);
    //txt = (TextView) findViewById(R.id.edtPupukSpeed);
    //txt.setText(sspd);

    if (CGeneral.TEST_ONLY_NO_LOCATION_VALIDATION) return true;

    return true; 
}//ValidLocation

private void SaveData(){

    View textJnsHama = (EditText) findViewById(R.id.jenisHama);
    View textJmlHama = (EditText) findViewById(R.id.jmlhHama);
    View textJnsMusuh = (EditText) findViewById(R.id.jnsMusuh);
    View textJmlMusuh = (EditText) findViewById(R.id.jmlhMusuh);
    View textIntens = (EditText) findViewById(R.id.intenTetap);
    View textLuasInten = (EditText) findViewById(R.id.luasTerancam);
    //View editText8 = (EditText) findViewById(R.id.txtManufaktur);
    View spinner1 = (Spinner) findViewById(R.id.namapetak);
    //manufakturButton.setText(stringBuilder.toString());
    String jnsHama=((TextView) textJnsHama).getText().toString();
    String jmlHama=((TextView) textJmlHama).getText().toString();
    String jnsMusuh=((TextView) textJnsMusuh).getText().toString();
    String jmlMusuh=((TextView) textJmlMusuh).getText().toString();
    String intens=((TextView) textIntens).getText().toString();
    String luasInten=((TextView) textLuasInten).getText().toString();
    String spinnerPetak=((Spinner) spinner1).getSelectedItem().toString();







    CPetakRecord rec=new CPetakRecord();
    Date dt=new Date();
    rec.jenisHm=jnsHama;
    rec.jumlahHm=jmlHama;
    rec.jenisMsh=jnsMusuh;
    //rec.lblKomoditas=spinnerKmdLabel;
    rec.jumlahMsh=jmlMusuh;
    rec.intensitas=intens;
    rec.luasTerancam=luasInten;
    //rec.lblHama=spinnerHamaLabel;
    rec.nmPetak=spinnerPetak;
    rec.dLatitude=dLat;
    rec.dLongitude=dLon;
    rec.sFilename=outputFile.toString();
//  rec.sFilename=outputFileUri.toString();
    rec.lDate=dt.getTime();
    rec.sSent="Not Sent";
    cDBPetak.insertEntry(rec);

}//SaveData

@Override
public void onBackPressed() {
}

@Override
public void onAttachedToWindow() {
    this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
    super.onAttachedToWindow();
}

@Override
public void onActivityResult(int requestCode,int resultCode,Intent data) {
    String str="";

    super.onActivityResult(requestCode, resultCode, data);
    switch(requestCode) {
    case (CGeneral.SHOW_SUB_ACTIVITY_LOGIN) :
        if (resultCode == Activity.RESULT_OK) {
            //+isLogin=true;
            tvStatus.setText("Login Ok - userId : "+CGeneral.strUserID);
        }
        if (resultCode == Activity.RESULT_CANCELED) {
            setResult(RESULT_CANCELED, null);
            finish();
        }
        break;
    case (CGeneral.SHOW_SUB_ACTIVITY_VIEW) :
        break;
    case (CGeneral.SHOW_SUB_ACTIVITY_TAKE_PICTURE) :

        if (resultCode == Activity.RESULT_OK) {
            str="Camera Result : Ok";

            String myData = toList.getSelectedItem().toString();
              int position = dataAdapter.getPosition(myData);


               if(position >= 0){
                dataAdapter.remove(myData);
                dataAdapter.notifyDataSetChanged();
               }
               else {
                Toast.makeText(getBaseContext(), myData + " not in Spinner", Toast.LENGTH_LONG).show();
               }



            View b = findViewById(R.id.btnPupukQuit);
            b.setVisibility(View.GONE);
            onBackPressed();
            onAttachedToWindow();





            if (!CGeneral.TEST_ONLY_NO_LOCATION_VALIDATION){
                EnableFoto(false); // foto has been taken,disable it until new location

            }
            // Check if the result includes a thumbnail Bitmap
            if (data != null) {
                str=str+" A";
                if (data.hasExtra("data")) {
                    Bitmap thumbnail = data.getParcelableExtra("data");
//                  ImageView img;
//                  img=(ImageView)findViewById(R.id.imgView); 
//                  img.setImageBitmap(thumbnail);

                    str=str+" B";
                    try {
                        str=str+" B1";
                        String fname=outputFile.toString();
                        str=str+" fname:"+fname;
                        FileOutputStream fos=new FileOutputStream(outputFile);

                        thumbnail.compress(Bitmap.CompressFormat.PNG, 90, fos);
                        SaveData();
                        str=str+" B2";


                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        str=str+" B3";
                        e.printStackTrace();
                    } 

                }
            }
            else {
                str=str+" C";
                // TODO Do something with the full image stored
                // in outputFileUri
                SaveData();
            }
            str=str+" D";
        }
        if (resultCode == Activity.RESULT_CANCELED) {
            str="Camera Result : Canceled";
        }
        tvStatus.setText(str);
        break;
    }       
}//onActivityResult

public void EnableFoto(boolean flag){
    Button button = (Button) findViewById(R.id.btnPetakFoto);
    if (flag){
        button.setVisibility(View.VISIBLE);
    }
    else {//if (ValidLocation(location))
        button.setVisibility(View.INVISIBLE);
    }//if (ValidLocation(location))
}

}
这是我的日志

03-07 12:03:30.156: ERROR/AndroidRuntime(7543): FATAL EXCEPTION: main
03-07 12:03:30.156: ERROR/AndroidRuntime(7543): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=5, result=-1, data=Intent { act=inline-data (has extras) }} to activity {hariff.ltis.mainmenu/hariff.ltis.petaktetap.MainUpdate}: java.lang.IndexOutOfBoundsException: Invalid index 3, size is 3
03-07 12:03:30.156: ERROR/AndroidRuntime(7543):     at android.app.ActivityThread.deliverResults(ActivityThread.java:2532)
03-07 12:03:30.156: ERROR/AndroidRuntime(7543):     at android.app.ActivityThread.handleSendResult(ActivityThread.java:2574)
03-07 12:03:30.156: ERROR/AndroidRuntime(7543):     at android.app.ActivityThread.access$2000(ActivityThread.java:117)
03-07 12:03:30.156: ERROR/AndroidRuntime(7543):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:961)
03-07 12:03:30.156: ERROR/AndroidRuntime(7543):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-07 12:03:30.156: ERROR/AndroidRuntime(7543):     at android.os.Looper.loop(Looper.java:130)
03-07 12:03:30.156: ERROR/AndroidRuntime(7543):     at android.app.ActivityThread.main(ActivityThread.java:3683)
03-07 12:03:30.156: ERROR/AndroidRuntime(7543):     at java.lang.reflect.Method.invokeNative(Native Method)
03-07 12:03:30.156: ERROR/AndroidRuntime(7543):     at java.lang.reflect.Method.invoke(Method.java:507)
03-07 12:03:30.156: ERROR/AndroidRuntime(7543):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
03-07 12:03:30.156: ERROR/AndroidRuntime(7543):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
03-07 12:03:30.156: ERROR/AndroidRuntime(7543):     at dalvik.system.NativeStart.main(Native Method)
03-07 12:03:30.156: ERROR/AndroidRuntime(7543): Caused by: java.lang.IndexOutOfBoundsException: Invalid index 3, size is 3
03-07 12:03:30.156: ERROR/AndroidRuntime(7543):     at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:257)
03-07 12:03:30.156: ERROR/AndroidRuntime(7543):     at java.util.ArrayList.get(ArrayList.java:311)
03-07 12:03:30.156: ERROR/AndroidRuntime(7543):     at android.widget.ArrayAdapter.getItem(ArrayAdapter.java:298)
03-07 12:03:30.156: ERROR/AndroidRuntime(7543):     at android.widget.AdapterView.getSelectedItem(AdapterView.java:552)
03-07 12:03:30.156: ERROR/AndroidRuntime(7543):     at hariff.ltis.petaktetap.MainUpdate.SaveData(MainUpdate.java:344)
03-07 12:03:30.156: ERROR/AndroidRuntime(7543):     at hariff.ltis.petaktetap.MainUpdate.onActivityResult(MainUpdate.java:481)
03-07 12:03:30.156: ERROR/AndroidRuntime(7543):     at android.app.Activity.dispatchActivityResult(Activity.java:3908)
03-07 12:03:30.156: ERROR/AndroidRuntime(7543):     at android.app.ActivityThread.deliverResults(ActivityThread.java:2528)
如何修复错误
indexoutofboundsexception


它是关于ArrayList的?

是的,它是关于代码中的
ArrayList的。在某个时刻,您的
数据适配器的大小为
3
,您正试图访问索引
3
处的元素,这会引发
IndexOutOfBoundsException
。请始终记住,如果
ArrayList
的大小为
x
,则只能访问索引
x-1

例如:如果大小为
4
,则

列表。获取(3)
-是允许的


列表。获取(4)
-是不允许的

是的,它是关于代码中的
数组列表。在某个时刻,您的
数据适配器的大小为
3
,您正试图访问索引
3
处的元素,这会引发
IndexOutOfBoundsException
。请始终记住,如果
ArrayList
的大小为
x
,则只能访问索引
x-1

例如:如果大小为
4
,则

列表。获取(3)
-是允许的


list.get(4)
-不允许调用
dataAdapter.remove()
,而不更改微调器中选定的索引。然后在
SaveData()
函数中调用
spinner1.getSelectedItem()
,从而产生
IndexOutOfBoundsException


解决方案是什么?将所选索引设置为从适配器中删除项目后仍然存在的索引。

您正在调用
dataAdapter.remove()
,而不更改微调器中的所选索引。然后在
SaveData()
函数中调用
spinner1.getSelectedItem()
,从而产生
IndexOutOfBoundsException


解决方案是什么?将所选索引设置为从适配器中删除项目后仍然存在的索引。

如果要获得微调器所选项目位置,只需使用

spinner.getSelectedItemPosition() which gives integer value..
为什么要使用

String myData = toList.getSelectedItem().toString();
int position = dataAdapter.getPosition(myData); // I think the problem is here
您可以直接初始化

int position = toList.getSelectedItemPosition();

如果您想获得微调器选中的项目位置,只需使用

spinner.getSelectedItemPosition() which gives integer value..
为什么要使用

String myData = toList.getSelectedItem().toString();
int position = dataAdapter.getPosition(myData); // I think the problem is here
您可以直接初始化

int position = toList.getSelectedItemPosition();

第344行和第481行?第344行和第481行?当我使用
int position=toList.getSelectedItemPosition()更改时,仍然强制关闭
indexoutofboundsexception
当我使用
int position=toList.getSelectedItemPosition()更改时,仍然强制关闭
indexoutofboundsexception
是的,我错了,现在我在删除项之前放置了
SaveData()
方法。而且有效。谢谢,我错了,现在我把
SaveData()。而且有效。谢谢