当我单击“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;
}