Android 使用AlertDialog时捕获异常?

Android 使用AlertDialog时捕获异常?,android,error-handling,Android,Error Handling,我试图将我的alertdialog设置为一个独立于主类的类,当它被调用时也会出现错误,应用程序停止,我想知道如何捕获异常,或者如何在这样的代码中找到错误 以下是警报对话框的代码: import android.app.AlertDialog; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; imp

我试图将我的alertdialog设置为一个独立于主类的类,当它被调用时也会出现错误,应用程序停止,我想知道如何捕获异常,或者如何在这样的代码中找到错误

以下是警报对话框的代码:

import android.app.AlertDialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class PlacepinDialog extends AlertDialog{

    AlertDialog.Builder builder;
    AlertDialog alertDialog;
    TextView text;
    ImageView image;
    Button place;
    Button cancel;
    LayoutInflater inflater;
    View layout;

    public PlacepinDialog(Context context) {
        super(context);
        //Setting up View and Inflater
        LayoutInflater inflater = (LayoutInflater)getLayoutInflater();
        View layout = inflater.inflate(R.layout.placepin_dialog,
                (ViewGroup) findViewById(R.id.mvMain));

        //Text Views
        TextView text = (TextView) layout.findViewById(R.id.Placetext);
        text.setText("Do you want to place a pin at the location you pressed?");

        //Image Views
        ImageView image = (ImageView) layout.findViewById(R.id.Placeimage);
        image.setImageResource(R.drawable.icon);

        //Building the Dialog
        builder = new AlertDialog.Builder(context);
        builder.setView(layout);
        alertDialog.setTitle("Place Pin");
        alertDialog = builder.create();
    }
    }
这里是调用alertdialog的地方(这个onTouchEvent在主类之外的另一个类中,所以我不能只执行main.this):


您将上下文传递为null,这就是问题所在。给一些适当的值,你可能得不到它

    PlacepinDialog alertDialog = new PlacepinDialog(null);

public PlacepinDialog(Context context)

builder = new AlertDialog.Builder(context); // context is null.

这些行是从代码中选取的。这就是问题的根源。

什么样的环境适合这样做?我还需要好好阅读一下android环境的内容。你必须传递你活动的环境。MyActivity.this,可能是。你知道我可以从这个上下文中了解的一些链接或页面吗?因为我不知道它是怎么工作的。。在类中调用对话框时没有创建上下文。您是从onTouchEvent调用它,它必须位于视图类或子类中。视图有一个getContext()方法来返回视图的上下文。我尝试只放置MyActivity。这表明出现了一些新错误。。但是,如果我想使用上下文,那么上下文c应该等于什么呢?
    PlacepinDialog alertDialog = new PlacepinDialog(null);

public PlacepinDialog(Context context)

builder = new AlertDialog.Builder(context); // context is null.