0

I have a listView and i use ArrayAdapter.addAll to load the data.I want to use ListView.getChild(0) after use ArrayAdapter.addAll at once.But NullPointerException was thrown.

I try to add the ListView.getChild(0) to the MessageQueue by using Handler.post.The app works sometimes since as I do this, but sometimes the NullPointerException also was thrown.

My Code:

mRightAdapter.addAll(mRightDisplayDatas); 
mHandler.post(new Runnable() {
    @Override public void run() { 
    ((TextView) mLeftListView.getChildAt(0)).setCompoundDrawablesWithIntrinsicBounds(null, null, getResources().getDrawable(R.mipmap.ic_right, mContext.getTheme()), null);
   }
});

log:

FATAL EXCEPTION: main
                                                                    Process: com.buledon.volunteerapp, PID: 4787
                                                                    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setCompoundDrawablesWithIntrinsicBounds(android.graphics.drawable.Drawable, android.graphics.drawable.Drawable, android.graphics.drawable.Drawable, android.graphics.drawable.Drawable)' on a null object reference
                                                                        at com.buledon.volunteerapp.widget.CitySelectView$3.run(CitySelectView.java:130)
                                                                        at android.os.Handler.handleCallback(Handler.java:739)
                                                                        at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                        at android.os.Looper.loop(Looper.java:135)
                                                                        at android.app.ActivityThread.main(ActivityThread.java:5669)
                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                        at java.lang.reflect.Method.invoke(Method.java:372)
                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Paul Yang
  • 52
  • 8

1 Answers1

2

Also use mRightAdapter.notifyDataSetChanged. Also added values don't get reflected in listview immediately. Use mHandler.postDelayed and add a delay of few millisecond. You can check if getChild(0) is not null. If its null post the handler again.

A cleaner way would be to add this code in getView() method of Adapter class and check for index of the view being requested. If its 0 then execute your code. This way you will be doing your stuff at right place and right time.

chejaras
  • 862
  • 5
  • 10