在数组排序行上单击带有 OnItemClickListener 的任何项目时应用程序崩溃

Posted

技术标签:

【中文标题】在数组排序行上单击带有 OnItemClickListener 的任何项目时应用程序崩溃【英文标题】:App crashes when clicking on any item with OnItemClickListener on array sort line 【发布时间】:2021-02-27 16:00:00 【问题描述】:

应用程序运行良好,直到我单击任何列表项,它崩溃了。使用搜索时它运行良好,但是当我直接在列表项上单击它时,应用程序会停止。Logcat 和调试在第 153 行显示相同的问题。我在行153.第一个代码是 CribActivity 最后一个是视图活动,我不知道它可能与这个错误有关。

 @SuppressLint("UseValueOf")
 public class CribActivity extends Activity 
 
private ListView lv1;
private EditText et;

private String lv_arr[]=
        "item 1",
        "item 2",
        "item 67"
        ;
private ArrayList<String> array_sort= new ArrayList<String>();
int textlength=0;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    
    
    lv1 = (ListView) findViewById(R.id.listView);
    et = (EditText) findViewById(R.id.EditText01);

    lv1 = (ListView)findViewById(R.id.listView);
   
    lv1.setAdapter(
            new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , lv_arr));
    lv1.setTextFilterEnabled(true);
    
    
    et.addTextChangedListener(new TextWatcher()
    
    public void afterTextChanged(Editable s)
    
                                                                    
    
    public void beforeTextChanged(CharSequence s,
    int start, int count, int after)
    
  
    
    public void onTextChanged(CharSequence s,
    int start, int before, int count)
    
    textlength = et.getText().length();
    array_sort.clear();
    for (int i = 0; i < lv_arr.length; i++)
    
    if (textlength <= lv_arr[i].length())
    
    if(et.getText().toString().equalsIgnoreCase(
    (String)
    lv_arr[i].subSequence(0,
    textlength)))
    
   array_sort.add(lv_arr[i]);
                                 
                                   
                                  
    lv1.setAdapter(new ArrayAdapter<String>
    (CribActivity.this,
    android.R.layout.simple_list_item_1, array_sort));
    
    );
    
    
    lv1.setOnItemClickListener(new OnItemClickListener() 
        public void onItemClick(AdapterView<?> a, View v, int position,
                long id) 
            String name = array_sort.get(position); //***THIS IS THE LINE 153***
            for (int i = 0; i < lv_arr.length; i++) 
                
                    if (name
                            .equalsIgnoreCase(
                                    (String) lv_arr[i])) 
                        position = i; 
                        
                        break;
                    
                
            
            
        
            String itemname = new Integer(position).toString();

            Intent intent = new Intent();

            intent.setClass(CribActivity.this, ViewActivity.class);

            Bundle b = new Bundle();

            
            b.putString("defStrID", itemname);

            intent.putExtras(b);

            nt
            startActivity(intent);
        
    );


调试:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: ru.tablica.sputnikovyh, PID: 24169
java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
    at java.util.ArrayList.get(ArrayList.java:437)
    at ru.tablica.sputnikovyh.CribActivity$2.onItemClick(CribActivity.java:153)
    at android.widget.AdapterView.performItemClick(AdapterView.java:318)
    at android.widget.AbsListView.performItemClick(AbsListView.java:1159)
    at android.widget.AbsListView$PerformClick.run(AbsListView.java:3136)
    at android.widget.AbsListView.onTouchUp(AbsListView.java:4064)
    at android.widget.AbsListView.onTouchEvent(AbsListView.java:3822)
    at android.view.View.dispatchTouchEvent(View.java:12513)
    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3024)
    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2705)
    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3030)
    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2719)
    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3030)
    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2719)
    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3030)
    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2719)
    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3030)
    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2719)
    at com.android.internal.policy.DecorView.superDispatchTouchEvent(DecorView.java:440)
    at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1830)
    at android.app.Activity.dispatchTouchEvent(Activity.java:3400)
    at com.android.internal.policy.DecorView.dispatchTouchEvent(DecorView.java:398)
    at android.view.View.dispatchPointerEvent(View.java:12752)
    at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:5106)
    at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4909)
    at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4426)
    at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4479)
    at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4445)
    at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4585)
    at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4453)
    at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4642)
    at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4426)
    at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4479)
    at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4445)
    at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4453)
    at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4426)
    at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:7092)
    at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:7061)
    at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:7022)
    at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:7195)
    at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:186)
    at android.os.MessageQueue.nativePollOnce(Native Method)
    at android.os.MessageQueue.next(MessageQueue.java:326)
    at android.os.Looper.loop(Looper.java:160)
    at android.app.ActivityThread.main(ActivityThread.java:6669)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

logcat:

    E/eglCodecCommon: GoldfishAddressSpaceHostMemoryAllocator: ioctl_ping failed for device_type=5, 
    ret=-1
    E/AndroidRuntime: FATAL EXCEPTION: main
    java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.ArrayList.get(ArrayList.java:437)
    at ru.tablica.sputnikovyh.CribActivity$2.onItemClick(CribActivity.java:156)
    at android.widget.AdapterView.performItemClick(AdapterView.java:318)
    at android.widget.AbsListView.performItemClick(AbsListView.java:1159)
    at android.widget.AbsListView$PerformClick.run(AbsListView.java:3136)
    at android.widget.AbsListView$3.run(AbsListView.java:4052)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6669)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

查看活动

     public class ViewActivity extends Activity 

     @Override
     public void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_NO_TITLE);

    setContentView(R.layout.view);




    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

    Bundle bundle = getIntent().getExtras();

    String itemname = "n" + bundle.getString("defStrID");

    Context context = getBaseContext();


    String text = readRawTextFile(context, getResources().getIdentifier(itemname, "raw", "ru.tablica.sputnikovyh"));

    WebView myWebView = (WebView) findViewById(R.id.webView);
    String summary = "<!Doctype html><html><head><meta charset=utf-8></head><body>" + text + "</body></html>";
    myWebView.loadData(summary, "text/html; charset=utf-8", "utf-8");


public static String readRawTextFile(Context ctx, int resId)

    InputStream inputStream = ctx.getResources().openRawResource(resId);

    InputStreamReader inputreader = new InputStreamReader(inputStream);
    BufferedReader buffreader = new BufferedReader(inputreader);
    String line;
    StringBuilder text = new StringBuilder();

    try 
        while (( line = buffreader.readLine()) != null) 
            text.append(line);
            text.append('\n');
        
     catch (IOException e) 
        return null;
    
    return text.toString();


【问题讨论】:

这个错误告诉你在array_sort这个位置没有项目,尝试打印你的array_sort 字符串名称 = array_sort.get(position); System.out.println(array_sort);像这样? 在字符串名称之前,使用 Log.d("my array: ", "+"+array_stort) 没有任何变化(与调试完全相同的 logcat 【参考方案1】:

您正在访问onItemClick 内的array_sort,在您执行任何搜索之前,它在开始时为空。这就是为什么你有OutOfBoundException

当不处于“搜索模式”时,您的侦听器应访问lv_arr 数组或使用方便的方法adapter.getItem(position) - 您需要保持对适配器实例的引用或使用listView.getAdapter().getItem(position)。我看到您在搜索模式下正在更换适配器,因此您也可以更换 OnItemClickListener(但最好在开始时设置一个侦听器,其中一些逻辑处理这两种情况 - 常用列表并通过搜索过滤)

【讨论】:

我尝试在onItemClick之前添加这两行代码,但现在它根本不可点击,if (array_sort.size() 您的代码非常混乱,在一行中您正在检查array_sort,接下来您正在访问lv_arr - 这些不一样。清理您的代码,再次阅读我的答案,您将得到修复。添加一些 ifs 而不了解检查的内容和时间不是解决方案 这就是您的代码无法正常工作的原因 - array_sort 为空(执行任何排序时),您在 onItemClick (array_sort.get(position) 的第一行访问它。但下一行正在处理lv_arr - 你显然不知道你应该在哪个数组上工作并执行单击的项目接收 感谢您的帮助,但似乎我不像您那么好,所以如果您能提供更准确的建议,我将不胜感激。我应该在哪里添加什么样的代码? String name = array_sort.get(position); 替换为 String name = lv_arr.get(position); 这将使您的代码在不执行搜索时工作,而不是在 EditText 中输入单个字符。我建议您从代码中完全删除array_sort(以及所有相关行)并重新编写过滤功能。有很多教程,而您当前的代码只是一团糟……您应该了解有关此功能(搜索/过滤)的更多信息以及数组如何工作的一些基础知识,我不会为您提供复制/粘贴的确切代码,因为您不会学到任何东西,这不是 SP 的目的

以上是关于在数组排序行上单击带有 OnItemClickListener 的任何项目时应用程序崩溃的主要内容,如果未能解决你的问题,请参考以下文章

模拟网格行上的单击事件

jQuery单击gridview行上的选择按钮

数组在所有行上只听一次

Android:从自定义列表视图中单击的按钮获取列表视图项目

在缓冲模式下打开行编辑器时检测网格上的单击

JTree 通过单击行上的任意位置选择节点