Click here to Skip to main content
15,879,474 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
When i remove item automatic, my app is force close because of index out of bound
so here is my code
Java
<pre>package com.example.eis2;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.eis2.Item.approvalnonfullmodel;
import com.example.eis2.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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

import static com.example.eis2.Item.LoginItem.KEY_NIK;
import static com.example.eis2.izin.txt_jabatan;
import static com.example.eis2.izin.txt_nomor;

public class approval_nonfull extends AppCompatActivity {
    public ListView listok;
    private List<approvalnonfullmodel> movieItemList;
    Button notapprove, approve;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_approval_nonfull);
        listok = findViewById(R.id.list);

        movieItemList = new ArrayList<>();
        notapprove = (Button) findViewById(R.id.notapprove);
        notapprove.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(approval_nonfull.this, nonfull_noapprove.class);
                startActivity(i);
            }
        });

        approve = (Button) findViewById(R.id.approve);
        approve.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(approval_nonfull.this, nonfull_yesapprove.class);
                startActivity(i);
            }
        });
        fullday();
    }

    private void fullday() {
        String lokasi = txt_nomor.getText().toString().trim();
        System.out.println("Test" + lokasi);


        StringRequest stringRequest = new StringRequest(Request.Method.GET, "...",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        try {
                            JSONObject obj = new JSONObject(response);
                            final JSONArray movieArray = obj.getJSONArray("data");

                            JSONObject movieObject = null;
                            for (int i = 0; i < movieArray.length(); i++) {

                                movieObject = movieArray.getJSONObject(i);

                                final approvalnonfullmodel movieItem = new approvalnonfullmodel(
                                        movieObject.getString("id_non_full"),
                                        movieObject.getString("no_pengajuan_non_full"),
                                        movieObject.getString("tanggal_pengajuan"),
                                        movieObject.getString("lokasi_struktur"),
                                        movieObject.getString("nama_karyawan_struktur"),
                                        movieObject.getString("jenis_non_full"),
                                        movieObject.getString("tanggal_non_full"),
                                        movieObject.getString("ket_tambahan_non_full"),
                                        movieObject.getString("status_non_full"),
                                        movieObject.getString("feedback_non_full"));

                                movieItemList.add(movieItem);

                            }
                            final ListViewAdapterApprovalNonFull adapter = new  ListViewAdapterApprovalNonFull(movieItemList, getApplicationContext());

                            listok.setAdapter(adapter);
                            listok.setStackFromBottom(true);

                            listok.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                                    Intent i = new Intent(approval_nonfull.this, form_nonfull.class);
                                    String idkaryawan = ((approvalnonfullmodel) parent.getItemAtPosition(position)).getId_non_full();
                                    i.putExtra(KEY_NIK, idkaryawan);
                                    startActivity(i);
                                }
                            });


                            adapter.notifyDataSetChanged();

                        } catch (JSONException e) {
                            e.printStackTrace();

                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getApplicationContext(), "Belum ada pengajuan", Toast.LENGTH_SHORT).show();
                    }
                });


        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }
    public void refreshActivity() {
        Intent i = new Intent(this, approval_izin.class);
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(i);
        finish();
    }
    @Override
    public void onBackPressed() {
        refreshActivity();
        super.onBackPressed();
    }
    public class ListViewAdapterApprovalNonFull extends ArrayAdapter<approvalnonfullmodel> {
        private List<approvalnonfullmodel> movieItemList;

        private Context context;

        public ListViewAdapterApprovalNonFull(List<approvalnonfullmodel> movieItemList, Context context) {
            super(context, R.layout.list_item_approval_nonfull, movieItemList);
            this.movieItemList = movieItemList;
            this.context = context;
        }
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            LayoutInflater inflater = LayoutInflater.from(context);

            View listViewItem = inflater.inflate(R.layout.list_item_approval_nonfull, null, true);

            TextView id = listViewItem.findViewById(R.id.id);
            TextView nama = listViewItem.findViewById(R.id.nama);
            TextView lokasi = listViewItem.findViewById(R.id.lokasi);
            TextView jenis = listViewItem.findViewById(R.id.jenis);
            TextView tanggal = listViewItem.findViewById(R.id.tanggal);
            TextView keterangan = listViewItem.findViewById(R.id.keterangan);
            TextView status = listViewItem.findViewById(R.id.status);
            TextView feedback = listViewItem.findViewById(R.id.feedback);

            approvalnonfullmodel movieItem = movieItemList.get(position);

            id.setText(movieItem.getId_non_full());
            nama.setText(movieItem.getNama_karyawan_struktur());
            lokasi.setText(movieItem.getLokasi_struktur());
            jenis.setText(movieItem.getJenis_non_full());
            tanggal.setText(movieItem.getTanggal_non_full());
            keterangan.setText(movieItem.getKet_tambahan_non_full());
            status.setText(movieItem.getStatus_non_full());
            feedback.setText(movieItem.getFeedback_non_full());

            if(!txt_jabatan.getText().toString().equals(lokasi.getText().toString())){
                movieItemList.remove(position);
                this.notifyDataSetChanged();
            }
            if ("0".equals(status.getText().toString())) {
                status.setText("Menunggu Atasan");
                this.notifyDataSetChanged();
            }

            if("1".equalsIgnoreCase(status.getText().toString()) || "2".equalsIgnoreCase(status.getText().toString()) || "3".equalsIgnoreCase(status.getText().toString())) {
                movieItemList.remove(position);
                listViewItem.setVisibility(View.INVISIBLE);
                this.notifyDataSetChanged();
            }

            return listViewItem;
        }
    }
}


What I have tried:

This code is use for remove and getting position

Java
<pre>public class ListViewAdapterApprovalNonFull extends ArrayAdapter<approvalnonfullmodel> {
        private List<approvalnonfullmodel> movieItemList;

        private Context context;

        public ListViewAdapterApprovalNonFull(List<approvalnonfullmodel> movieItemList, Context context) {
            super(context, R.layout.list_item_approval_nonfull, movieItemList);
            this.movieItemList = movieItemList;
            this.context = context;
        }
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            LayoutInflater inflater = LayoutInflater.from(context);

            View listViewItem = inflater.inflate(R.layout.list_item_approval_nonfull, null, true);

            TextView id = listViewItem.findViewById(R.id.id);
            TextView nama = listViewItem.findViewById(R.id.nama);
            TextView lokasi = listViewItem.findViewById(R.id.lokasi);
            TextView jenis = listViewItem.findViewById(R.id.jenis);
            TextView tanggal = listViewItem.findViewById(R.id.tanggal);
            TextView keterangan = listViewItem.findViewById(R.id.keterangan);
            TextView status = listViewItem.findViewById(R.id.status);
            TextView feedback = listViewItem.findViewById(R.id.feedback);

            approvalnonfullmodel movieItem = movieItemList.get(position);

            id.setText(movieItem.getId_non_full());
            nama.setText(movieItem.getNama_karyawan_struktur());
            lokasi.setText(movieItem.getLokasi_struktur());
            jenis.setText(movieItem.getJenis_non_full());
            tanggal.setText(movieItem.getTanggal_non_full());
            keterangan.setText(movieItem.getKet_tambahan_non_full());
            status.setText(movieItem.getStatus_non_full());
            feedback.setText(movieItem.getFeedback_non_full());

            if(!txt_jabatan.getText().toString().equals(lokasi.getText().toString())){
                movieItemList.remove(position);
                this.notifyDataSetChanged();
            }
            if ("0".equals(status.getText().toString())) {
                status.setText("Menunggu Atasan");
                this.notifyDataSetChanged();
            }

            if("1".equalsIgnoreCase(status.getText().toString()) || "2".equalsIgnoreCase(status.getText().toString()) || "3".equalsIgnoreCase(status.getText().toString())) {
                movieItemList.remove(position);
                listViewItem.setVisibility(View.INVISIBLE);
                this.notifyDataSetChanged();
            }

            return listViewItem;
        }
    }
}


when it removes item, the app is force closed here is the error message :
java.lang.IndexOutOfBoundsException: Index: 945, Size: 945
       at java.util.ArrayList.remove(ArrayList.java:503)
       at com.example.eis2.approval_nonfull$ListViewAdapterApprovalNonFull.getView(approval_nonfull.java:197)


so.. the main cause is
Java
if("1".equalsIgnoreCase(status.getText().toString()) || "2".equalsIgnoreCase(status.getText().toString()) || "3".equalsIgnoreCase(status.getText().toString())) {
                movieItemList.remove(position); -------> this is the problem
                listViewItem.setVisibility(View.INVISIBLE);
                this.notifyDataSetChanged();
            }


can you guys solve this problem ? i appreciate that....
Posted
Updated 21-Oct-20 23:43pm
Comments
David Crow 22-Oct-20 20:29pm    
You appear to be calling the remove() method twice using the same value of position with each.
Komang Putra 22-Oct-20 23:27pm    
So.. i must call remove method just once ?
David Crow 23-Oct-20 8:22am    
Only you would know the answer to that. Look at the two if() conditions that determine whether an item should be removed or not. They do not appear to be related. Perhaps the second if() could be an else if() instead?

1 solution

Quote:
Index out of bound when remove item

The error message also tell you where is the error. Good idea to tell us too.
Advice: use the debugger, it will allow you to inspect the variables when error occurs.

Your code do not behave the way you expect, or you don't understand why !

There is an almost universal solution: Run your code on debugger step by step, inspect variables.
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't know what your code is supposed to do, it don't find bugs, it just help you to by showing you what is going on. When the code don't do what is expected, you are close to a bug.
To see what your code is doing: Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.

Debugger - Wikipedia, the free encyclopedia[^]

Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]

jdb - The Java Debugger[^]
https://www.jetbrains.com/idea/help/debugging-your-first-java-application.html[^]

The debugger is here to only show you what your code is doing and your task is to compare with what it should do.

[Update]
Quote:
java.lang.IndexOutOfBoundsException: Index: 945, Size: 945

This means that movieItemList have 945 items, and since Java is zero based, positions are from 0 to 944. You try to remove item number 945 which does not exist.
You have find why it happen.
Java
if(!txt_jabatan.getText().toString().equals(lokasi.getText().toString())){
    movieItemList.remove(position); // Is it possible that this remove was done before the error ?
    this.notifyDataSetChanged();
}
if ("0".equals(status.getText().toString())) {
    status.setText("Menunggu Atasan");
    this.notifyDataSetChanged();
}

if("1".equalsIgnoreCase(status.getText().toString()) || "2".equalsIgnoreCase(status.getText().toString()) || "3".equalsIgnoreCase(status.getText().toString())) {
    movieItemList.remove(position); // error is here
    listViewItem.setVisibility(View.INVISIBLE);
    this.notifyDataSetChanged();
}
 
Share this answer
 
v3
Comments
David Crow 22-Oct-20 20:33pm    
How exactly is this a solution instead of just a helpful suggestion? Shouldn't the OP determine whether your suggestion is solution-worthy or not? Just curious...
Patrice T 23-Oct-20 1:36am    
OP added useful information after this solution.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900