错误:java.lang.NullPointerException:尝试在空对象引用上调用接口方法“int java.util.List.size()”
Posted
技术标签:
【中文标题】错误:java.lang.NullPointerException:尝试在空对象引用上调用接口方法“int java.util.List.size()”【英文标题】:Error: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference 【发布时间】:2020-08-25 01:15:29 【问题描述】:当我在 androidStudio 中运行我的应用程序时出现以下异常:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.leftover, PID: 5379
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:389)
at com.baoyz.swipemenulistview.SwipeMenuAdapter.getCount(SwipeMenuAdapter.java:32)
at android.widget.ListView.setAdapter(ListView.java:581)
at com.baoyz.swipemenulistview.SwipeMenuListView.setAdapter(SwipeMenuListView.java:65)
at com.example.leftover.StorageFragment.onCreateView(StorageFragment.java:52)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2600)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:881)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:439)
at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2079)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1869)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727)
at androidx.fragment.app.FragmentManagerImpl.dispatchStateChange(FragmentManagerImpl.java:2663)
at androidx.fragment.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManagerImpl.java:2613)
at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:246)
at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:542)
at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:201)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1435)
at android.app.Activity.performStart(Activity.java:8013)
at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3366)
at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:221)
at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2044)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7476)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:939)
这是我工作的片段:
public class StorageFragment extends Fragment
private static final String TAG = "StorageFragment";
private User user;
private Button addButton;
private AutoCompleteTextView autoEditText;
private SwipeMenuListView listView;
private ArrayList<String> list;
private ArrayAdapter listAdapter;
private ArrayAdapter<String> autoCompleteAdapter;
private static final String[] LEBENSMITTEL = new String[]"Apfel", "Ananas", "Aubergine", "Alkohol", "Artischocke", "Aloe Vera";
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
View v = inflater.inflate(R.layout.fragment_storage, container, false);
addButton = (Button) v.findViewById(R.id.buttonAddToStorage);
autoEditText = (AutoCompleteTextView) v.findViewById(R.id.search_bar);
listView = (SwipeMenuListView) v.findViewById(R.id.listView);
list = FileHelper.readData(getActivity());
listAdapter = new ArrayAdapter (getActivity(), android.R.layout.simple_list_item_1, list);
listView.setAdapter(listAdapter);
addButton.setOnClickListener((View.OnClickListener) this);
autoCompleteAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, LEBENSMITTEL);
autoEditText.setAdapter(autoCompleteAdapter);
/**
* Swipe-Menu with Add- and Delete-Button
*/
SwipeMenuCreator creator = new SwipeMenuCreator()
@Override
public void create(SwipeMenu menu)
// Add-Item
SwipeMenuItem editItem = new SwipeMenuItem(getActivity().getApplicationContext());
editItem.setBackground(new ColorDrawable(Color.rgb(0xC9, 0xC9, 0xCE)));
editItem.setWidth(170);
editItem.setIcon(R.drawable.ic_storage_add_24dp);
menu.addMenuItem(editItem);
// Delete-Item
SwipeMenuItem deleteItem = new SwipeMenuItem(getActivity().getApplicationContext());
deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9, 0x3F, 0x25)));
deleteItem.setWidth(170);
deleteItem.setIcon(R.drawable.ic_storage_delete_24dp);
menu.addMenuItem(deleteItem);
;
listView.setMenuCreator(creator);
listView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener()
@Override
public boolean onMenuItemClick(int position, SwipeMenu menu, int index)
switch (index)
case 0: //add
showMessageDialog();
break;
case 1: //delete
//nothing happens here
Log.d(TAG, "onMenuItemClick: clicked item " + index);
break;
// false : close the menu; true : not close the menu
return false;
);
return v;
public void setUser(User user)
this.user = user;
/**
* Function for Add-Button
*/
public void onClick(View v)
switch(v.getId())
case R.id.buttonAddToStorage:
String itemEntered = autoEditText.getText().toString();
listAdapter.add(itemEntered);
autoEditText.setText("");
FileHelper.writeData(list, getActivity());
Toast.makeText(getActivity(), "Lebensmittel hinzugefügt", Toast.LENGTH_SHORT).show();
break;
/**
* Method for Message Alert Dialog
*/
private void showMessageDialog()
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.AlertDialogTheme);
View v = null;
v = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_storage_layout_add_dialog, (ConstraintLayout) v.findViewById(R.id.layoutDialogContainer));
builder.setView(v);
((TextView) v.findViewById(R.id.textTitle)).setText(getResources().getString(R.string.dialog_message_title));
((TextView) v.findViewById(R.id.textMessage)).setText(getResources().getString(R.string.dialog_message));
((Button) v.findViewById(R.id.buttonHoldItem)).setText(getResources().getString(R.string.im_Lager_halten));
((Button) v.findViewById(R.id.buttonDeleteItem)).setText(getResources().getString(R.string.aus_Lager_entfernen));
final AlertDialog alertDialog = builder.create();
v.findViewById(R.id.buttonHoldItem).setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
alertDialog.dismiss();
Toast.makeText(getActivity(), "Ja", Toast.LENGTH_SHORT).show();
);
v.findViewById(R.id.buttonDeleteItem).setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
alertDialog.dismiss();
Toast.makeText(getActivity(), "Nein", Toast.LENGTH_SHORT).show();
);
if(alertDialog.getWindow() != null)
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));
alertDialog.show();
错误出在片段中,但我不确定。当我尝试打开它时,这个错误会导致我的应用程序崩溃。
编辑:
我调试了onCreateView()
。
变量addButton, autoEditText, listView, list, listAdapter
和autoCompleteAdapter
都为空。
但我就是不明白,请原谅我的失明,但是我在哪里可以更改这些不再为空。我以为我初始化了它们...... :(
请帮忙。
(我知道这段代码中还有其他一些错误,但现在我需要帮助)
【问题讨论】:
您是否尝试过在片段内的onCreateView
方法中使用调试器一次执行一行?在某个时刻你调用listView
对象上的setAdapter
方法,你应该检查参数是否正确。
调试并检查您的 listAdapter 是否为空?
这能回答你的问题吗? What is a NullPointerException, and how do I fix it?
我调试并编辑了我的帖子!
您在ArrayAdapter
构造函数调用中传递了一个空List
,这意味着FileHelper.readData(getActivity())
返回空。这就是我们所能告诉你的一切,从给出的内容。
【参考方案1】:
也许您忘记初始化 FileHelper?
FileHelper fileHelper=new FileHelper(); fileHelper.readData(getActivity());
【讨论】:
以上是关于错误:java.lang.NullPointerException:尝试在空对象引用上调用接口方法“int java.util.List.size()”的主要内容,如果未能解决你的问题,请参考以下文章
Sqoop - 尝试连接到 Oracle DB 服务器时出现 java.lang.NullPointerException
远程服务器返回错误: 404错误远程服务器返回错误:500错误 HttpWebResponse远程服务器返回错误:(404500) 错误。
Pig 安装错误:错误 pig.Main:错误 2998:未处理的内部错误