gpt4 book ai didi

java - 为什么我在这里收到微调器的空引用错误?

转载 作者:行者123 更新时间:2023-12-01 16:45:52 25 4
gpt4 key购买 nike

我正在 android studio 中编程,这是我的代码 fragment :

public class settingsView extends Fragment {

public settingsView() {
}

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

final Spinner citySpinner = (Spinner) getActivity().findViewById(R.id.citySpinner);

FirebaseDatabase.getInstance().getReference("/movies/karnataka").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

ArrayList<String> cityList = new ArrayList<>();

for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
cityList.add(snapshot.getKey());
}

Log.d("firebasedata", cityList.toString());

ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getApplicationContext(), android.R.layout.simple_spinner_item, cityList );
adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
citySpinner.setAdapter(adapter);
}

@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});


return inflater.inflate(R.layout.settingsview, container, false);
}
}

我正在获取

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Spinner.setAdapter(android.widget.SpinnerAdapter) on a null object reference exception 

在行:

citySpinner.setAdapter(adapter)

最佳答案

您需要首先在 oncreateview 中填充包含 fragment View 的 xml 文件。

然后使用该 View 执行 findviewbyid:

view = inflater.inflate(R.layout.fragment_xml, container, false);
final Spinner citySpinner = (Spinner) view.findViewById(R.id.citySpinner);

关于java - 为什么我在这里收到微调器的空引用错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51104938/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com