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

}

Logcatからのエラー

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実行可能ファイルよりもはるかに効率的です。また、メインタスクが完了するとUIスレッドで実行されるonPostExecuteメソッドがあり、UI要素を更新できるようになります。リンク

于 2013-03-06T11:43:38.763 に答える
0

nullPointerExceptionが発生します:-次の2つの理由が考えられます。-1。ProgressDialogがnull値を取得するということは、データを入力せずに混乱することを意味します。だからチェック

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

2.またはalertdialogの値がnullです。& 試す:-

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

コードの以下の部分を変更します。ProgressDialogをnullにした場所。そして、メインスレッドにalertdialogを表示しようとしています。以下のように試してください:

まず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 に答える