我有一个警告对话框,点击一个按钮我在一个单独的线程中进行webservice调用然后我想更新UI线程上的一些UI但是没有定义AlertDialog中的runOnUiThread,我该怎么做?
我还尝试使用runOnUiThread和AlertDialog的所有者活动的上下文。但我收到代码后发布的错误。 这是我的代码
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);
}
}
来自Log cat的错误
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)
答案 0 :(得分:3)
您是否尝试过使用Android AsyncTask?这比标准的Java runable更有效。它还有一个onPostExecute方法,该方法在主要任务完成后在UI线程上运行,并允许您更新UI元素。 link
答案 1 :(得分:0)
您收到nullPointerException: - 可能有两个原因: - 1. ProgressDialog采用null值意味着没有填充是dismess。 所以检查
if(progressDialog!=null){
mProgressDialog = ProgressDialog.show(RecordDialog.this.getContext(),
"Please wait....", "Recording Program....", true);
mProgressDialog.setCancelable(true);
}
2.或alertdialog具有空值。 &安培;尝试: -
Activity.runOnUiThread(new Runnable() {
public void run() {
AlerDialog();
}
});
答案 2 :(得分: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); }
完成上述更改后,请在runOnUiThread中运行AlertDialog
,如下所示:
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(); } }); } } };