ArrayList已初始化,但在尝试.add(string)方法时仍返回NullPointerException

时间:2014-11-23 20:20:11

标签: java android arraylist adapter

尝试对ArrayList使用add方法时遇到此错误。我可以看到很多人遇到同样的问题,但他们没有在添加元素之前初始化arraylist。但我想添加,并且,仍然,我要求控制台返回如果消息arraylist在方法之前为null,则返回false。

public class ShowTalkActivity extends Activity implements OnClickListener {

    private ListView listView;
    ArrayList<String> messages;
    ArrayAdapter<String> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_talk);

        Intent intent = getIntent();
        String selected = intent.getStringExtra("selected");
        setTitle(selected);

        listView = (ListView) findViewById(R.id.messagesList);
        messages = new ArrayList<String>();
        adapter = new ArrayAdapter<String>(this,R.layout.message_list_row, R.id.messagesList, messages);
        listView.setAdapter(adapter);

        ((Button) findViewById(R.id.sendMessage)).setOnClickListener(this);
    }

...

    @Override
    public void onClick(View view) {
        System.out.println(messages==null);
        messages.add("Anything");
        adapter.notifyDataSetChanged();
    }
}

的System.out.println(消息== NULL);打印错误。我还尝试在开始时初始化消息ArrayList,而不是仅仅声明。有谁知道发生了什么?谢谢!

更新

这是logcat跟踪:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:392)
        at android.widget.ArrayAdapter.getView(ArrayAdapter.java:362)
        at android.widget.AbsListView.obtainView(AbsListView.java:2344)
        at android.widget.ListView.makeAndAddView(ListView.java:1864)
        at android.widget.ListView.fillDown(ListView.java:698)
        at android.widget.ListView.fillFromTop(ListView.java:759)
        at android.widget.ListView.layoutChildren(ListView.java:1673)
        at android.widget.AbsListView.onLayout(AbsListView.java:2148)
        at android.view.View.layout(View.java:15596)
        at android.view.ViewGroup.layout(ViewGroup.java:4966)
        at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1076)
        at android.view.View.layout(View.java:15596)
        at android.view.ViewGroup.layout(ViewGroup.java:4966)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
        at android.view.View.layout(View.java:15596)
        at android.view.ViewGroup.layout(ViewGroup.java:4966)
        at com.android.internal.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:494)
        at android.view.View.layout(View.java:15596)
        at android.view.ViewGroup.layout(ViewGroup.java:4966)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
        at android.view.View.layout(View.java:15596)
        at android.view.ViewGroup.layout(ViewGroup.java:4966)
        at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2072)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1829)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1054)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5779)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
        at android.view.Choreographer.doCallbacks(Choreographer.java:580)
        at android.view.Choreographer.doFrame(Choreographer.java:550)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5221)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

3 个答案:

答案 0 :(得分:1)

MainActivity.java

package com.example.example;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

public class MainActivity extends Activity implements OnClickListener {

	private ListView listView;
	ArrayList<String> messages;
	ArrayAdapter<String> adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		setTitle("Setted title");

		listView = (ListView) findViewById(R.id.messagesList);
		messages = new ArrayList<String>();
		adapter = new ArrayAdapter(this, R.layout.message_list_row,
				R.id.messagesList, messages);

		listView.setAdapter(adapter);

		Button sendmessage = (Button) findViewById(R.id.sendMessage);
		sendmessage.setOnClickListener(this);

	}

	@Override
	public void onClick(View view) {
		System.out.println(messages == null);
		messages.add("Anything");
		adapter.notifyDataSetChanged();
	}
}

acitivity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ListView
        android:id="@+id/messagesList"
        android:layout_width="match_parent"
        android:layout_height="322dp" >
    </ListView>

    <Button
        android:id="@+id/sendMessage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />

</LinearLayout>

message_list_row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/messagesList"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

以上代码生成Result

答案 1 :(得分:0)

编辑:我完全错了。这句话错了: You cannot set an adapter with an empty ArrayList, even if u initialized it before. The adapter will find no value and throw the exception. 所以我的解决方案毫无用处。如果没用,我会在2天内将其删除。我之前注意到了哪个问题,但其他人已经回答了。 :) 编辑结束

您无法使用空ArrayList设置适配器,即使您之前已初始化它。适配器将找不到任何值并抛出异常。

试试这个:

public class ShowTalkActivity extends Activity implements OnClickListener {

private ListView listView;
ArrayList<String> messages;
ArrayAdapter<String> adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_show_talk);

    Intent intent = getIntent();
    String selected = intent.getStringExtra("selected");
    setTitle(selected);

    listView = (ListView) findViewById(R.id.messagesList);
    messages = new ArrayList<String>();
    //adapter = new ArrayAdapter<String>(this,R.layout.message_list_row, R.id.messagesList, messages);
    //listView.setAdapter(adapter);

    ((Button) findViewById(R.id.sendMessage)).setOnClickListener(this);
}

...

@Override
public void onClick(View view) {
    //System.out.println(messages==null);
    messages.add("Anything");
    if (adapter == null) {
      adapter = new ArrayAdapter<String>(this,R.layout.message_list_row, R.id.messagesList, messages);         
      listView.setAdapter(adapter);
    }
    else {
      adapter.addAll(messages);
      adapter.notifyDataSetChanged();
    }
}

希望我明白你的需要。

答案 2 :(得分:0)

查看logcat很明显,当它引用设置某些TextView或其他View对象时抛出空对象引用错误时,几乎可以肯定错误是View对象未正确设置。这是您在遇到这些错误时必须查看的地方。

此外,列表不必包含要设置为适配器的内容。 正如您在以下代码中看到的那样,
1)我创建了&#34; list_for_comm&#34;

的新实例

2)然后我将它设置为Adapter&#34; adapter_comm&#34;

3)然后我继续用空字符串填充列表。

4)然后,如果您希望在UI中实际看到列表更改,请通过&#34; notifyDataSetChanged&#34;

通知适配器

5)如果还没有笑容,请在脸上露出笑容。

public void initAllCommListStuff()
{
    lv_comm = (ListView_CommBar) findViewById(R.id.listView_with_comm_bar);
    lv_comm.setDivider(null);

    list_for_comm = new ArrayList<>(5);
    adapter_comm = new Adapter_CommBar(DisplayContactActivity.this, R.layout.comm_bar_layout_dc_portrait, list_for_comm);
    lv_comm.setAdapter(adapter_comm);

    for (int i=0; i<5; i++)
    {
        list_for_comm.add(new Adapter_GetSet_MovingBar(i, "", ""));
    }
    adapter_comm.notifyDataSetChanged();
}