致命异常:AsyncTask#1执行doInBackground时发生错误

时间:2015-06-10 08:48:37

标签: php android android-asynctask

请帮帮我, 我想制作条形码扫描仪并将结果发送到我的数据库中,但我有错误 这是我的代码:

MainActivity.java

    package common.TER2015;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import youb.y.com.android.zxinglib.integrator.IntentIntegrator;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;
import dossier.android.ter.R;

public class MainActivity extends Activity {
    private Handler  handler = new Handler();
    private TextView txtScanResult;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        txtScanResult = (TextView) findViewById(R.id.scan_result);
        View btnScan = findViewById(R.id.scan_button);

        // le boutton Scanner
        btnScan.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // dernièer paramètre se met à true pr la lumiére
                IntentIntegrator.initiateScan(MainActivity.this, R.layout.capture,
                        R.id.viewfinder_view, R.id.preview_view, true);
                Insert task = new Insert();
                task.execute(new String[]{"http://10.0.2.2:80/codebarre/insert.php"});  
            }

        });
    }
    private class Insert extends AsyncTask<String, Void, Boolean>{
        ProgressDialog dialog = new ProgressDialog(MainActivity.this);
        @Override
        protected void onPreExecute() {
        dialog.setMessage("Envoi en cours..");
        dialog.show();

        }

        @Override
        protected Boolean doInBackground(String... urls) {


            for(String url : urls){
            try {
                ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
                pairs.add(new BasicNameValuePair("codebarre", txtScanResult.getText().toString()));
                HttpClient client = new DefaultHttpClient();
                HttpPost post = new HttpPost(url);
                post.setEntity(new UrlEncodedFormEntity(pairs));
                client.execute(post);

            } catch (ClientProtocolException e) {
    Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_SHORT).show();
   return false;
            } 
            catch (IOException e) {
    Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_SHORT).show();
   return false;
            }
            }

            return true;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            if(result == true ){
Toast.makeText(MainActivity.this, "Succée", Toast.LENGTH_SHORT).show(); } else{
Toast.makeText(MainActivity.this, "Echéq", Toast.LENGTH_SHORT).show();
            }
            dialog.dismiss();
            }
        }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case IntentIntegrator.REQUEST_CODE:
                jim.h.common.android.zxinglib.integrator.IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
                if (scanResult == null) {
                    return;
                }
                final String result = scanResult.getContents();
                if (result != null) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                          //  txtScanResult.setText(result);

                        }
                        }
                    );
                }
                break;
            default:
        }}}

main.xml中

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@android:color/white"
    android:gravity="center"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="80dp"
        android:text="@string/scan_resut_lable"
        android:textColor="#000" />

    <TextView
        android:id="@+id/scan_result"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/scan_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal|top"
        android:text="@string/scan" />

    <ImageView
        android:id="@drawable/upecnoir"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="200dp"
        android:src="@drawable/upecnoir" />

</LinearLayout>

Capture.xml

<?xml version="1.0" encoding="UTF-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent">

    <SurfaceView android:id="@+id/preview_view"
        android:layout_width="fill_parent" android:layout_height="fill_parent"
        android:layout_centerInParent="true" />

     <jim.h.common.android.zxinglib.view.ViewfinderView
        android:id="@+id/viewfinder_view" android:layout_width="fill_parent"
        android:layout_height="fill_parent" android:background="#00000000" />

    <TextView android:id="@+id/status_view" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_gravity="bottom|center_horizontal"
        android:background="#00000000" android:text="@string/msg_default_status"
        android:textColor="#ffffffff" android:textSize="14sp" />

</FrameLayout>

insert.php

<?php
//if (isset($_POST['codebr'])){
include_once("connection.php");
$codebarre = $_POST['codebarre'];
mysql_query("insert into code(codeb) values('$codebarre')");
?>
<html>
<body>
<form action="insert.php" method="post">
codebarre <input type="text" name="codebarre" /> <br/>
<input type="submit" value ="Insert" />
</form>
</body>
</html>

LogCat

06-10 04:25:26.550: W/dalvikvm(1658): threadid=12: thread exiting with uncaught exception (group=0xb1a55ba8)
06-10 04:25:26.570: E/AndroidRuntime(1658): FATAL EXCEPTION: AsyncTask #1
06-10 04:25:26.570: E/AndroidRuntime(1658): Process: dossier.android.ter, PID: 1658
06-10 04:25:26.570: E/AndroidRuntime(1658): java.lang.RuntimeException: An error occured while executing doInBackground()
06-10 04:25:26.570: E/AndroidRuntime(1658):     at android.os.AsyncTask$3.done(AsyncTask.java:300)
06-10 04:25:26.570: E/AndroidRuntime(1658):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
06-10 04:25:26.570: E/AndroidRuntime(1658):     at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
06-10 04:25:26.570: E/AndroidRuntime(1658):     at java.util.concurrent.FutureTask.run(FutureTask.java:242)
06-10 04:25:26.570: E/AndroidRuntime(1658):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
06-10 04:25:26.570: E/AndroidRuntime(1658):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
06-10 04:25:26.570: E/AndroidRuntime(1658):     at java.lang.Thread.run(Thread.java:841)
06-10 04:25:26.570: E/AndroidRuntime(1658): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
06-10 04:25:26.570: E/AndroidRuntime(1658):     at android.os.Handler.<init>(Handler.java:200)
06-10 04:25:26.570: E/AndroidRuntime(1658):     at android.os.Handler.<init>(Handler.java:114)
06-10 04:25:26.570: E/AndroidRuntime(1658):     at android.widget.Toast$TN.<init>(Toast.java:327)
06-10 04:25:26.570: E/AndroidRuntime(1658):     at android.widget.Toast.<init>(Toast.java:92)
06-10 04:25:26.570: E/AndroidRuntime(1658):     at android.widget.Toast.makeText(Toast.java:241)
06-10 04:25:26.570: E/AndroidRuntime(1658):     at common.TER2015.MainActivity$Insert.doInBackground(MainActivity.java:82)
06-10 04:25:26.570: E/AndroidRuntime(1658):     at common.TER2015.MainActivity$Insert.doInBackground(MainActivity.java:1)
06-10 04:25:26.570: E/AndroidRuntime(1658):     at android.os.AsyncTask$2.call(AsyncTask.java:288)
06-10 04:25:26.570: E/AndroidRuntime(1658):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
06-10 04:25:26.570: E/AndroidRuntime(1658):     ... 3 more
06-10 04:25:32.350: I/Choreographer(1658): Skipped 234 frames!  The application may be doing too much work on its main thread.
06-10 04:30:26.730: I/Process(1658): Sending signal. PID: 1658 SIG: 9

请帮我解决这个问题。

1 个答案:

答案 0 :(得分:0)

您正在尝试从AsyncTask中的doInBackground()方法更新try-catch块中的UI(显示Toast消息)。你不能这样做。如果要显示来自doInBackground()的Toast消息,可以使用runOnUiThread方法。例如:

catch (ClientProtocolException e) {
    runOnUiThread(new Runnable() {

        public void run() {

           Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_SHORT).show();
           return false;

       }
    });

}