使用ArrayLists时出现奇怪的NPE行为

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用ArrayLists时出现奇怪的NPE行为相关的知识,希望对你有一定的参考价值。

我有一个名为public static ArrayList<Integer>的3个hp,att & def数组列表,分别名为GlobalDataHolder.java。当我尝试从另一个名为ArrayLists的类中的addSelectedCardToGlobalUserBox方法中向那些MainScreenFragment.java添加一个Integer值时,我得到一个NPE,表明hp ArrayList为null,从而阻止我向其添加值。奇怪的是,这种异常只发生在我在物理设备而不是模拟器上运行应用程序时。有任何想法吗?

的ArrayList:

    // Holds each card's hp stats
public static ArrayList<Integer> hp = new ArrayList<>();

// Holds each card's att stats
public static ArrayList<Integer> att = new ArrayList<>();

// Holds each card's def stats
public static ArrayList<Integer> def = new ArrayList<>();

addSelectedCardToGlobalUserBox()方法:

    /**
 * Add the selected card's icon to the Global User Box
 * @param position Holds the selected card's position.
 * This is used to define where the icon should be placed in the grid &
 * which icon from the DataBase was selected
 */
private void addSelectedCardToGlobalUserBox(int position) {
    GlobalDataHolder.dataHolder.add(ImageAdapter.mThumbIds[position]);
    GlobalDataHolder.cardArts.add(CardInfoDatabase.cardArts[position]);
    GlobalDataHolder.cardNameAndDescription.add(CardInfoDatabase.cardNameAndDescription[position]);
    GlobalDataHolder.leaderSkills.add(CardInfoDatabase.leaderSkills[position]);
    GlobalDataHolder.superAttacksName.add(CardInfoDatabase.superAttacksName[position]);
    GlobalDataHolder.superAttacksDesc.add(CardInfoDatabase.superAttacksDesc[position]);
    GlobalDataHolder.passiveSkillsName.add(CardInfoDatabase.passiveSkillsName[position]);
    GlobalDataHolder.passiveSkillsDesc.add(CardInfoDatabase.passiveSkillsDesc[position]);
    GlobalDataHolder.hp.add(CardInfoDatabase.hp[position]);
    GlobalDataHolder.att.add(CardInfoDatabase.att[position]);
    GlobalDataHolder.def.add(CardInfoDatabase.def[position]);
}

MainScrenFragment.java类供参考:

public class MainScreenFragment extends Fragment {

// Main Grid View
GridView gridView;

public MainScreenFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_main_screen, container, false);

    gridView = view.findViewById(R.id.gridViewLayout);
    gridView.setAdapter(new ImageAdapter(getContext())); // used to set the contents of the GridView-in this case images-
    registerForContextMenu(gridView);

    // When an item from the GridView gets clicked
    gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // Create a new Intent...
            Intent intent = new Intent(getContext(),CardViewActivity.class);
            intent.putExtra("Card Index",position);
            intent.putExtra("GLB_CARD_INDEX", -1);
            intent.putExtra("SCREEN_WIDTH",1080);
            startActivity(intent);
        }
    });
    return view;
}

// Create a Context Menu when an item in the GridView is long-pressed
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    menu.setHeaderTitle("Card Options");
    //AdapterView.AdapterContextMenuInfo cmi = (AdapterView.AdapterContextMenuInfo) menuInfo;
    menu.add(1,v.getId(),0, "Add Card to GLB");
    menu.add(2,v.getId(),0,"Add Card to JP");
}

// When an item in the context menu gets selected, call a method
@Override
public boolean onContextItemSelected(MenuItem item) {

    // Get some extra info about the contextMenu
    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();

    int position = info.position; // clicked view's position

    if(item.getTitle().equals("Add Card to GLB")) {
        addCardMessage("Card added to GLB");
        addSelectedCardToGlobalUserBox(position);
    } else if (item.getTitle().equals("Add Card to JP")) {
        addCardMessage("Card added to JP");
        addSelectedCardToJPUserBox(position);
    } else
    {
        return false;
    }
    return false;
}

/**
 * Creates a snackbar message, telling the user which card was added to which box
 * @param text Defines into which User Box the card was added
 */
private void addCardMessage( String text) {
      final Snackbar snackbar = Snackbar.make(gridView, text ,Snackbar.LENGTH_LONG);

      snackbar.setAction("Dismiss", new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            snackbar.dismiss();
        }
    });
    snackbar.setActionTextColor(Color.MAGENTA);
    snackbar.show();
}

/**
 * Add the selected card's icon to the Global User Box
 * @param position Holds the selected card's position.
 * This is used to define where the icon should be placed in the grid &
 * which icon from the DataBase was selected
 */
private void addSelectedCardToGlobalUserBox(int position) {
    GlobalDataHolder.dataHolder.add(ImageAdapter.mThumbIds[position]);
    GlobalDataHolder.cardArts.add(CardInfoDatabase.cardArts[position]);
    GlobalDataHolder.cardNameAndDescription.add(CardInfoDatabase.cardNameAndDescription[position]);
    GlobalDataHolder.leaderSkills.add(CardInfoDatabase.leaderSkills[position]);
    GlobalDataHolder.superAttacksName.add(CardInfoDatabase.superAttacksName[position]);
    GlobalDataHolder.superAttacksDesc.add(CardInfoDatabase.superAttacksDesc[position]);
    GlobalDataHolder.passiveSkillsName.add(CardInfoDatabase.passiveSkillsName[position]);
    GlobalDataHolder.passiveSkillsDesc.add(CardInfoDatabase.passiveSkillsDesc[position]);
    GlobalDataHolder.hp.add(CardInfoDatabase.hp[position]);
    GlobalDataHolder.att.add(CardInfoDatabase.att[position]);
    GlobalDataHolder.def.add(CardInfoDatabase.def[position]);
}

/**
 * Add the selected card's icon to the JP User Box
 * @param position Holds the selected card's position.
 * This is used to define where the icon should be placed in the grid &
 * which icon from the DataBase was selected
 */
private void addSelectedCardToJPUserBox(int position) {
    JPDataHolder.dataHolder.add(ImageAdapter.mThumbIds[position]);
    JPDataHolder.cardArts.add(CardInfoDatabase.cardArts[position]);
    JPDataHolder.cardNameAndDescription.add(CardInfoDatabase.cardNameAndDescription[position]);
    JPDataHolder.leaderSkills.add(CardInfoDatabase.leaderSkills[position]);
    JPDataHolder.superAttacksName.add(CardInfoDatabase.superAttacksName[position]);
    JPDataHolder.superAttacksDesc.add(CardInfoDatabase.superAttacksDesc[position]);
    JPDataHolder.passiveSkillsName.add(CardInfoDatabase.passiveSkillsName[position]);
    JPDataHolder.passiveSkillsDesc.add(CardInfoDatabase.passiveSkillsDesc[position]);
    JPDataHolder.hp.add(CardInfoDatabase.hp[position]);
    JPDataHolder.att.add(CardInfoDatabase.att[position]);
    JPDataHolder.def.add(CardInfoDatabase.def[position]);
}

}

名称:

01-01 16:05:51.421 22357-22357 / com.dcv.spdesigns.dokkancards E / androidRuntime:FATAL EXCEPTION:main进程:com.dcv.spdesigns.dokkancards,PID:22357 java.lang.NullPointerException:尝试调用虚拟com.dcv.spdesigns上com.dcv.spdesigns.dokkancards.ui.MainScreenFragment.addSelectedCardToGlobalUserBox(MainScreenFragment.java:122)中空对象引用的方法'boolean java.util.ArrayList.add(java.lang.Object)' Android.support.v4.app.FragmentManagerImpl.dispatchContextItemSelected(FragmentManager.java)上的android.support.v4.app.Fragment.performContextItemSelected(Fragment.java:2502)中的.dokkancards.ui.MainScreenFragment.onContextItemSelected(MainScreenFragment.java:79) :android.support.v4.app.FragmentController.dispatchContextItemSelected(FragmentController.java:357)在android.support.v7.app的android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:377)的android.support.v4.app.FragmentController.dispatchContextItemSelected(339)。 android.support上的AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:195)。位于com.android.internal.policy.PhoneWindow $ PhoneWindowMenuCallback.onMenuItemSelected(PhoneWindow。)的android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:108)的v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:108)。 java:4020)com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:761)位于com.android的com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:157) .internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:904)位于com.android.internal.view.menu.MenuPopup的com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:894) .onItemClick(MenuPopup.java:128)位于android.widget.Ab上的android.widget.AdapterView.performItemClick(AdapterView.java:339),android.widget.AbsListView,$。 AbsListView.java:4184)在android.os.Handler.h的android.widget.AbsListView $ 13.run(AbsListView.java:6754) andleCallback(Handler.java:751)在Android.os.Handler.dispatchMessage(Handler.java:95)android.app.Looper.loop(Looper.java:154)android.app.ActivityThread.main(ActivityThread.java) :6776)位于com.android.internal.os.ZygoteInit.main的com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:1520)的java.lang.reflect.Method.invoke(Native Method) (ZygoteInit.java:1410)

答案

在代码中的某处,您必须分配这些变量null。尝试制作变量final并检查null的分配位置(编译失败将指示您指定null的位置)。

以上是关于使用ArrayLists时出现奇怪的NPE行为的主要内容,如果未能解决你的问题,请参考以下文章

使用 objc_getAssociatedObject() 时出现奇怪的 Swift 行为

使用静态/常量 ON 子句时出现奇怪的 MERGE 行为

使用 EclipseLink 在 Oracle 上执行查询时出现奇怪的行为

使用选项卡控制器时出现奇怪的滚动行为 - iOS

将 Excel 工作表导出到 PDF 文件时出现奇怪的 Powershell 行为

使用最新的 xcode/OSX 版本构建项目时出现奇怪的应用程序行为