0

我已经在 Android 中实现了 ppt 文件转换,并且正在使用 REST 等 Web 服务。但是我的代码是在主线程上运行的,所以我必须使用 do-In-Background() 来执行异步任务。

当我运行应用程序时,我收到如下错误/警告:

View Root CalledFromWrongThreadException 仅是创建视图层次结构的原始线程

没有 do-In-Background() 可以正常运行,但在运行状态下按下后退按钮时应用程序崩溃。这是我的代码。

      btnSubmit.setOnClickListener(new View.OnClickListener()
                {

                    @Override
                    public void onClick(View arg0) 
                    {

                       convertToImage();

                    }

                });

         protected void onActivityResult
                (int requestCode, int resultCode, Intent data)


                      {     
                      // TODO Auto-generated method stub 

                        if (requestCode == PATH)    

                         {      
                            if (resultCode == RESULT_OK)

                               {            
                                            if (data != null)

                                {
                                path = data.getStringExtra("path");
                                 System.out.println("Path  : " + path );

                              String strfpath = path ;

                                          String fileName2
                                          =strfpath.substring(strfpath.lastIndexOf("/")+1);

                              System.out.println("fileName2 :" + fileName2 );

                                   function_arg1.setText(fileName2);
                    }       

                  }     

             }

    }

这是我的 doInBackground() 方法

private void convertToImage() 
    {
        httpGetAsynchTask httpGetAsyncTask = new httpGetAsynchTask();
        httpGetAsyncTask.execute();
    }


    class httpGetAsynchTask extends AsyncTask<String , Integer , String>
    {
        protected void onPreExecute() {
               try{
                   dialog.setMessage("Please Wait");
                   dialog.show();
               }
               catch(Exception e)
               {

               }
            }




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

            if (function_arg1.getText().length() == 0)
            {
                AlertDialog.Builder dialog = new AlertDialog.Builder(StorageFolderUploadFile.this);
                dialog.setTitle("Error");
                dialog.setMessage("Please Enter Require Fields");
                dialog.setNeutralButton("Ok", null);
                dialog.show();
            } 


            else 

            {
                fileName = function_arg1.getText().toString();
                System.out.println("File Name :-  " + fileName);

                folderName="tazeen";

                Folder obj = new Folder();

                try 
                {
                    response = obj.uploadFile(path/*, folderName*/);
                    Log.e("",""+response);
                    if (response) 

                    {
                        result.append("File Uploaded Successfully \n");

                        Document docObj=new Document( fileName /*folderName*/);
                        count = docObj.getSlideCount();


                        if (count > 0) 
                        {
                            result.append(" \n Numbers Of Slides = " + count);
                            System.out.println("Number Of Slides " + count );



                            for(int i=1; i <= count ; i++)
                            {                          

                               System.out.println("________________________________________");

                                System.out.println("i  :-> " + i );

                                String outputPath = fileName + "_Tazeen" + i + ".jpg" ;
                                System.out.println("outputPath :-> " + outputPath);

                                slideNumber = i;
                                System.out.println("slideNumber :-> " + slideNumber);

                                Document docObj2=new Document(fileName);
                                System.out.println("docObj2 :-> " + docObj2);

                                docObj2.saveSlideAs(outputPath.toString().trim(), slideNumber, imageFormat);
                                System.out.println("docObj2 :-> " + docObj2);

                                result.append("slide is converted and save to your sdcard \n");

                                String imagePath = path + "/" + outputPath ;
                                System.out.println("imagePath : " + imagePath );


                            }

                        }

                    }

                    else 

                    {
                        result.append("Oops..Something went wrong");
                        }
                } 


                           catch (Exception e)
                           {
                            // TODO Auto-generated catch block
                               e.printStackTrace();


                           }



            }


            return fileName;
        }




        @Override
        public void onPostExecute(String values)
        {

            convertToImage(); 

            try
            {
                if(dialog.isShowing())
                {
                    dialog.dismiss();
                }
            }
            catch(Exception e)
            {}
        }

    }
4

3 回答 3

1

您无法从后台线程访问与用户界面有关的任何内容。所以所有的AlertDialog.Builder dialog都是不允许的,如果function_arg1是,View那么也应该避免。

注意:我担心是否System.out允许,但根据评论应该可以。

如果它有帮助,当我使用 时AsyncTask,我通常会创建一个类来保存所有可能的结果,包括错误消息和抛出的任何异常。然后,该对象可以根据onPostExecute.

于 2013-06-15T10:59:19.760 回答
0

打电话

new Async_Task(context, true).execute(multipartEntity, class);


public class Async_Task extends AsyncTask<Object,Boolean,String> {

    HttpHelper parsing;
    Object objs;
    private ProgressDialog Dialog;
    Context context;
    Boolean flag=true;

    public Async_Task(Context context,Boolean flag) {
        this.context=context;
        this.flag=flag;
        parsing=new HttpHelper(context);
    }

    @Override
    protected void onPreExecute() {
        if(flag)
        {
            Dialog = new ProgressDialog(context);
            Dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            Dialog.setMessage("Please Wait...");
            Dialog.setCancelable(false);
            Dialog.show();
        }
    }

    @Override
    protected String doInBackground(Object... urls) {
        MultipartEntity nameValuePairs=(MultipartEntity) urls[0];
        objs=urls[1];
        String obj=parsing.getJSONFromUrl(Constant.API,nameValuePairs);
//      Log.i("output",obj);
        return obj;
    }

    @Override
    protected void onPostExecute(String result)
    {
        if(flag)
            Dialog.dismiss();


        if(objs instanceof LoginActivity)
        {
            ((LoginActivity) objs).loginMessage(result);
        }
    }
}
于 2013-06-15T11:03:56.330 回答
0

您应该避免Alert DialogProgress Dialog. 因为是一个后台进程来帮助减少一个activity的主线程的负载。您可以在启动类之前或在方法内部调用这些类型的对话框和 toast。ToastdoInBackgroundAsyncTaskAsyncTaskonPreExecute

于 2013-06-15T12:02:39.033 回答