ListView.setAdapter Null 指针异常:而 adapter.getCount 显示所有记录,而 Listview 也不是 Null [duplicate]

ListView.setAdapter Null Pointer exception While adapter.getCount show all records and Listview is also not Null [duplicate]

提问人:Naseem Khan 提问时间:9/27/2019 最后编辑:ardiienNaseem Khan 更新时间:9/27/2019 访问量:117

问:

我有一个应用程序,它填充了自定义适配器和列表中的溢出菜单项。从 中调用自定义适配器,并调用一个实现 .在其单击功能中,我想淡化除单击项之外的所有列表项。ListViewMainActivityOnAlbumOverflowSelectedListeneronClickListner

当我尝试调用它时,它会抛出空指针异常。所以下面是代码片段:myListview.seteAdapter(Cus_aptr)MainActivity->CustomAdapter-> OnAlbumOverflowSelectedListener->onCLick

1. main activity
package com.example.shahnaii;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;

import java.util.ArrayList;

public class ScrollingActivity extends AppCompatActivity {
    ArrayList<DataModel> dataModels;
    ListView listView;
    private static CustomAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scrolling);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Open new window to add entries", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        listView = findViewById(R.id.list_myContent);
        dataModels= new ArrayList<>();

        dataModels.add(new DataModel("Apple Pie", "Android 1.0", "1","September 23, 2008"));
        dataModels.add(new DataModel("Banana Bread", "Android 1.1", "2","February 9, 2009"));
        dataModels.add(new DataModel("Cupcake", "Android 1.5", "3","April 27, 2009"));
        dataModels.add(new DataModel("Donut","Android 1.6","4","September 15, 2009"));
        dataModels.add(new DataModel("Eclair", "Android 2.0", "5","October 26, 2009"));
        dataModels.add(new DataModel("Froyo", "Android 2.2", "8","May 20, 2010"));
        dataModels.add(new DataModel("Gingerbread", "Android 2.3", "9","December 6, 2010"));
        dataModels.add(new DataModel("Honeycomb","Android 3.0","11","February 22, 2011"));
        dataModels.add(new DataModel("Ice Cream Sandwich", "Android 4.0", "14","October 18, 2011"));
        dataModels.add(new DataModel("Jelly Bean", "Android 4.2", "16","July 9, 2012"));
        dataModels.add(new DataModel("Kitkat", "Android 4.4", "19","October 31, 2013"));
        dataModels.add(new DataModel("Lollipop","Android 5.0","21","November 12, 2014"));
        dataModels.add(new DataModel("Marshmallow", "Android 6.0", "23","October 5, 2015"));

        //adapter= new CustomAdapter(dataModels,getApplicationContext());
        adapter= new CustomAdapter(dataModels,this);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                DataModel dataModel= dataModels.get(position);

                Snackbar.make(view, dataModel.getName()+"\n"+dataModel.getType()+" API: "+dataModel.getVersion_number(), Snackbar.LENGTH_LONG)
                        .setAction("No action", null).show();
            }
        });


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_scrolling, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
          switch (id)
        {
            case R.id.action_Menu1: {
                Toast.makeText(getApplicationContext(),"Menu 1 Selected",Toast.LENGTH_SHORT).show();
            }


        }

        return super.onOptionsItemSelected(item);
    }
}

2. custom Adapter
package com.example.shahnaii;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.TextView;

import com.google.android.material.snackbar.Snackbar;

import java.lang.reflect.Field;
import java.util.ArrayList;



public class CustomAdapter extends ArrayAdapter<DataModel> implements View.OnClickListener{


    Context mContext;
    ArrayList<DataModel> mData;

// View lookup cache
private static class ViewHolder {
    TextView txtName;
    TextView txtType;
    TextView txtVersion;
    ImageView info;
    ImageView overFlow;
    }

    public CustomAdapter(ArrayList<DataModel> data, Context context) {
        super(context, R.layout.row_item, data);
        this.mContext=context;
        this.mData=data;
         }

    @Override
    public void onClick(View v) {

        int position=(Integer) v.getTag();
        Object object= getItem(position);
        DataModel dataModel=(DataModel)object;

        switch (v.getId())
        {
            case R.id.item_info:
                Snackbar.make(v, "Release date " +dataModel.getFeature(), Snackbar.LENGTH_LONG)
                        .setAction("No action", null).show();
                break;

        }


    }

    private int lastPosition = -1;

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Get the data item for this position
        DataModel dataModel = getItem(position);
        // Check if an existing view is being reused, otherwise inflate the view
        ViewHolder viewHolder; // view lookup cache stored in tag

        final View result;

        if (convertView == null) {

            viewHolder = new ViewHolder();
            LayoutInflater inflater = LayoutInflater.from(getContext());
            convertView = inflater.inflate(R.layout.row_item, parent, false);
            viewHolder.txtName = (TextView) convertView.findViewById(R.id.name);
            viewHolder.txtType = (TextView) convertView.findViewById(R.id.type);
            viewHolder.txtVersion = (TextView) convertView.findViewById(R.id.version_number);
            viewHolder.info = (ImageView) convertView.findViewById(R.id.item_info);
            viewHolder.overFlow = (ImageView) convertView.findViewById(R.id.album_overflow);
            //viewHolder.overFlow.setOnClickListener(new OnAlbumOverflowSelectedListener(mContext,position));
                    result=convertView;

            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
            result=convertView;
        }

        viewHolder.txtName.setText(dataModel.getName());
        viewHolder.txtType.setText(dataModel.getType());
        viewHolder.txtVersion.setText(dataModel.getVersion_number());
        viewHolder.info.setOnClickListener(this);
        viewHolder.info.setTag(position);
        viewHolder.overFlow.setOnClickListener(new OnAlbumOverflowSelectedListener(mContext,mData,position));
        //viewHolder.overFlow.setTag(position);
        // Return the completed view to render on screen
        return result;
    }
}

3. OnAlbumOverflowSelectedListner

package com.example.shahnaii;

import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.PopupMenu;

import com.google.android.material.snackbar.Snackbar;

import java.lang.reflect.Field;
import java.util.ArrayList;

public class OnAlbumOverflowSelectedListener  implements View.OnClickListener  {
    private ListView mListView;
    private ArrayAdapter mArrAdapter;
    private ArrayList uData;
    private final AlphaAnimation mFadeOut = new AlphaAnimation(1.0f, 0.3f);
    private final AlphaAnimation mFadeIn = new AlphaAnimation(0.3f, 1.0f);
    //private MediaStore.Audio.Albums mAlbum;
    private Context mContext;
    private int mPosition;
    private int mAlbum;
     public OnAlbumOverflowSelectedListener(Context con,ArrayList<?>data,int pos)
     {
         mContext=con;
         mPosition = pos;
         this.uData = data;
     }

    @Override
    public void onClick(View v) {
        // This is an android.support.v7.widget.PopupMenu;

        PopupMenu popupMenu = new PopupMenu(mContext, v) {
        };

        popupMenu.inflate(R.menu.menu);
        // Force icons to show
        Object menuHelper;
        Class[] argTypes;
        try {
            Field fMenuHelper = PopupMenu.class.getDeclaredField("mPopup");
            fMenuHelper.setAccessible(true);
            menuHelper = fMenuHelper.get(popupMenu);
            argTypes = new Class[] { boolean.class };
            menuHelper.getClass().getDeclaredMethod("setForceShowIcon",
                    argTypes).invoke(menuHelper, true);
        } catch (Exception e) {
            popupMenu.show();
            return;
        }
        // Force icons to show ends here
        popupMenu.show();

        /*fading process begins-*/
        // Dim out all the other list items if they exist
        CustomAdapter cust_adptr = new CustomAdapter(this.uData,this.mContext);
         Object obj = cust_adptr.getItem(mPosition);
        DataModel dm = (DataModel)obj;

        Snackbar.make(v, "Release date "+cust_adptr.getItem(mPosition).getFeature(), Snackbar.LENGTH_LONG)
                .setAction("No action", null).show();

        mListView = v.findViewById(R.id.list_myContent);
        mListView.setAdapter(cust_adptr);

        int firstPos = mListView.getFirstVisiblePosition() - mListView.getHeaderViewsCount();
        final int ourPos = mArrAdapter.getPosition(mPosition) - firstPos;
        int count = mListView.getChildCount();
        for (int i = 0; i <= count; i++) {
            if (i == ourPos) {
                continue;
            }

            final View child = mListView.getChildAt(i);
            if (child != null) {
                child.clearAnimation();
                child.startAnimation(mFadeOut);
            }
        }

        // Make sure to bring them back to normal after the menu is gone
        popupMenu.setOnDismissListener(new PopupMenu.OnDismissListener() {
            @Override
            public void onDismiss(PopupMenu popupMenu) {
                int count = mListView.getChildCount();
                for (int i = 0; i <= count; i++) {
                    if (i == ourPos) {
                        continue;
                    }

                    final View v = mListView.getChildAt(i);
                    if (v != null) {
                        v.clearAnimation();
                        v.startAnimation(mFadeIn);
                    }
                }
            }
        });
        /*fading process ends*/

    }
}


OnAlbumOverflowSelectedListener class
onlcick method()
{
....

CustomAdapter cust_adptr = new CustomAdapter(this.uData,this.mContext);
         Object obj = cust_adptr.getItem(mPosition);
        DataModel dm = (DataModel)obj;

        Snackbar.make(v, "Release date "+cust_adptr.getItem(mPosition).getFeature(), Snackbar.LENGTH_LONG)
                .setAction("No action", null).show();

        mListView = v.findViewById(R.id.list_myContent);
        mListView.setAdapter(cust_adptr); this code throw null pointer
Android ListView NullPointerException 自定义适配器

评论

0赞 ardiien 9/27/2019
请添加错误堆栈并格式化您的代码,尤其是在最后需要帮助时。stackoverflow.com/help/how-to-ask

答:

1赞 Subham Naik 9/27/2019 #1

检查它是否activity_scrolling.xml不包含 ID 为 R.id.list_myContent 的 ListView。
你也可以发布错误日志吗?

评论

0赞 Naseem Khan 9/27/2019
其他xml文件中没有R.id.list_myContent,下面是错误代码2019-09-27 15:35:17.090 11129-11129/com.example.shahnaii E/AndroidRuntime:致命异常:主进程:com.example.shahnaii,PID:11129 java.lang.NullPointerException:尝试在 com.example.shahnaii.OnAlbumOverflowSelectedListener.onClick(OnAlbumOverflowSelectedListener.java:69) 的空对象引用上调用虚拟方法“void android.widget.ListView.setAdapter(android.widget.ListAdapter)”android.view.View.performClick(View.java:6310) 位于和
0赞 Arvind Patil 9/27/2019 #2
  1. 尝试查找 ID。在主要情况下,如果您错过了声明 id 并在该视图或按钮上实现任何操作,您将得到NullPointerException

  2. 有时,如果您将任何从后端到“文本”视图或“按钮图像”视图的值设置为null,那么您还将获得.NullPointerException

  3. 或者你可以把你的代码放在try-catch中以避免崩溃