0

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 :

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.

Here is my 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 ?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Loic T
  • 15
  • 3

1 Answers1

-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.

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


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

vincrichaud
  • 2,218
  • 17
  • 34
  • @ downvoter, could you provide a feedback ? So I can improve my answer – vincrichaud May 02 '18 at 11:54
  • I come back to you as I still have a NullPointerException pointing to the line `holder.icon.setImageDrawable(drawable);`. In the definition of the getview, I have a warning on `parent` that says `not annotated parameter overrides @NonNull parameter`and I don't know if this is the cause of my error – Loic T May 02 '18 at 13:15
  • It means that either `holder` or `icon` is null. `holder` is null if you go through the else and convertView.getTag() returned null. `icon` is null if you go through the if and `findViewById()` can't find a view having `R.id.icon` as ID, or you go through the else and the object returned by `convertView.getTag()` has a field icon that is null – vincrichaud May 02 '18 at 13:20
  • OK, that was not easy for me to understand but I made it, changed the `convertView.findViewById(R.id.icon);` thats doesn't exists (I don't get why I didn't have any error) into `findViewById(R.id.Car)` which actually exists, and it works. Thanks! – Loic T May 02 '18 at 13:48