[英]java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
[英]java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() in Android
當我按下與JSON連接到MySQL數據庫以從中獲取數據的按鈕時,在logcat中收到此錯誤。 這是錯誤:
05-15 12:09:39.569 4982-5178/? E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.example.ospitznik.enarrations, PID: 4982
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:208)
at android.os.Handler.<init>(Handler.java:122)
at android.app.Activity.<init>(Activity.java:765)
at com.example.ospitznik.enarrations.NarracionesActivity.<init>(NarracionesActivity.java:7)
at com.example.ospitznik.enarrations.VisorActivity.filtrarDatos(VisorActivity.java:180)
at com.example.ospitznik.enarrations.VisorActivity.access$400(VisorActivity.java:30)
at com.example.ospitznik.enarrations.VisorActivity$Mostrar.doInBackground(VisorActivity.java:217)
at com.example.ospitznik.enarrations.VisorActivity$Mostrar.doInBackground(VisorActivity.java:213)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
我的活動是這樣的:
public class VisorActivity extends Activity {
private EditText etNarracion;
private TextView tvUsu;
private ImageView mostrar;
private ImageView mas;
private ImageView menos;
private ImageView ivBotonInicio;
private int posicion=0;
private List<NarracionesActivity> listaNarraciones;
private NarracionesActivity narraciones;
@SuppressLint("InlinedApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_visor);
tvUsu = (TextView) findViewById(R.id.etUsu);
etNarracion = (EditText) findViewById(R.id.etNarracion);
ivBotonInicio = (ImageView) findViewById(R.id.ivBotonInicio);
Bundle extras = getIntent().getExtras();
String usuario = extras.getString("usuario");
tvUsu.setText(usuario);
listaNarraciones=new ArrayList<NarracionesActivity>();
ivBotonInicio.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Bundle extras = getIntent().getExtras();
String usuario = extras.getString("usuario");
Intent i = new Intent(VisorActivity.this, NarracionActivity.class);
i.putExtra("usuario", usuario);
startActivityForResult(i, 0);
finish();
}
});
//Mostramos los datos de la persona por pantalla.
mostrar=(ImageView)findViewById(R.id.ivBotonMostrar);
mostrar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new Mostrar ().execute();
}
});
mas = (ImageView) findViewById(R.id.ivBotonDer);
mas.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(!listaNarraciones.isEmpty()){
if(posicion>=listaNarraciones.size()-1){
posicion=listaNarraciones.size()-1;
mostrarNarracion(posicion);
}else{
posicion++;
mostrarNarracion(posicion);
}
}
}
});
//Se mueve por nuestro ArrayList mostrando el objeto anterior
menos=(ImageView)findViewById(R.id.ivBotonIzq);
menos.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(!listaNarraciones.isEmpty()){
if(posicion<=0){
posicion=0;
mostrarNarracion(posicion);
}
else{
posicion--;
mostrarNarracion(posicion);
}
}
}
});
}
private String mostrar(){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.enarrations.com/selectAllJSON.php");
String resultado="";
HttpResponse response;
try {
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream instream = entity.getContent();
resultado= convertStreamToString(instream);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return resultado;
}
private String convertStreamToString(InputStream is) throws IOException {
if (is != null) {
StringBuilder sb = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "UTF-8"));
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
}
finally {
is.close();
}
return sb.toString();
} else {
return "";
}
}
private boolean filtrarDatos(){
listaNarraciones.clear();
String data=mostrar();
if(!data.equalsIgnoreCase("")){
JSONObject json;
try {
json = new JSONObject(data);
JSONArray jsonArray = json.optJSONArray("narraciones");
for (int i = 0; i < jsonArray.length(); i++) {
narraciones=new NarracionesActivity();
JSONObject jsonArrayChild = jsonArray.getJSONObject(i);
narraciones.setUs_cod(jsonArrayChild.optString("us_cod"));
narraciones.setUs_email(jsonArrayChild.optString("us_email"));
narraciones.setUs_narracion(jsonArrayChild.optString("us_narracion"));
listaNarraciones.add(narraciones);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
return false;
}
private void mostrarNarracion(final int posicion){
runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
NarracionesActivity narraciones = listaNarraciones.get(posicion);
etNarracion.setText(narraciones.getUs_narracion());
}
});
}
class Mostrar extends AsyncTask<String,String,String> {
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
if(filtrarDatos())mostrarNarracion(posicion);
return null;
}
}
}
因為當前使用doInBackground
方法中的AsyncTask
從Web服務獲取數據,所以不需要使用runOnUiThread
來更新TextView中的文本,只需使用onPostExecute
來更新View中的數據:
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(result !=null)
etNarracion.setText(result);
}
並將doInBackground
方法更改為:
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
if(filtrarDatos()){
return listaNarraciones.get(posicion).getUs_narracion();
}else
return null;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.