Android AsyncTask 对话框警报

发布于 2024-12-14 20:02:48 字数 2712 浏览 0 评论 0原文

我有一个启动屏幕,用于检查服务器上是否有任何新内容的 URL。如果显示我希望向应用程序用户显示一个警报对话框,以便根据用户的操作,即如果是从服务器下载新内容并将其获取到数据库,否则如果否从服务器加载应用程序的内容。

但是我无法在 AsyncTask 中使用警报对话框 我的代码片段如下:

protected String doInBackground(String... mode){
  /* I AM QUERY MY DATABASE FOR THE PREVIOUS CONTENT(SAY CONTENT 1, CONTENT 2);
  * then i start my connection to the server which has an xml file with the content
  * info (say content 3), at this stage .
  * i Check certain condition here,
  * say if result ==0 then i wish to display an alertdialog.
  * I used an alert dialog and i get some error. Stating use Looper or Handler.

  * Can anyone help me with this?
  */  
}

编辑

所以

doInBackGround(String... mode){
  if(result==0){
    // how do i implement this alert show that if the dialog appears and on clicking Yes i wish to exectute the URL handling part below        

    AlertDialog.Builder alert = new AlertDialog.Builder(context);
    alert.setTitle("Updates Found");
    alert.setMessage( "New Updates for has been found.\n Would you like to download ?\n"
              + "Whats the update: Checking "+pld.result.get(i).get( "issue" ));
    alert.setIcon(android.R.drawable.ic_dialog_info);                              
    alert.setPositiveButton(android.R.string.yes,
      new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int id) { 
          try { 
            URL url = new URL(pld.result.get(i).get("link"));
            ManageZipFile.getArchive(url,pld.result.get(i).get("issue"), file); 
          } 
          catch (Exception ex) { 
            Log.d(TAG, "Exception from URL"+ ex.getMessage()); 
          }

          progressState += updateProgressBar(20);
          pld.saveCoverData(pld.result.get(i).get("issue"));
          try { 
            pldContent = new PullLoadData(getString(R.string.files_path) 
                                          + pld.result.get(i).get("issue") 
                                          + "/contents.xml",context); 
            pldContent.getNewsItems();
            progressState += updateProgressBar(20); 
          } 
          catch(XmlPullParserException e) { 
            Log.e(TAG, "GetNEWSITEM "+ e.getMessage()); 
          } 
          catch (IOException e) { 
            Log.e(TAG, "XML FIle not found" + e.getMessage()); 
          } 
        } 
     });

     alert.setNegativeButton(android.R.string.no, 
       new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int arg1) { 
           dialog.dismiss();
       }
     }); 

     AlertDialog showAlert = alert.create();
     showAlert.show();
   }
 }

I have a splash screen which check an URL if there's any new content on the server. If show i wish to show a AlertDialog, to the app user so that depending on the action of user,i.e if YES download new contents from the server and get it to database else if NO load the contents for the app from the server.

However i am not being able to use an alert dialog inside AsyncTask
My snippet code is as:

protected String doInBackground(String... mode){
  /* I AM QUERY MY DATABASE FOR THE PREVIOUS CONTENT(SAY CONTENT 1, CONTENT 2);
  * then i start my connection to the server which has an xml file with the content
  * info (say content 3), at this stage .
  * i Check certain condition here,
  * say if result ==0 then i wish to display an alertdialog.
  * I used an alert dialog and i get some error. Stating use Looper or Handler.

  * Can anyone help me with this?
  */  
}

Edited

So in

doInBackGround(String... mode){
  if(result==0){
    // how do i implement this alert show that if the dialog appears and on clicking Yes i wish to exectute the URL handling part below        

    AlertDialog.Builder alert = new AlertDialog.Builder(context);
    alert.setTitle("Updates Found");
    alert.setMessage( "New Updates for has been found.\n Would you like to download ?\n"
              + "Whats the update: Checking "+pld.result.get(i).get( "issue" ));
    alert.setIcon(android.R.drawable.ic_dialog_info);                              
    alert.setPositiveButton(android.R.string.yes,
      new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int id) { 
          try { 
            URL url = new URL(pld.result.get(i).get("link"));
            ManageZipFile.getArchive(url,pld.result.get(i).get("issue"), file); 
          } 
          catch (Exception ex) { 
            Log.d(TAG, "Exception from URL"+ ex.getMessage()); 
          }

          progressState += updateProgressBar(20);
          pld.saveCoverData(pld.result.get(i).get("issue"));
          try { 
            pldContent = new PullLoadData(getString(R.string.files_path) 
                                          + pld.result.get(i).get("issue") 
                                          + "/contents.xml",context); 
            pldContent.getNewsItems();
            progressState += updateProgressBar(20); 
          } 
          catch(XmlPullParserException e) { 
            Log.e(TAG, "GetNEWSITEM "+ e.getMessage()); 
          } 
          catch (IOException e) { 
            Log.e(TAG, "XML FIle not found" + e.getMessage()); 
          } 
        } 
     });

     alert.setNegativeButton(android.R.string.no, 
       new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int arg1) { 
           dialog.dismiss();
       }
     }); 

     AlertDialog showAlert = alert.create();
     showAlert.show();
   }
 }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

沦落红尘 2024-12-21 20:02:48

这是因为 doInBackground 方法在非 UI 线程上运行,而 AlertDialog 需要在 UI 线程上显示。

要解决您的问题,请将 AlertDialog 的代码移至 AsyncTask 中的 onProgressUpdate 方法,然后当您想要显示 Dialog 时doInBackground 调用 publishProgress()

protected String doInBackground( String... mode ) {
  if( something )
    //Conditions for showing a Dialog has been met
}

protected void onProgressUpdate( Void... params ) {
  //Show your dialog.
}

如果您需要向对话框传递某种变量/数据,您可以传递您在 中声明的数据类型代码>扩展AsyncTask - 其中 Progress 是您可以通过 publishProgress( myVariable ) 方法传递的参数类型。

This is because the method doInBackground runs on a non-UI thread, and an AlertDialog needs to be displayed on the UI-thread.

To solve your problem, move the code for your AlertDialog to the method onProgressUpdate in AsyncTask, then when you want to display the Dialog call publishProgress() from doInBackground

protected String doInBackground( String... mode ) {
  if( something )
    //Conditions for showing a Dialog has been met
}

protected void onProgressUpdate( Void... params ) {
  //Show your dialog.
}

If you need to pass some kind of variable/data to the dialog, you can pass the kind of data you declared in extends AsyncTask<Params, Progress, Result> - where Progress is the type of parameter you can pass via the publishProgress( myVariable )-method.

路还长,别太狂 2024-12-21 20:02:48

UI 线程意味着它与您的 UI 直接关联。您无法执行诸如网络数据获取、磁盘访问等操作,这些操作需要在 UI 线程中花费大量处理时间。它们应该在单独的线程中完成。

AsyncTask 有助于在单独的线程中执行这些操作,否则可能会导致臭名昭著的 ANR 错误。(应用程序不响应)。

AsyncTask 包含诸如 onPreExecute() onPostExecute() onProgressUpdate() 、doInBackground () 等方法,您可以从 onPreExecute() onPostExecute() onProgressUpdate() 访问 UI 线程。操作需要更长的处理时间应该在 doinbackground() 中执行。

我无法理解您的问题的功能需求,但如果您想显示 Alert对话框 数据获取操作之前,从onPreExecute()显示它
或者如果您想数据获取后显示从 onPostExecute() 执行此操作。

UI thread means it is associated directly with your UI.you cant do operations like network datafetch,disk access etc which require large processing time in your UI thread. They should be done in seperate thread.

AsyncTask helps to carry out theese operations in seperate thread which may otherwise results in infamous ANR error.(application not responding).

AsyncTask contain methods like onPreExecute() onPostExecute() onProgressUpdate() ,doInBackground ()etc you can access UI thread from onPreExecute() onPostExecute() onProgressUpdate() .The operation requiring longer processing time should be carried out in doinbackground().

I can't understand the functionality demands from your question but if you want to display Alert Dialog before data fetching operation,Display it from onPreExecute()
or if you want to display after data fetch Do it from onPostExecute().

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文