我的应用程序在ListView事件或线程中崩溃

时间:2014-06-20 04:20:48

标签: android multithreading listview

lst.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, final View view,int position, long id) {
    //btnsub is button
    btnsub.setEnabled(true); 
    Toast.makeText(getApplicationContext(), "before start()", Toast.LENGTH_SHORT).show();
    for(int i=0;i<j;i++){
        //lst is ListView Object
        View vtmp = lst.getChildAt(i);
        if(vtmp !=null){
        if(i==lst.getCheckedItemPosition()){
            //cindex is int var
            cindex=lst.getCheckedItemPosition();
            }else{  }
        }
    }

    new Thread() {
        public void run() {
            Toast.makeText(getApplicationContext(), "in Thread ", Toast.LENGTH_LONG).show();
            try{
                    Thread.sleep(1000);
                    lst.getChildAt(cindex).setBackgroundColor(Color.BLUE);
            }catch(Exception e){
              Toast.makeText(getApplicationContext(), "Thread Generate: "+e.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
    }.start();


    Toast.makeText(getApplicationContext(), "after start()", Toast.LENGTH_SHORT).show();
    }
 });

2 个答案:

答案 0 :(得分:0)

您无法在工作线程中更新UI。修改你的代码:

new Thread() {
        public void run() {

            try{
                    Thread.sleep(1000);
                    mActivity.runOnUiThread(new Runnable() {
             public void run() {
                Toast.makeText(getApplicationContext(), "in Thread ", Toast.LENGTH_LONG).show();
                lst.getChildAt(cindex).setBackgroundColor(Color.BLUE);
             }
            });
            }catch(Exception e){

                }
            }
    }.start();

更好的方法是使用Handler,您可以阅读 - Communicating with the UI Thread

答案 1 :(得分:0)

用以下代码替换线程部分:

runOnUiThread(new Runnable() {
                   @Override
                        public void run() {
                                   Toast.makeText(getApplicationContext(), "in Thread ", Toast.LENGTH_LONG).show();
            try{
                    Thread.sleep(1000);
                    lst.getChildAt(cindex).setBackgroundColor(Color.BLUE);
            }catch(Exception e){
              Toast.makeText(getApplicationContext(), "Thread Generate: "+e.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
                        }
                    });