【问题标题】:Showing a Toast message inside a thread for click event on a dialog box在对话框上的单击事件线程内显示 Toast 消息
【发布时间】:2013-12-09 09:28:06
【问题描述】:

我正在开发一个应用程序,用于显示从 Web 服务获取的数据到列表视图。实际上,根据我的应用程序:当用户从列表视图中单击一个项目时,应该询问一些带有对话框的消息。当用户按“是”时,会发生 Web 服务调用过程。所以..我想显示一个进度对话框,直到 Web 服务调用过程完成(用于调用 Web 服务的方法返回一个字符串消息。我想在此进度对话框关闭后显示该消息)。

我正在适配器类的 getview 方法中编写这些代码。

这是我的代码

    public View getView(final int position, View convertView, final ViewGroup parent) {
    // TODO Auto-generated method stub

    View vi = convertView;
    if(convertView==null)
        vi = inflater.inflate(R.layout.dialog_row,null);


        //final TextView firstname = (TextView) vi.findViewById(R.id.fname);
        //final TextView lastname = (TextView) vi.findViewById(R.id.lname);
        final TextView startTime = (TextView) vi.findViewById(R.id.stime2);
        final TextView endTime = (TextView) vi.findViewById(R.id.etime2);
        final TextView date = (TextView) vi.findViewById(R.id.blank2);
        final TextView uid = (TextView) vi.findViewById(R.id.lname2);
        final TextView appid = (TextView) vi.findViewById(R.id.hidenappoinment);
        final ImageView img = (ImageView) vi.findViewById(R.id.list_image2);


        HashMap<String, String> song = new HashMap<String, String>();
        song =data.get(position);

        //firstname.setText(song.get(MainActivity.TAG_PROP_FNAME));
        //lastname.setText(song.get(MainActivity.TAG_PROP_LNAME));
        startTime.setText(song.get(MainActivity.TAG_STIME));
        endTime.setText(song.get(MainActivity.TAG_ETIME));
        date.setText(song.get(MainActivity.TAG_DATE));
        uid.setText(song.get(ShortList.TAG_UID));
        appid.setText(song.get(ShortList.TAG_APOINMENTID));



        //imageLoader.DisplayImage(song.get(CustomizedListView.KEY_THUMB_URL), img);





        vi.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                //String getFname = firstname.getText().toString();
                Toast.makeText(parent.getContext(), "view clicked: " , Toast.LENGTH_SHORT).show();

                //get the id of the view
                //check the id of the request
                //call the web service acording to the id

                AlertDialog.Builder alertbuild = new AlertDialog.Builder(activity);

                alertbuild.setMessage("Everything else will be Considerd as Rejected! Are You Sure ?");
                alertbuild.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(final DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        //Toast.makeText(mContext, "Yes ", Toast.LENGTH_LONG).show();

                        final String getStime = startTime.getText().toString();
                        final String getEtime = endTime.getText().toString();
                        final String getDate = date.getText().toString();
                        final String getUid = uid.getText().toString();
                        final String getapid = appid.getText().toString();


                        final ProgressDialog ringProgressDialog = ProgressDialog.show(activity, "Please wait ...", "Request is in Progress ...", true);
                                    ringProgressDialog.setCancelable(false);

                                    new Thread(new Runnable() {
                                        @Override
                                    public void run() {
                                            try {
                                                // Here you should write your time consuming task...
                                                // Let the progress ring for 10 seconds...


                                            //  ShortList sendandget = new ShortList();

                                            //    String resp = sendandget.sendDataAndGetResponce(getDate, getStime, getEtime,getUid,getapid);

                                            //    if(resp.equalsIgnoreCase("true")){


                                            //    }
                                                Thread.sleep(10000);


                                            } catch (Exception e) {

                                                e.printStackTrace();
                                        }
                                            ringProgressDialog.dismiss();
                                            Toast.makeText(mContext, "Your Request Accepted", Toast.LENGTH_LONG).show();
                                            dialog.dismiss();
                                        }
                                    }).start();




                    //  ArrayList<HashMap<String, String>> rfejected = getRejected.getRejectedList(getDate, getStime, getEtime,getUid,getapid);
                        //ArrayList<HashMap<String, String>> accept = getRejected.getAccept(getDate, getStime, getEtime,getUid,getapid);

                    //  sendaceptedAndReject(accept,getUid,rfejected,getapid);



                    }
                })

                .setNegativeButton("NO", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        Toast.makeText(mContext, "No ", Toast.LENGTH_LONG).show();
                    }
                });

                alertbuild.show();


            }
        });

        return vi;



}

我试图发布一条 toast 消息以了解天气是否正常工作。进度对话框正在显示,但在我等待它的时间之后,它就被解雇了,没有显示我的 toast 消息。

请有人帮助我

我尝试过使用异步任务

这是我的编码..我没有做任何复杂的事情..只是想让 C 它工作与否..但是 OnPreExecute() 它没有显示 progressDialog :(

    public class ShowResponce extends AsyncTask<String, Void, String>{

    private ProgressDialog pDialog;

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        pDialog = new ProgressDialog(activity);
        pDialog.setMessage("Getting Data ...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();


    }

    @Override
    protected String doInBackground(String... arg0) {
        // TODO Auto-generated method stub
        //ShortList sendandget = new ShortList();
        //String resp = sendandget.sendDataAndGetResponce(getDate, getStime, getEtime,getUid,getapid);
        String x="a";

        return x;
    }

    @Override
    protected void onPostExecute(String x) {
        // TODO Auto-generated method stub
         pDialog.dismiss();

         Toast.makeText(mContext, x, Toast.LENGTH_LONG).show();

    }





}

【问题讨论】:

  • 哪种吐司不起作用?
  • 这个:Toast.makeText(mContext, "Your Request Accepted", Toast.LENGTH_LONG).show();
  • 使用AsyncTask调用web-service

标签: android multithreading dialog


【解决方案1】:

你不能在任何线程中做任何与 UI 相关的工作。为此,您必须使用 Hanlder 或仅使用 AsyncTask 调用 web-servicee 并在 AsyncTask 的 onPostExecute() 中显示您的 Toast。

【讨论】:

  • 我已经这样做了..但是因为我在一个不是活动的类中,并且由 BaseAdapter 扩展它会产生一个错误,说 12-09 16:19:45.800: E/AndroidRuntime( 14054): android.view.WindowManager$BadTokenException: 无法添加窗口 -- 令牌 null 不适用于应用程序你能帮我解决这个问题吗?
  • 在您的 BaseAdapter 类中,您必须传递活动的对象,然后像这样执行 - Toast.makeText(activityInstance, "Toast", Toast.LENGTH_LONG).show();跨度>
  • @Gishantha Darshana .....是的,没关系。如果“mContest”是 Activity 实例,那么您一定看到了 Toast ?
【解决方案2】:

可以使用 runOnUiThread() 为例

this.runOnUiThread(show_toast);

在 show_toast 中

private Runnable show_toast = new Runnable()
{
    public void run()
    {
        Toast.makeText(Autoamtion.this, "My Toast message", Toast.LENGTH_SHORT)
                    .show();
    }
};

点击~Toast from a Non-UI thread

【讨论】:

    【解决方案3】:

    使用RunOnUiThread 显示来自另一个线程的toast

    runOnUiThread(new Runnable() {
        public void run() {
            //Toast
        }
    });
    

    【讨论】:

      【解决方案4】:

      您无法在单个线程中显示 Toast 消息,因为它未链接到您的 UI 线程。

      您必须在工作完成后Handler 概念或runOnUiThread() 显示Toast 消息。

      查看runOnUiThread() 和 Handler 类的以下代码,它们可能会对您有所帮助。

      runOnUiThread(new Runnable() {
                       public void run() {
      
                           Toast.makeText(mContext,"your message",Toast.LENGTH_LONG).show();
                      }
                  });
      

      以下是使用 Handler 的替代方式。

      Handler h = new Handler({
       public void handleMessage(Message m) {
                        Toast.makeText(mContext,"your message",Toast.LENGTH_LONG).show();
                  }
      });
      

      然后当你想显示消息时调用下面的语句。

      h.sendEmptyMessage(0);
      

      【讨论】:

      • 我又添加了一行代码来调用处理程序。这就是您需要的代码示例。您可以在任何地方将 Handler 对象定义为 Activity 中的内部类,并在您想要显示消息时调用 h.sendEmptyMessage(0)。否则用户 runOnUiTjread() 您要在其中显示 toast 消息。
      【解决方案5】:

      关注http://developer.android.com/guide/components/processes-and-threads.html

      这样做

      public void onClick(View v) {
          new Thread(new Runnable() {
              public void run() {
                  Bitmap b = loadImageFromNetwork("http://example.com/image.png");
                  mImageView.setImageBitmap(b);
              }
          }).start();
      }
      

      改成

      public void onClick(View v) {
          new Thread(new Runnable() {
              public void run() {
                  final Bitmap bitmap = loadImageFromNetwork("http://example.com/image.png");
                  mImageView.post(new Runnable() {
                      public void run() {
                          mImageView.setImageBitmap(bitmap);
      Toast.makeText(mContext,"your message",Toast.LENGTH_LONG).show();
      
                      }
                  });
              }
          }).start();
      

      }

      【讨论】:

        【解决方案6】:

        使用处理程序类显示 Toast 消息。

         dialog = ProgressDialog.show(mContext, "Your Application", "Processing...",
                    true);
        
         final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            dialog.dismiss();
                   Toast.makeText(mContext, "Your Request Accepted", Toast.LENGTH_LONG).show();
                                                dialog.dismiss();
          }
        
          callService = new Thread() {
                public void run() {
                    try {
                        result = CallWebserice(address);
                        handler.sendEmptyMessage(0);
                    } catch (Exception e) {
                    }
                }
            };
          callService.start();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-03-11
          • 2019-09-12
          • 1970-01-01
          • 2018-04-04
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多