Android:尝试在异步任务中创建对话框<;字符串对象
我正在使用异步任务 我使用parent创建无错误的意图 创建对话框的行给出了一个 无法将父级解析为ye。 新建parent.AlertDialog.Builder(此) 我得到的错误是parent不存在,但我使用parent以相同的方法调用intent 代码块 私有类SendTextOperation扩展了AsyncTask{Android:尝试在异步任务中创建对话框<;字符串对象,android,Android,我正在使用异步任务 我使用parent创建无错误的意图 创建对话框的行给出了一个 无法将父级解析为ye。 新建parent.AlertDialog.Builder(此) 我得到的错误是parent不存在,但我使用parent以相同的方法调用intent 代码块 私有类SendTextOperation扩展了AsyncTask{ @Override protected void onPreExecute() { //Update UI here
@Override
protected void onPreExecute() {
//Update UI here
}
@Override
protected String doInBackground(String... params) {
// Talk to server here to avoid Ui hanging
rt=TalkToServer("http://besttechsolutions.biz/projects/bookclub/login.php");
return(rt);
}
@Override
protected void onPostExecute(String result) {
if (rt.contains("ok"))
{
Intent i = new Intent(parent, cChat.class);
startActivity(i);
}
else
{
new parent.AlertDialog.Builder(this)
.setTitle("Game Over")
.setMessage("Your time is up, You saved "
+" Million more people!!")
.setNeutralButton("Try Again",new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dlg, int i)
{
}} ).show();
}
}
}
假设您在名为MyActivity的类中声明了该类
然后在创建对话框时使用MyActivity.this来代替它。要从非活动中显示
AlertDialog
,您需要将当前活动上下文传递到非活动类,在您的情况下,传递到SendTextOperation
类
为SendTextOperation
创建一个构造函数
,如下所示:
public class SendTextOperation extends AsyncTask<String,Void,String>{
Context context;
public SendTextOperation(Context context) {
this.context = context;
}
@Override
protected void onPreExecute() {
//Update UI here
}
@Override
protected String doInBackground(String... params) {
// Talk to server here to avoid Ui hanging
rt=TalkToServer("http://besttechsolutions.biz/projects/bookclub/login.php");
return(rt);
}
@Override
protected void onPostExecute(String result) {
if (rt.contains("ok"))
{
Intent i = new Intent(context, cChat.class);
startActivity(i);
}
else
{
new context.AlertDialog.Builder(context)
.setTitle("Game Over")
.setMessage("Your time is up, You saved "
+" Million more people!!")
.setNeutralButton("Try Again",new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dlg, int i)
{
}} ).show();
}
}
}
SendTextOperation sendtxtasyncTask = new SendTextOperation(CurrentActivity.this);
sendtxtasyncTask.execute("");
看起来你应该这样称呼它:
final AlertDialog.Builder builder = new AlertDialog.Builder(_context);
builder.setMessage(_context.getString(R.string.error) + ": " + _errorMessage)
.setTitle(_context.getString(R.string.loginError))
.setIcon(android.R.drawable.ic_dialog_alert)
.setCancelable(true)
.setPositiveButton(_context.getString(R.string.ok), null);
final AlertDialog alert = builder.create();
alert.show();
(我自己的示例代码)
您的错误似乎是试图执行
parent.AlertDialog.Builder(此)
,如果parent是您的上下文,则需要使用new AlertDialog.Builder(父)
。尝试new AlertDialog.Builder(父)
,或者如果AsyncTask是一个内部非静态活动类,则可以初始化AlertDialog.Builder(你的活动。这个)请不要投票给我的答案,因为我有一顶红帽子。red hat
。那么投票不会影响我的观点。我投票给你是因为答案足够正确。我甚至没有看你的代表。@doctordrive:你是对的,但这个答案在两种情况下都有效