setAdapter()nullpointerexception

时间:2016-08-18 06:50:35

标签: android listview android-arrayadapter

我的应用程序总是崩溃在" messagesList.setAdaper(适配器)"它说"无法启动活动ComponentInfo {com.ofekot.socialchat / com.ofekot.socialchat.ChatActivity}:java.lang.NullPointerException", 我无法理解导致问题的原因。

这是Java类:

package com.ofekot.socialchat;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;

import java.util.ArrayList;

public class ChatActivity extends AppCompatActivity {

    private ListView messagesList;
    private EditText messageBox;
    private ImageButton sendBtn;

    private ArrayList<ChatMessage> messages;
    private String usernameFrom;
    private String usernameTo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if(getSupportActionBar() != null) {
            Bundle extras = getIntent().getExtras();
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            if (extras != null) {
                getSupportActionBar().setTitle(extras.getString(Config.NICKNAME));
                usernameFrom = extras.getString(Config.USER_NAME_FROM);
                usernameTo = extras.getString(Config.USER_NAME_TO);
            }
        }
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
        initialize();
    }

    private void initialize() {
        final Manager manager = new Manager(this);
        messagesList = (ListView)findViewById(R.id.messagesList);
        sendBtn = (ImageButton)findViewById(R.id.sendBtn);
        messageBox = (EditText)findViewById(R.id.messageBox);
        sendBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String message = messageBox.getText().toString();
                if(!message.equals("")) {
                    messageBox.setText("");
                    manager.sendMessage(usernameFrom, message, usernameTo);
                }
            }
        });
        messagesList.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
        messages = manager.readFromLocalDatabase(usernameFrom, usernameTo);
        MessagesAdapter adapter = new MessagesAdapter(this, messages);
        messagesList.setAdapter(adapter);
    }
}

这是XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.ofekot.socialchat.ChatActivity"
    tools:showIn="@layout/activity_chat"
    android:background="@color/colorGrey">


    <ListView
        android:id="@+id/messagesList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:divider="@android:color/transparent"
        android:dividerHeight="5dp"
        android:listSelector="@android:color/transparent"
        android:cacheColorHint="@android:color/transparent">
    </ListView>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="3dp">

        <EditText
            android:id="@+id/messageBox"
            android:layout_width="220dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:layout_marginTop="2dp"
            android:layout_marginBottom="2dp"
            android:layout_marginStart="2dp"
            android:layout_marginLeft="2dp"
            android:padding="2dp"
            android:scrollbars="vertical"
            style="@style/EditTextStyle"/>
        <ImageButton
            android:id="@+id/sendBtn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_margin="2dp"
            android:src="@drawable/ic_arrow_back_24dp"
            style="@style/ButtonStyle"/>
    </LinearLayout>


</RelativeLayout>

这是日志:

08-18 09:58:05.745 12209-12209/com.ofekot.socialchat E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ofekot.socialchat, PID: 12209
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ofekot.socialchat/com.ofekot.socialchat.ChatActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2200)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2250)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1200)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5105)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:608)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.ofekot.socialchat.MessagesAdapter.getCount(MessagesAdapter.java:71)
at android.widget.ListView.setAdapter(ListView.java:480)
at com.ofekot.socialchat.ChatActivity.initialize(ChatActivity.java:66)
at com.ofekot.socialchat.ChatActivity.onCreate(ChatActivity.java:45)
at android.app.Activity.performCreate(Activity.java:5275)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2164)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2250) 
at android.app.ActivityThread.access$800(ActivityThread.java:139) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1200) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5105) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:608) 
at dalvik.system.NativeStart.main(Native Method) 

2 个答案:

答案 0 :(得分:2)

ArrayList<ChatMessage> messages一开始为空,因此它会在getCount()方法中抛出空指针异常。

将其更改为:

private ArrayList<ChatMessage> messages = new ArrayList<ChatMessage>()

或在创建适配器之前在代码中初始化它。

答案 1 :(得分:1)

无论@Misagh Emmamverdi发布了什么都是正确的。但是,如果你有一个自定义适配器,那么在getCount()中检查arraylist是否为null或者不是如下所示

MessageAdapter.java

Public Sub EnablePictures()
    Dim Enable As Boolean
    For Each row As DataGridViewRow In DataGridView1.Rows
        Enable = Convert.ToBoolean(row.Cells("Access").Value)
        Dim ctrl = Me.Controls(row.Cells("Control Name").Value)
        if ctrl IsNot Nothing Then
            ctrl.Enabled = Enable
        End If
    Next
End Sub

如果您使用相同的适配器显示多个活动,这是一种更安全的方法。