【问题标题】:Array Adapter is null after initialized (wrong layout file)初始化后数组适配器为空(布局文件错误)
【发布时间】:2020-11-26 00:13:48
【问题描述】:

我的应用总是因为一个愚蠢的原因而崩溃!我环顾四周,有类似问题的用户正在使用片段,而我正在使用活动。我在 on create 方法中的代码如下。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    setContentView(R.layout.activity_select_contact);

    setResult(Activity.RESULT_CANCELED);
    ArrayAdapter<String> mPairedDevicesArrayAdapter = new ArrayAdapter<>(getApplicationContext(), R.layout.device_name);

    ListView mPairedListView = findViewById(R.id.paired_devices);
    mPairedListView.setAdapter(mPairedDevicesArrayAdapter);
    mPairedListView.setOnItemClickListener(mDeviceClickListener);

    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter.getBondedDevices();

    if (mPairedDevices.size() > 0) {
        /* List of all paired devices */
        findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
        for (BluetoothDevice mDevice : mPairedDevices) {
            mPairedDevicesArrayAdapter.add(mDevice.getName() + "\n" + mDevice.getAddress());
        }
    } else {
        /* No paired device */
        String mNoDevices = "None Paired";
   

错误如下,

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void

android.widget.ListView.setAdapter(android.widget.ListAdapter)' 空对象引用 在 ca.edgarwideman.taxibuddy.ConnectPrinter.onCreate(ConnectPrinter.java:39)

第 39 行(发生错误的地方)就是这个,

mPairedListView.setAdapter(mPairedDevicesArrayAdapter);

我知道了????,答案在下面……

【问题讨论】:

  • 也就是说您的ListView 为空。你能包括你的activity_select_contact.xml 布局文件吗?
  • 一会儿就好了
  • 该死,那是我的错误,我加载了错误的 XML,哇,我的脑袋确实在沙子里!还是要谢谢你的帮助!猜猜这就是这些论坛的用途!干杯!

标签: java android listview nullpointerexception android-arrayadapter


【解决方案1】:

知道了!而且我几乎不好意思承认...? 始终确保您的 OnCreate 启动正确的布局文件!

setContentView(R.layout.activity_select_contact);

应该是

setContentView(R.layout.activity_connect_printer);

谢谢你们帮助我! 感谢@ianhanniballake

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-12
    • 1970-01-01
    • 2015-08-05
    • 2020-12-11
    • 1970-01-01
    相关资源
    最近更新 更多