【问题标题】:java.lang.RuntimeException: An error occured while executing doInBackground()java.lang.RuntimeException:执行 doInBackground() 时发生错误
【发布时间】:2023-05-05 02:01:01
【问题描述】:

有时我会在我的应用程序中收到此崩溃错误

java.lang.RuntimeException: An error occured while executing doInBackground()

这是完整的 logCat:

java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:200)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
at java.lang.Thread.run(Thread.java:1019)
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:121)
at android.widget.Toast.<init>(Toast.java:68)
at android.widget.Toast.makeText(Toast.java:231)
at kostas.menu.olympiakos.nea.loadFeed(nea.java:84)
at kostas.menu.olympiakos.nea.access$1(nea.java:75)
at kostas.menu.olympiakos.nea$BackgroundAsyncTask_nea.doInBackground(nea.java:242)
at kostas.menu.olympiakos.nea$BackgroundAsyncTask_nea.doInBackground(nea.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:185)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
... 4 more

这是我的 .nea 类代码:

package kostas.menu.olympiakos;


import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.LayoutAnimationController;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;


public class nea extends ListActivity{
    private List<Message> messages; 




    List<String> des = new ArrayList<String>();//to prosthesa gia na anoigei to keimeno sto alert
    List<String> text = new ArrayList<String>();//to prosthesa gia na anoigei o titlos sto alert
    List<URL> url = new ArrayList<URL>();//to prosthesa gia to koumpi pou pigainei sto link

    List<String> imgl = new ArrayList<String>();//to prosthesa gia na anoigei to keimeno sto alert

    @Override 
    public void onCreate(Bundle icicle) {   
        super.onCreate(icicle);
        setContentView(R.layout.main2);

        if(isInternetOn()) {
            new BackgroundAsyncTask_nea().execute();
            }else{
             Toast.makeText(nea.this,R.string.no_connection, Toast.LENGTH_SHORT).show();
             finish();
            }



    }


    private void loadFeed(AsyncTask<Void, Void, Void> asyncTask){
        try{ 
            BaseFeedParser parser = new BaseFeedParser();
            messages = parser.parse();

            }
         catch (Throwable t){
              Log.e("OSFP.News",t.getMessage(),t);

                Toast.makeText(nea.this, "Χρειάζεστε σύνδεση στο internet",
                        Toast.LENGTH_SHORT).show();
                finish();

            }
    }


    private void displayRss(){

        ArrayList<HashMap<String, String>> List_nea = new ArrayList<HashMap<String, String>>(messages.size());


        for (Message msg : messages){

            des.add(msg.getDescription());// keimeno
            text.add(msg.getTitle());// titlos
            url.add(msg.getLink());// link
            imgl.add(msg.getImgLink());

        HashMap<String, String> map = new HashMap<String, String>();
        map.put("name", msg.getTitle());
        map.put("date", msg.getDate());     


        List_nea.add(map);
        ListAdapter mSchedule = new SimpleAdapter(this, List_nea, R.layout.row,
                new String[] {"name", "date"}, new int[] {R.id.TextView01, R.id.TextView02});
        this.setListAdapter(mSchedule);
        }

    AnimationSet set = new AnimationSet(true);

    Animation animation = new AlphaAnimation(0.0f, 1.0f);
    animation.setDuration(400);
    set.addAnimation(animation);

    animation = new TranslateAnimation(
        Animation.RELATIVE_TO_SELF, 0.0f,Animation.RELATIVE_TO_SELF, 0.0f,
        Animation.RELATIVE_TO_SELF, -1.0f,Animation.RELATIVE_TO_SELF, 0.0f
    );

    animation.setDuration(400);
    set.addAnimation(animation);
    LayoutAnimationController controller = new LayoutAnimationController(set, 0.5f);
    ListView listViewn = getListView();        
    listViewn.setLayoutAnimation(controller);

    }



    protected void onListItemClick(ListView l, View v, final int position, long id) {



        super.onListItemClick(l, v, position, id);
        Dialog dialog = new Dialog(this);
       String description = des.get(position).toString().replaceAll("\\<.*?>","");
       String imagee=imgl.get(position).toString();
        final URL link = url.get(position);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); 
            dialog.setContentView(R.layout.single);
            dialog.setCancelable(true);
            Toast msg = Toast.makeText(nea.this, "The url is  :  "+imagee, Toast.LENGTH_LONG);
            msg.show();
//xrisimopoiisa toast gia na elegxw poio link pernw apo to site



            TextView title_dialog = (TextView) dialog.findViewById(R.id.title_dialog);
            title_dialog.setText(text.get(position));


            TextView text = (TextView) dialog.findViewById(R.id.descr);
            text.setText(description);


            ImageView image1 = (ImageView) dialog.findViewById(R.id.image1);


            try {
                //where imageUrl is what you pulled out from the rss feed
                Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imagee).getContent());
                image1.setImageBitmap(bitmap); 
              } catch (MalformedURLException e) {
               //log exception here
              } catch (IOException e) {
                //log exception here
              }      
            Button btnt = (Button) dialog.findViewById(R.id.btnrss);//ti kanei to koumpi otan to patas gia to link
            btnt.setOnClickListener(new View.OnClickListener() {
                public void onClick (View view) {

                    Intent viewMessage = new Intent(Intent.ACTION_VIEW, Uri.parse(link.toExternalForm()));
                    startActivityForResult(viewMessage, 0);

                }  

            });           

            dialog.show();
    }

        //options menu
    @Override
    public boolean onCreateOptionsMenu(Menu menu2) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu2, menu2);
        return true;
    }  

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.refresh:
            new BackgroundAsyncTask_nea().execute();
            break;


        }
        return true;
    }

    public class BackgroundAsyncTask_nea extends
       AsyncTask<Void, Void, Void> {
          private ProgressDialog dialog;
        int myProgress;   

        @Override
        protected void onPostExecute(Void result) {

            displayRss();
             dialog.dismiss();

        }

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
              dialog = ProgressDialog.show(nea.this, "", "Loading. Please wait...", true);
            myProgress = 0;
        }

        protected void onProgressUpdate(Integer... progress) {
          // TODO Auto-generated method stub
          //super.onProgressUpdate(values);

            dialog.setProgress(progress[0]);
         }

        @Override
        protected Void doInBackground(Void... arg0) {
            // TODO Auto-generated method stub

            loadFeed(this);
            return null;
        }



    }


    public final boolean isInternetOn() {
        ConnectivityManager connec =  (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        // ARE WE CONNECTED TO THE NET
        if ( connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED ||
        connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTING ||
        connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING ||
        connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED ) {
        // MESSAGE TO SCREEN FOR TESTING (IF REQ)
        //Toast.makeText(this, connectionType + ” connected”, Toast.LENGTH_SHORT).show();
        return true;
        } else if ( connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED ||  connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED  ) {
        //System.out.println(“Not Connected”);
        return false;
        }
        return false;
        }
}

为什么会出现这个错误?我该如何解决?谢谢 :)

编辑:

Public void toast_doInBck(View view) {
        // Do something long
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i <= 10; i++) {
                    Toast.makeText(nea.this,R.string.no_connection, Toast.LENGTH_SHORT).show();
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                        }
                    });
                }
            }
        };
        new Thread(runnable).start();
    }

EDIT2:

    private void loadFeed(AsyncTask<Void, Void, Void> asyncTask){
        try{ 
            BaseFeedParser parser = new BaseFeedParser();
            messages = parser.parse();

            }
         catch (Throwable t){
              Log.e("OSFP.News",t.getMessage(),t);
Looper.prepare();
                Toast.makeText(nea.this, "Παρακαλώ προσπαθήστε αργότερα..",
                        Toast.LENGTH_SHORT).show();
                finish();
                Looper.loop();

            }
    }

【问题讨论】:

  • 您阅读了邮件吗? Can't create handler inside thread that has not called Looper.prepare()
  • 是的,我读过,但我不知道如何解决!只需在我的 toast 之前调用 Looper.prepare,然后在它之后调用 Looper.Loop?

标签: android


【解决方案1】:

您不能在后台线程上执行任何 GUI 工作。相反,您应该post a Runnable to a handler created in the GUI thread 让您的 Toast 在正确的线程上执行。

编辑:由于作业标签被删除,我将给出一个大纲;

  • new() 在您的 GUI 线程中创建一个处理程序(onCreate 是一个好地方)并将其保存在一个成员变量中,例如“处理程序”。
  • 将显示 Toast 的内容移至 Runnable(匿名类对此非常有用)
  • 要显示吐司,请使用 Runnable 作为参数执行 handler.post()。 Runnable 将在 GUI 线程中执行。

有关完整示例,请参阅this article

【讨论】:

  • 对不起,我需要更多帮助。我可以在答案上创建类似我的编辑的内容吗?
  • 拜托,我已经用我找到的可行解决方案更新了我的答案(EDIT2)。你能告诉我这种方法是否正确吗?
  • 您仍然无法从后台线程运行 loadFeed,您需要在 catch 块中放置一个 handler.post(),并给它一个 Runnable,在其 run() 方法中调用您的 Toast 方法。
【解决方案2】:

我认为在这段代码中 Toast 给你带来麻烦,

catch (Throwable t){
              Log.e("OSFP.News",t.getMessage(),t);

                Toast.makeText(nea.this, "Χρειάζεστε σύνδεση στο internet",
                        Toast.LENGTH_SHORT).show();
                finish();

            }

因为您正试图从AsyncTask 的工作线程中执行UI operation,所以这永远不会允许..

更新:如果您想从AsyncTaskdoInBackGround() 更新某些内容,请使用publishProgress(Progress...)onProgressUpdate(Progress...)

【讨论】:

    【解决方案3】:

    这可能是因为您试图在 doInBackground() 上显示某些内容。 doInBackground 在无法执行任何 UI 工作的工作线程中运行(包括显示 Toast,这就是您正在执行的操作)。相反,所有 UI 工作都应该在 onPostExecute() 上完成。

    【讨论】:

    • 感谢您的回答!用户界面在 onPostExecute 上完成!如果我的连接出现问题,我只是在 doInBackground 中敬酒。这不可能吗?
    【解决方案4】:

    您在loadFeed 中显示Toast,它在AsyncTaskdoInBackground 部分中调用。您不应该从那里访问 UI。

    【讨论】:

    • 如果 loadFeed() 的 try{} 不起作用,有什么办法可以祝酒?
    最近更新 更多