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

时间:2021-11-30 15:43:46

I have been trying to use the code given in the answer to this question although I choose not to use a separate class for the ListAdapter. When I try to start my activity (InfosActivity), the app crashes, here's the log :

虽然我选择不为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) 

I have read some topics abouts NullPointer exception but still can't find a solution.

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

Here is my ListAdapter:

这是我的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;
    }
};

And how I use it :

以及我如何使用它:

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();
        }
    });

Can you help me please ?

你能帮我吗 ?

1 个解决方案

#1


-1  

The problem is that you instantiate your ListAdapter in the declaration. So the instantiation is done during the instantiation of the InfoActivity class (So before it has finished to instantiate). If InfoActivity has not finished to instantiate, this is null. So when you do getApplicationContext() you are doing this.getapplicationContext() but this is null.

问题是您在声明中实例化ListAdapter。因此,实例化在InfoActivity类的实例化期间完成(因此在它完成实例化之前)。如果InfoActivity尚未完成实例化,则为null。所以当你执行getApplicationContext()时,你正在执行this.getapplicationContext(),但这是null。

You have to instantiate your ListAdapter after the Activity is instantiated. So you can for example instantiate your Listadapter in the onStart() method.

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


FurtherMore, as explained in this comment, if you need your activity context, use this instead of getApplicationContext()

更多,如本评论中所述,如果您需要活动上下文,请使用此代替getApplicationContext()

#1


-1  

The problem is that you instantiate your ListAdapter in the declaration. So the instantiation is done during the instantiation of the InfoActivity class (So before it has finished to instantiate). If InfoActivity has not finished to instantiate, this is null. So when you do getApplicationContext() you are doing this.getapplicationContext() but this is null.

问题是您在声明中实例化ListAdapter。因此,实例化在InfoActivity类的实例化期间完成(因此在它完成实例化之前)。如果InfoActivity尚未完成实例化,则为null。所以当你执行getApplicationContext()时,你正在执行this.getapplicationContext(),但这是null。

You have to instantiate your ListAdapter after the Activity is instantiated. So you can for example instantiate your Listadapter in the onStart() method.

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


FurtherMore, as explained in this comment, if you need your activity context, use this instead of getApplicationContext()

更多,如本评论中所述,如果您需要活动上下文,请使用此代替getApplicationContext()