ListView.setAdapter Null Pointer exception 虽然 adapter.getCount 显示所有记录并且 Listview 也不是 Null [重复]

Posted

技术标签:

【中文标题】ListView.setAdapter Null Pointer exception 虽然 adapter.getCount 显示所有记录并且 Listview 也不是 Null [重复]【英文标题】:ListView.setAdapter Null Pointer exception While adapter.getCount show all records and Listview is also not Null [duplicate] 【发布时间】:2020-01-27 11:22:29 【问题描述】:

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

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

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

【问题讨论】:

请添加错误堆栈并格式化您的代码,尤其是在您需要帮助的最后。 ***.com/help/how-to-ask 【参考方案1】:

检查 activity_scrolling.xml 可能不包含 ID 为 R.id.list_myContent 的 ListView。 你能把错误日志也贴出来吗?

【讨论】:

没有 R.id.list_myContent 在其他 xml 文件中,以下是错误代码 2019-09-27 15:35:17.090 11129-11129/com.example.shahnaii E/AndroidRuntime: FATAL EXCEPTION:主进程:com.example.shahnaii,PID:11129 java.lang.NullPointerException:尝试在 com.example 的空对象引用上调用虚拟方法 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)'。 shahnaii.OnAlbumOverflowSelectedListener.onClick(OnAlbumOverflowSelectedListener.java:69) at android.view.View.performClick(View.java:6310) at and【参考方案2】:

    尝试查找 id。在主要情况下,如果您错过声明 id 并对该视图或按钮执行任何操作,您将收到 NullPointerException

    有时,如果您将任何从后端变为空的值设置为文本视图或按钮图像视图,那么您也会得到NullPointerException

    或者您可以将代码放入 try-catch 以避免崩溃

【讨论】:

以上是关于ListView.setAdapter Null Pointer exception 虽然 adapter.getCount 显示所有记录并且 Listview 也不是 Null [重复]的主要内容,如果未能解决你的问题,请参考以下文章

Android:尝试在空对象引用上调用虚拟方法“void android.widget.ListView.setAdapter(android.widget.ListAdapter)”

Android ListView清除

在 customadapter 中设置 setAdapter() 的空指针

求助,如何在listview里addheadview-Android开发问答

复杂listview学习笔记

convertview listview 适配器 EditText 混淆