“android.view.ViewRootImpl $ CalledFromWrongThreadException:只有创建视图层次结构的原始线程才能触及其视图。”

时间:2013-11-08 23:40:26

标签: android spinner

当我点击“Buscar”(来自葡萄牙语:搜索)按钮时,我正试图用mysql数据库中的数据填充执行时间的微调器,但是当我点击这个按钮时,我得到以下异常:“android。 view.ViewRootImpl $ CalledFromWrongThreadException:只有创建视图层次结构的原始线程才能触及其视图。“

我的代码

btnBuscarProduto.setOnClickListener(new View.OnClickListener() {  
        public void onClick(View v) {
            new Thread(new Runnable() {
                public void run() {
                    Looper.prepare();
                    /*This is a string*/resultadoBusca = buscar(edtBuscaProduto.getText().toString());
                    System.out.println("Resultado da Busca: "+resultadoBusca);
                    if(resultadoBusca.equalsIgnoreCase("Vazio")){
                        Toast toast = Toast.makeText(getActivity(), "Nada Encontrado", Toast.LENGTH_SHORT);
                        toast.show(); 
                    }else{
                        /*This is a List<String>*/listaBusca = makeList(resultadoBusca);
                        System.out.println("Lista da Busca"+listaBusca);
                        ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, list);
                        spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
                        spnProdutos.setAdapter(spinnerArrayAdapter);

                    }                                             
                }
              }).start();                 
        }
    });

public String buscar(String termo){
String resp = null;
try{
        httpclient = new DefaultHttpClient();
        httppost = new HttpPost("http://192.168.1.101/android/busca.php");
        nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("busca", termo)); 
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));            
        response=httpclient.execute(httppost);           
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        resp = httpclient.execute(httppost, responseHandler);
    }catch(Exception e){
        Toast toast = Toast.makeText(getActivity(), "Erro: "+e.getMessage(), Toast.LENGTH_SHORT);
        toast.show(); 
    }
return resp;
}

public List<String> makeList(String input){ 
    List<String> list = new ArrayList<String>();
    String[] newArray = input.split("\\|");
    for (int i =0; i<newArray.length; i++){
        list.add(newArray[i].toString());
    }   
    return list;
}  

4 个答案:

答案 0 :(得分:1)

您收到此异常是因为您尝试更新后台UI上的Thread

 Toast toast = Toast.makeText(getActivity(), "Nada Encontrado", Toast.LENGTH_SHORT);
                    toast.show();

有几种方法可以解决这个问题,我最喜欢的一种方法是使用AsyncTask

您可以执行AsyncTask doInBackground()来执行onPostExecute()中的网络内容,然后您可以将结果返回到UI,您可以根据结果更新{{1}}

Here is an example of using AsyncTask

答案 1 :(得分:0)

我认为你不能从UI线程以外的其他线程更改UI。看看runOnUiThread。获得搜索结果后,您应该输入UI线程,然后可以修改UI。

答案 2 :(得分:0)

为了简单起见,我会这样做:

btnBuscarProduto.setOnClickListener(new View.OnClickListener() {  
    public void onClick(View v) {
        new Thread(new Runnable() {
            public void run() {
                Looper.prepare();
                /*This is a string*/resultadoBusca = buscar(edtBuscaProduto.getText().toString());
                System.out.println("Resultado da Busca: "+resultadoBusca);
               MyActivity.this.runOnUiThread(new Runnable(){

                    @Override
                    public void run() {
                        if(resultadoBusca.equalsIgnoreCase("Vazio")){
                            Toast toast = Toast.makeText(getActivity(), "Nada Encontrado", Toast.LENGTH_SHORT);
                            toast.show(); 
                         }else{
                           /*This is a List<String>*/listaBusca = makeList(resultadoBusca);
                           System.out.println("Lista da Busca"+listaBusca);
                           ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, list);
                           spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
                           spnProdutos.setAdapter(spinnerArrayAdapter);

                        }               
                    }});

            }
          }).start();                 
    }
});

答案 3 :(得分:0)

不允许非ui线程触摸视图。通过Context提供的runOnUIThread方法在UI线程上执行视图操作。