2

我有一个警报对话框,在单击按钮时,我在单独的线程中进行 Web 服务调用,然后我想更新 UI 线程上的一些 UI,但未定义 AlertDialog 中的 runOnUiThread,我该怎么做?

我还尝试在 AlertDialog 的所有者活动上下文中使用 runOnUiThread。但我收到代码后发布的错误。这是我的代码

 public class RecordDialog extends Dialog implements OnClickListener {
Button recordButton;

/*
 * param context
 */

String requestResponse="";
int progIndex=0;
public static String sessionId = "";
public static String programId = "";
public static String channelId = "";

static Handler handler;
Context cont;

public RecordDialog(Context context) {
    super(context);
    cont= context;
    /** 'Window.FEATURE_NO_TITLE' - Used to hide the title */
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    /** Design the dialog in main.xml file */
    setContentView(R.layout.record_dialog);
    recordButton = (Button) findViewById(R.id.recordBtn);
    recordButton.setOnClickListener(this);
    sessionId = SuccessLogin.userId;
    handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // process incoming messages here
            switch (msg.what) {
            // ///normal - just update message shown on progress dialog
            case 0:
                // update progress bar
                // serviceClient.myprogress.setMessage("" +(String)
                // msg.obj);
                break;
            // normal - cancel the dialog and update the UI
            case 1:

                break;
            // error - may be due to bad settings, or bad response from

            case 2:
                // serviceClient.myprogress.cancel();
                // AlertDialog alert = ServerNotResponding((String)
                // msg.obj);
                // alert.show();
                break;
            }

            super.handleMessage(msg);
        }
    };
}

public static org.w3c.dom.Element recElement;

private static String extractResponse(String xml)
        throws ParserConfigurationException, SAXException, IOException {

    @SuppressWarnings("deprecation")
    java.io.InputStream sbis = new java.io.StringBufferInputStream(xml);

    javax.xml.parsers.DocumentBuilderFactory b = javax.xml.parsers.DocumentBuilderFactory
            .newInstance();
    b.setNamespaceAware(false);
    org.w3c.dom.Document doc = null;
    javax.xml.parsers.DocumentBuilder db = null;

    db = b.newDocumentBuilder();
    doc = db.parse(sbis);
/*  org.w3c.dom.Element docElem= doc.getDocumentElement();

    NodeList items = docElem.getElementsByTagName("UserID");
    Log.v("items count", items.getLength()+"...");




    NodeList nodes= docElem.getElementsByTagName("UserID");
    Log.v("value", "......"+nodes.item(0).getTextContent());
    if(nodes.item(0).getTextContent().equals("UserID"))
    {
        String value=nodes.item(0).getNodeValue();
        Log.v("value", "......"+value);
    }*/
    return doc.getDocumentElement().getTextContent().trim()
            .replaceAll("responseStatus", "").trim();
}
public String recordProgram()
{
    String action = "action=submitChannelProgramRecordingRequest&cid="
            + channelId
            + "&sid="
            + sessionId
            + "&pid="
            + programId;

    String res = ServiceClient
            .submit_ChannelRecordingRequest(action, handler);
    Log.v("recording request sent response", res
            + "***&&&&");


    try {
        res = extractResponse(res);
        return res;
    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return res;

}

Runnable recordProg ;
private ProgressDialog mProgressDialog = null;

private Runnable invalidRes = new Runnable() {

    public void run() {

        mProgressDialog.dismiss();
        /*
         * AlertDialog alert = ServerNotResponding(); alert.show();
         */

    }
};

private Runnable retRes = new Runnable() {

    public void run() {

          mProgressDialog.dismiss();


            GuideActivity.progs.get(progIndex).isRecordingRequested="true";
            if(requestResponse.equals("Program Recording Started"))
            {
                recordButton.setBackgroundResource(R.drawable.record_already_btn_background);
                Log.v("Program Recording Started", "Program Recording Started");
                //Toast.makeText(RecordDialog.this.getContext(), "Program Recording Started.", Toast.LENGTH_LONG).show();

                AlertDialog.Builder builder = new AlertDialog.Builder(
                        RecordDialog.this.getContext());

                builder.setTitle("");
                 builder.setMessage("Program Recording Started");

                builder.setPositiveButton("Ok",
                        new DialogInterface.OnClickListener() {

                            public void onClick(
                                    DialogInterface dialog,
                                    int which) {

                                    dialog.dismiss();
                                }
                        });

                builder.create().show();
            }
            else
                if(requestResponse.equals("UPR ERROR-CODE :: ALREADY REQUESTED"))
                {
                    Log.v("Program Recording Started", "Program Recording Started");
                    //Toast.makeText(RecordDialog.this.getContext(), "Program Recording ALREADY REQUESTED", Toast.LENGTH_LONG).show();

                    AlertDialog.Builder builder = new AlertDialog.Builder(
                            RecordDialog.this.getContext());

                    builder.setTitle("");
                     builder.setMessage("Program Recording ALREADY REQUESTED");

                    builder.setPositiveButton("Ok",
                            new DialogInterface.OnClickListener() {

                                public void onClick(
                                        DialogInterface dialog,
                                        int which) {

                                        dialog.dismiss();
                                }

                            });

                    builder.create().show();
                }

    }
};




@Override
public void onClick(View v) {
    /** When OK Button is clicked, dismiss the dialog */
    //if (v == recordButton) {
        mProgressDialog = ProgressDialog.show(RecordDialog.this.getContext(),
                "Please wait....", "Recording Program....", true);
        mProgressDialog.setCancelable(true);


        mProgressDialog.setOnKeyListener(new OnKeyListener() {

            public boolean onKey(DialogInterface dialog, int keyCode,
                    KeyEvent event) {
                // TODO Auto-generated method stub
                // Log.v("key is pressed", "yes");
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    mProgressDialog.dismiss();
                    dialog.dismiss();

                }
                return false;
            }
        });


         recordProg = new Runnable() {

            public void run() {
                try {

                    String response= recordProgram();
                    //int index   = response.indexOf('\n');
                    //response = response.substring(index, response.length()).trim();

                    requestResponse=response;
                    Log.v("final response", response+"^^^^^^^^^^^^^^^^^^^^");
                }

                catch (Exception e) {

                     Log.v("Exception", e.getMessage() + "..");
                    // runOnUiThread(invalidRes);;
                RecordDialog.this.getOwnerActivity().runOnUiThread(invalidRes);
                }

                RecordDialog.this.getOwnerActivity().runOnUiThread(retRes);
            }
        };

        Thread thread = new Thread(null, recordProg, "MagentoBackground");
        thread.start();

         //dismiss();



    //}
}

@Override
public void onAttachedToWindow() {
    super.onAttachedToWindow();
    Window window = getWindow();
    window.setFormat(PixelFormat.RGBA_8888);
}

}

日志猫的错误

10-15 04:05:58.363: E/AndroidRuntime(3790): FATAL EXCEPTION: MagentoBackground
10-15 04:05:58.363: E/AndroidRuntime(3790): java.lang.NullPointerException
10-15 04:05:58.363: E/AndroidRuntime(3790):     at wherever.google.tv.guide.RecordDialog$5.run(RecordDialog.java:277)
10-15 04:05:58.363: E/AndroidRuntime(3790):     at java.lang.Thread.run(Thread.java:1020)


10-15 04:05:59.453: E/WindowManager(3790): Activity wherever.google.tv.guide.GuideActivity has leaked window com.android.internal.policy.impl.tv.TvWindow$DecorView@2c208668 that was originally added here
10-15 04:05:59.453: E/WindowManager(3790): android.view.WindowLeaked: Activity wherever.google.tv.guide.GuideActivity has leaked window com.android.internal.policy.impl.tv.TvWindow$DecorView@2c208668 that was originally added here
10-15 04:05:59.453: E/WindowManager(3790):  at android.view.ViewRoot.<init>(ViewRoot.java:292)
10-15 04:05:59.453: E/WindowManager(3790):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:249)
10-15 04:05:59.453: E/WindowManager(3790):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:193)
10-15 04:05:59.453: E/WindowManager(3790):  at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:118)
10-15 04:05:59.453: E/WindowManager(3790):  at android.view.Window$LocalWindowManager.addView(Window.java:554)
10-15 04:05:59.453: E/WindowManager(3790):  at android.app.Dialog.show(Dialog.java:277)
10-15 04:05:59.453: E/WindowManager(3790):  at android.app.ProgressDialog.show(ProgressDialog.java:115)
10-15 04:05:59.453: E/WindowManager(3790):  at android.app.ProgressDialog.show(ProgressDialog.java:98)
10-15 04:05:59.453: E/WindowManager(3790):  at wherever.google.tv.guide.RecordDialog.onClick(RecordDialog.java:236)
10-15 04:05:59.453: E/WindowManager(3790):  at android.view.View.performClick(View.java:3161)
10-15 04:05:59.453: E/WindowManager(3790):  at android.view.View.onKeyUp(View.java:5081)
10-15 04:05:59.453: E/WindowManager(3790):  at android.widget.TextView.onKeyUp(TextView.java:4999)
10-15 04:05:59.453: E/WindowManager(3790):  at android.view.KeyEvent.dispatch(KeyEvent.java:2689)
10-15 04:05:59.453: E/WindowManager(3790):  at android.view.View.dispatchKeyEvent(View.java:4629)
10-15 04:05:59.453: E/WindowManager(3790):  at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1163)
10-15 04:05:59.453: E/WindowManager(3790):  at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1163)
10-15 04:05:59.453: E/WindowManager(3790):  at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1163)
10-15 04:05:59.453: E/WindowManager(3790):  at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1163)
10-15 04:05:59.453: E/WindowManager(3790):  at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1163)
10-15 04:05:59.453: E/WindowManager(3790):  at com.android.internal.policy.impl.tv.TvWindow$DecorView.superDispatchKeyEvent(TvWindow.java:1191)
10-15 04:05:59.453: E/WindowManager(3790):  at com.android.internal.policy.impl.tv.TvWindow.superDispatchKeyEvent(TvWindow.java:794)
10-15 04:05:59.453: E/WindowManager(3790):  at android.app.Dialog.dispatchKeyEvent(Dialog.java:717)
10-15 04:05:59.453: E/WindowManager(3790):  at com.android.internal.policy.impl.tv.TvWindow$DecorView.dispatchKeyEvent(TvWindow.java:1147)
10-15 04:05:59.453: E/WindowManager(3790):  at android.view.ViewRoot.deliverKeyEventPostIme(ViewRoot.java:2946)
10-15 04:05:59.453: E/WindowManager(3790):  at android.view.ViewRoot.handleFinishedEvent(ViewRoot.java:2916)
10-15 04:05:59.453: E/WindowManager(3790):  at android.view.ViewRoot.handleMessage(ViewRoot.java:2093)
10-15 04:05:59.453: E/WindowManager(3790):  at android.os.Handler.dispatchMessage(Handler.java:99)
10-15 04:05:59.453: E/WindowManager(3790):  at android.os.Looper.loop(Looper.java:132)
10-15 04:05:59.453: E/WindowManager(3790):  at android.app.ActivityThread.main(ActivityThread.java:4196)
10-15 04:05:59.453: E/WindowManager(3790):  at java.lang.reflect.Method.invokeNative(Native Method)
10-15 04:05:59.453: E/WindowManager(3790):  at java.lang.reflect.Method.invoke(Method.java:491)
10-15 04:05:59.453: E/WindowManager(3790):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
10-15 04:05:59.453: E/WindowManager(3790):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
10-15 04:05:59.453: E/WindowManager(3790):  at dalvik.system.NativeStart.main(Native Method)
4

3 回答 3

4

您是否尝试过使用 android AsyncTask?这比标准的 Java 可运行文件要高效得多。它还有一个 onPostExecute 方法,一旦主要任务完成,它就会在 UI 线程上运行,并且应该允许您更新 UI 元素。关联

于 2013-03-06T11:43:38.763 回答
0

你得到 nullPointerException :- 可能有两个原因:- 1. ProgressDialog 取空值意味着不填充是混乱的。所以检查

         if(progressDialog!=null){
      mProgressDialog = ProgressDialog.show(RecordDialog.this.getContext(),
            "Please wait....", "Recording Program....", true);
    mProgressDialog.setCancelable(true);
    }

2.or alertdialog 有空值。& 尝试:-

                Activity.runOnUiThread(new Runnable() {
                            public void run() {
                                AlerDialog();
                            }
                        });
于 2013-03-06T11:47:37.300 回答
0

更改以下代码部分。您将ProgressDialogas 设为 null 的位置。你正试图在主线程上显示警报对话框。尝试如下:

首先在构造函数中初始化你ProgressDialog,如下所示:

     private ProgressDialog mProgressDialog = null;
     public RecordDialog(Context context) {
           super(context);
           cont= context;
        mProgressDialog = ProgressDialog.show(RecordDialog.this.getContext(),
            "Please wait....", "Recording Program....", true);
        }

上述更改后,AlertDialog在 runOnUiThread 中运行如下:

 private Runnable invalidRes = new Runnable() {
     public void run() {
        mProgressDialog.dismiss();
     }
    };
     private Runnable retRes = new Runnable() {
      public void run() {
      mProgressDialog.dismiss();
        GuideActivity.progs.get(progIndex).isRecordingRequested="true";
        if(requestResponse.equals("Program Recording Started"))
        {
          recordButton.setBackgroundResource(R.drawable.record_already_btn_background);
            Log.v("Program Recording Started", "Program Recording Started");
            //Toast.makeText(RecordDialog.this.getContext(), "Program Recording Started.", Toast.LENGTH_LONG).show();

           Activity.runOnUiThread(new Runnable() {
              public void run() {

               AlertDialog.Builder builder = new AlertDialog.Builder(
                    RecordDialog.this.getContext());
              builder.setTitle("");
             builder.setMessage("Program Recording Started");
              builder.setPositiveButton("Ok",
                    new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog,
                                int which) {
                     dialog.dismiss();
                            }
                    });

            builder.create().show();
               }
           });
        }
        else
            if(requestResponse.equals("UPR ERROR-CODE :: ALREADY REQUESTED"))
            {
                Log.v("Program Recording Started", "Program Recording Started");
                //Toast.makeText(RecordDialog.this.getContext(), "Program Recording ALREADY REQUESTED", Toast.LENGTH_LONG).show();

                 Activity.runOnUiThread(new Runnable() {
                  public void run() {

                      AlertDialog.Builder builder = new AlertDialog.Builder(
                        RecordDialog.this.getContext());
                  builder.setTitle("");
                 builder.setMessage("Program Recording ALREADY REQUESTED");
                 builder.setPositiveButton("Ok",
                        new DialogInterface.OnClickListener() {
                            public void onClick(
                                    DialogInterface dialog,
                                    int which) {
                                    dialog.dismiss();
                            }
                  });
             builder.create().show();
              }
             });
            }
  }
 };
于 2013-03-06T12:14:55.353 回答