Исключение нулевого указателя при попытке создать диалоговое окно предупреждения - PullRequest
0 голосов
/ 02 мая 2018

Я пытался использовать код, указанный в ответе на этот вопрос, хотя я решил не использовать отдельный класс для 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 голосов
/ 02 мая 2018

Проблема в том, что вы создаете экземпляр ListAdapter в объявлении. Таким образом, создание экземпляра выполняется во время создания экземпляра класса InfoActivity (т.е. до его завершения). Если InfoActivity еще не завершила создание экземпляра, this равно null. Поэтому, когда вы делаете getApplicationContext(), вы делаете this.getapplicationContext(), но this равно нулю.

Вы должны создать свой ListAdapter после того, как будет создан экземпляр Activity. Так, например, вы можете создать экземпляр своего Listadapter в методе onStart ().


Далее, как объяснено в этом комментарии , если вам нужен контекст вашей деятельности, используйте this вместо getApplicationContext()

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...