java.lang.RuntimeException的:执行doInBackground时出错() [英] java.lang.RuntimeException: An error occured while executing doInBackground()

查看:6881
本文介绍了java.lang.RuntimeException的:执行doInBackground时出错()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时候,我在我的应用程序得到这个崩溃的错误

  java.lang.RuntimeException的:执行doInBackground时出错()
 

这是完整的logcat:

  java.lang.RuntimeException的:执行doInBackground时出错()
在android.os.AsyncTask $ 3.done(AsyncTask.java:200)
在java.util.concurrent.FutureTask中$ Sync.innerSetException(FutureTask.java:274)
在java.util.concurrent.FutureTask.setException(FutureTask.java:125)
在java.util.concurrent.FutureTask中$ Sync.innerRun(FutureTask.java:308)
在java.util.concurrent.FutureTask.run(FutureTask.java:138)
在java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
在java.util.concurrent.ThreadPoolExecutor中的$ Worker.run(ThreadPoolExecutor.java:581)
在java.lang.Thread.run(Thread.java:1019)
java.lang.RuntimeException的:所致。内螺纹已经不叫尺蠖prepare无法创建处理器()
在android.os.Handler< INIT>(Handler.java:121)
在android.widget.Toast< INIT>(Toast.java:68)
在android.widget.Toast.makeText(Toast.java:231)
在kostas.menu.olympiakos.nea.loadFeed(nea.java:84)
在kostas.menu.olympiakos.nea.access $ 1(nea.java:75)
在kostas.menu.olympiakos.nea $ BackgroundAsyncTask_nea.doInBackground(nea.java:242)
在kostas.menu.olympiakos.nea $ BackgroundAsyncTask_nea.doInBackground(nea.java:1)
在android.os.AsyncTask $ 2.call(AsyncTask.java:185)
在java.util.concurrent.FutureTask中$ Sync.innerRun(FutureTask.java:306)
... 4个
 

这是我.nea类code:

 包kostas.menu.olympiakos;


进口java.io.IOException异常;
进口的java.io.InputStream;
进口java.net.MalformedURLException;
进口的java.net.URL;
进口的java.util.ArrayList;
进口的java.util.HashMap;
进口的java.util.List;

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


公共类NEA扩展ListActivity {
    私人列表<消息>消息;




    名单<字符串> DES =新的ArrayList<字符串>(); //以prosthesa GIA呐anoigei到keimeno STO警报
    名单<字符串>文=新的ArrayList<字符串>(); //以prosthesa GIA呐anoigeiØtitlos STO警报
    名单<网址> URL =新的ArrayList<网址>(); //以prosthesa GIA到koumpi POU pigainei STO链接

    名单<字符串> IMGL =新的ArrayList<字符串>(); //以prosthesa GIA呐anoigei到keimeno STO警报

    @覆盖
    公共无效的onCreate(包冰柱){
        super.onCreate(冰柱);
        的setContentView(R.layout.main2);

        如果(isInternetOn()){
            新BackgroundAsyncTask_nea()执行();
            }其他{
             Toast.makeText(nea.this,R.string.no_connection,Toast.LENGTH_SHORT).show();
             完();
            }



    }


    私人无效loadFeed(AsyncTask的<虚空,虚空,虚空>的AsyncTask){
        尝试{
            BaseFeedParser分析器=新BaseFeedParser();
            消息= parser.parse();

            }
         捕获(的Throwable T){
              Log.e(OSFP.News,t.getMessage(),叔);

                Toast.makeText(nea.this,Χρειάζεστεσύνδεσηστο互联网,
                        Toast.LENGTH_SHORT).show();
                完();

            }
    }


    私人无效displayRss(){

        ArrayList的< HashMap的<字符串,字符串>> List_nea =新的ArrayList< HashMap的<字符串,字符串>>(messages.size());


        对于(消息消息:消息){

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

        HashMap的<字符串,字符串>图=新的HashMap<字符串,字符串>();
        map.put(姓名,msg.getTitle());
        map.put(日期,msg.getDate());


        List_nea.add(图)
        ListAdapter mSchedule =新SimpleAdapter(这一点,List_nea,R.layout.row,
                新的String [] {姓名,日期},新的INT [] {R.id.TextView01,R.id.TextView02});
        this.setListAdapter(mSchedule);
        }

    AnimationSet组=新AnimationSet(真正的);

    动画动画=新AlphaAnimation(0.0,1.0F);
    animation.setDuration(400);
    set.addAnimation(动画);

    动画=新TranslateAnimation(
        Animation.RELATIVE_TO_SELF,0.0,Animation.RELATIVE_TO_SELF,0.0,
        Animation.RELATIVE_TO_SELF,-1.0F,Animation.RELATIVE_TO_SELF,0.0
    );

    animation.setDuration(400);
    set.addAnimation(动画);
    LayoutAnimationController控制器=新LayoutAnimationController(套,0.5F);
    ListView控件listViewn = getListView();
    listViewn.setLayoutAnimation(控制器);

    }



    保护无效onListItemClick(ListView的L,视图V,最终诠释的位置,长的id){



        super.onListItemClick(L,V,位置ID);
        对话对话框=新的对话框(本);
       字符串描述= des.get(位置)的ToString()的replaceAll(\\< *>?,);
       字符串imagee = imgl.get(位置)的ToString();
        最终的URL链接= url.get(位置);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setContentView(R.layout.single);
            dialog.setCancelable(真正的);
            吐司味精= Toast.makeText(nea.this,网址是:+ imagee,Toast.LENGTH_LONG);
            msg.show();
// xrisimopoiisa敬酒嘉娜elegxw Poio的链接pernw APO现场



            TextView的title_dialog =(TextView中)dialog.findViewById(R.id.title_dialog);
            title_dialog.setText(text.get(位置));


            TextView的文字=(TextView的)dialog.findViewById(R.id.descr);
            text.setText(介绍);


            ImageView的此搜索=(ImageView的)dialog.findViewById(R.id.image1);


            尝试 {
                //,其中imageURL你从RSS源拉出
                点阵位图= BitmapFactory.de codeStream((InputStream的)新的URL(imagee).getContent());
                image1.setImageBitmap(位);
              }赶上(MalformedURLException异常E){
               //日志这里异常
              }赶上(IOException异常E){
                //日志这里异常
              }
            按钮btnt =(按钮)dialog.findViewById(R.id.btnrss); // TI宽永来koumpi领导的祖国,以PATAS GIA链接
            btnt.setOnClickListener(新View.OnClickListener(){
                公共无效的onClick(视图查看){

                    意图viewMessage =新的意图(Intent.ACTION_VIEW,Uri.parse(link.toExternalForm()));
                    startActivityForResult(viewMessage,0);

                }

            });

            dialog.show();
    }

        //选项菜单
    @覆盖
    公共布尔onCreateOptionsMenu(菜单MENU2){
        MenuInflater充气= getMenuInflater();
        inflater.inflate(R.menu.menu2,MENU2);
        返回true;
    }

    @覆盖
    公共布尔onOptionsItemSelected(菜单项项){
        开关(item.getItemId()){
        案例R.id.refresh:
            新BackgroundAsyncTask_nea()执行();
            打破;


        }
        返回true;
    }

    公共类BackgroundAsyncTask_nea扩展
       AsyncTask的<虚空,虚空,虚空> {
          私人ProgressDialog对话框;
        INT myProgress;

        @覆盖
        保护无效onPostExecute(无效的结果){

            displayRss();
             dialog.dismiss();

        }

        @覆盖
        在preExecute保护无效(){
            // TODO自动生成方法存根
              对话框= ProgressDialog.show(nea.this,,请耐心等待...,真正的);
            myProgress = 0;
        }

        保护无效onProgressUpdate(整数...进度){
          // TODO自动生成方法存根
          //super.onProgressUpdate(values​​);

            dialog.setProgress(进展[0]);
         }

        @覆盖
        保护无效doInBackground(虚空......为arg0){
            // TODO自动生成方法存根

            loadFeed(本);
            返回null;
        }



    }


    公众最终布尔isInternetOn(){
        ConnectivityManager CONNEC =(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        //我们是否连接到网络
        如果(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){
        //消息筛选测试(IF REQ)
        //Toast.makeText(this,connectionType +连接,Toast.LENGTH_SHORT).show();
        返回true;
        }否则如果(connec.getNetworkInfo(0).getState()== NetworkInfo.State.DISCONNECTED || connec.getNetworkInfo(1).getState()== NetworkInfo.State.DISCONNECTED){
        //System.out.println("Not连接);
        返回false;
        }
        返回false;
        }
}
 

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

编辑:

 公共无效toast_doInBck(查看视图){
        //做一些长
        可运行可运行=新的Runnable(){
            @覆盖
            公共无效的run(){
                的for(int i = 0; I< = 10;我++){
                    Toast.makeText(nea.this,R.string.no_connection,Toast.LENGTH_SHORT).show();
                    handler.post(新的Runnable(){
                        @覆盖
                        公共无效的run(){
                        }
                    });
                }
            }
        };
        新的线程(可运行)。开始();
    }
 

EDIT2:

 私人无效loadFeed(AsyncTask的<虚空,虚空,虚空>的AsyncTask){
        尝试{
            BaseFeedParser分析器=新BaseFeedParser();
            消息= parser.parse();

            }
         捕获(的Throwable T){
              Log.e(OSFP.News,t.getMessage(),叔);
活套prepare()。
                Toast.makeText(nea.this,Παρακαλώπροσπαθήστεαργότερα..
                        Toast.LENGTH_SHORT).show();
                完();
                Looper.loop();

            }
    }
 

解决方案

这可能是因为你想显示什么东西doInBackground()。 doInBackground运行在一个工作线程,不能做任何的用户界面的工作(包括显示敬酒,这是你在做什么)。相反,所有的用户界面的工作应在onPostExecute()来完成。

Sometimes i get this crash error in my app

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

This is the full 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

and this is my .nea class code:

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;
        }
}

Why am i getting this error?How can i solve it?Thanks :)

EDIT:

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();

            }
    }

解决方案

This is probably because you're trying to display something on doInBackground(). doInBackground runs in a worker thread which cannot do any UI work (including showing Toasts, which is what you're doing). Instead, all UI work should be done on onPostExecute().

这篇关于java.lang.RuntimeException的:执行doInBackground时出错()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆