0

我有一个 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))
}

}

当我在微调器中选择最后一项“Petak 4”并使用按钮删除该项目时,

此代码在 onClick 按钮方法内工作,带有开关盒。

但是当我将代码放入 onActivityResult 时,应用程序被强制关闭

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

这是我的日志猫

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 的吗?

4

3 回答 3

2

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

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

于 2013-03-07T05:23:52.310 回答
1

如果您想获得 Spinner 选择的项目位置,那么只需使用

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();
于 2013-03-07T05:24:22.197 回答
0

是的,它ArrayList与您的代码中的一个有关。在某些时候,您dataAdapter拥有 size 3,并且您试图访问 index 处的元素3,这是 throwing IndexOutOfBoundsException。永远记住,如果你的大小ArrayListx,你只能访问到 index x-1

例如:如果大小为4,则

list.get(3)-允许

list.get(4)-不允许

于 2013-03-07T05:21:42.267 回答