使用AlertDialog时捕获异常?

时间:2011-10-16 18:17:38

标签: android error-handling

我试图让我的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):

public boolean onTouchEvent(MotionEvent e, MapView mv){
        int i = e.getAction();

        switch(i){

        case MotionEvent.ACTION_DOWN:
            //When your finger touches the screen
            Log.d("ACTION DOWN", "Finger touched screen");

            break;

        case MotionEvent.ACTION_UP:
            //When your finger stop touching the screen
            Log.d("ACTION UP", "Finger was removed from screen");
            try{
            PlacepinDialog alertDialog = new PlacepinDialog(null);
            }
            catch(){

            }
            break;

        case MotionEvent.ACTION_MOVE:
            //When your finger moves around the screen
            Log.d("ACTION MOVE", "Finger was moved around the screen");

            break;
        }

        return false;
    }

1 个答案:

答案 0 :(得分:2)

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

    PlacepinDialog alertDialog = new PlacepinDialog(null);

public PlacepinDialog(Context context)

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

从您的代码中挑选这些行。这导致了这个问题。