尝试构建警报对话框时出现空指针异常

时间:2018-05-02 11:19:13

标签: java android nullpointerexception

我一直在尝试使用this问题答案中给出的代码,尽管我选择不为ListAdapter使用单独的类。 当我尝试启动我的活动(InfosActivity)时,应用程序崩溃,这里是日志:

05-02 11:50:22.195 7521-7521/com.example.uia59227.User_and_Car_Data E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                  Process: com.example.uia59227.User_and_Car_Data, PID: 7521
                                                                                  java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.uia59227.User_and_Car_Data/com.example.uia59227.User_and_Car_Data.InfosActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
                                                                                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2849)
                                                                                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045)
                                                                                      at android.app.ActivityThread.-wrap14(ActivityThread.java)
                                                                                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642)
                                                                                      at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                      at android.os.Looper.loop(Looper.java:154)
                                                                                      at android.app.ActivityThread.main(ActivityThread.java:6776)
                                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
                                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)
                                                                                   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
                                                                                      at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:106)
                                                                                      at com.example.uia59227.User_and_Car_Data.InfosActivity.<init>(InfosActivity.java:223)
                                                                                      at java.lang.Class.newInstance(Native Method)
                                                                                      at android.app.Instrumentation.newActivity(Instrumentation.java:1086)
                                                                                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2839)
                                                                                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045) 
                                                                                      at android.app.ActivityThread.-wrap14(ActivityThread.java) 
                                                                                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642) 
                                                                                      at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                                      at android.os.Looper.loop(Looper.java:154) 
                                                                                      at android.app.ActivityThread.main(ActivityThread.java:6776) 
                                                                                      at java.lang.reflect.Method.invoke(Native Method) 
                                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496) 
                                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386) 

我已经阅读了一些关于NullPointer异常的主题,但仍无法找到解决方案。

这是我的ListAdapter:

String[] items = {"airplanes", "animals", "cars", "colors", "flowers", "letters", "monsters", "numbers", "shapes", "smileys", "sports", "stars" };

ListAdapter adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.list_row, items) {

    ViewHolder holder;
    Drawable icon;

    class ViewHolder {
        ImageView icon;
        TextView title;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        final LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.list_row, null);

            holder = new ViewHolder();
            holder.icon = (ImageView) convertView.findViewById(R.id.icon);
            holder.title = (TextView) convertView.findViewById(R.id.title);
            convertView.setTag(holder);
        } else {
            // view already defined, retrieve view holder
            holder = (ViewHolder) convertView.getTag();
        }

        Drawable drawable = ContextCompat.getDrawable(context,R.drawable.ic_person); //this is an image from the drawables folder

        holder.title.setText(items[position]);
        holder.icon.setImageDrawable(drawable);

        return convertView;
    }
};

以及我如何使用它:

quickReviewButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
            alertDialogBuilder
                    .setTitle("Full report")
                    .setAdapter(adapter, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int item) {
                            Toast.makeText(InfosActivity.this, "You selected: " + items[item], Toast.LENGTH_LONG).show();
                            dialog.dismiss();
                        }
                    });

            // create alert dialog
            AlertDialog alertDialog = alertDialogBuilder.create();

            // show it
            alertDialog.show();
        }
    });

你能帮我吗?

1 个答案:

答案 0 :(得分:-1)

问题是您在声明中实例化ListAdapter。因此,实例化在InfoActivity类的实例化期间完成(因此在它完成实例化之前)。如果InfoActivity尚未完成实例化,则thisnull。因此,当您执行getApplicationContext() this.getapplicationContext()thisthis为空。

在实例化Activity之后,您必须实例化ListAdapter。因此,您可以在onStart()方法中实例化Listadapter。

FurtherMore,如此comment中所述,如果您需要活动上下文,请使用getApplicationContext()代替afr