Android : getting NullPointerException for ImageView imag = (ImageView) findViewById(R.id.image)

ⅰ亾dé卋堺 提交于 2019-11-29 17:04:20

In short: You should write a ListAdapter which draws the views in the list. You seem to use findViewById() on the wrong view/context (on the screen3 xml layout). An example containing a ListAdapter is available at the android developer site.

The getView() method should basically look something like this:

public View getView(int position, View convertView, ViewGroup parent) {
    View v = convertView;
    if (convertView == null) {
        v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row, null);
    }
    h = tasks.get(i);
    if(h.get("taskStatus").trim().equals("1")){
        imag = (ImageView) v.findViewById(R.id.image);
        imag.setImageResource(R.drawable.done);
    } else { 
        // ...
    }
    return v;
}

check whether the resource which your laoding is available in your res folder or not.

It seems that you haven't specified android:id="@+id/image" in the imageview inside your layout

Edit: I think the problem is you are using findViewById before the ListView in your ListActivity contains your custom_row which is who has the ImageView.

Try doing setListAdapter before populateList()

populateList() runs before the ListView is rendered to the screen, so the custom_row_screen3 doesn't exist in the Activity.

You could subclass SimpleAdapter and override getView() or setViewImage(), but I often find it simpler to anonymously implement a SimpleAdapter.ViewBinder and assign it with SimpleAdapter#setViewBinder().

In the ViewBinder, return false if the View that's passed in isn't an ImageView. If it is, you can use the map of data (passed in as an Object) to check the value of the "taskStatus" key.

Make sure to do this before calling setListAdapter().

adapter.setViewBinder(new SimpleAdapter.ViewBinder () {
  @Override
  boolean setViewValue(View view, Object data, String textRepresentation) {
    if (!(view instanceof ImageView)) return false;

    String taskStatus = ((Map<String, String>) data).get("taskStatus").trim();
    ((ImageView) view).setImageResource(taskStatus.equals("1") ? R.drawable.done :
                                                               R.drawable.not);
  }
});

Thanks all of you You all all pointed me in right direction that my imageview is not pointing to my adapter I followed the steps as in http://devblogs.net/2011/01/04/custom-listview-with-image-using-simpleadapter/ and it was working!!! just needed to put my image in hashmap... I was banging my head to the wall!!!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!