空指针异常错误与ArrayList.add Java

huangapple 未分类评论44阅读模式
英文:

Null Pointer Exception Error With Arraylist.add Java

问题

我正在尝试创建一个显示对象列表的活动在一个卡片中以RecyclerView列表的形式显示主活动中的列表由第二个活动中的EditText设置的值组成我已经把所有东西都搞定了但是当我从第二个活动获取意图时我遇到了这个错误而且即使在使用虚拟数据时也会出现错误这在之前是没有的

    java.lang.NullPointerException尝试在空对象引用上调用虚拟方法'void android.widget.TextView.setText(java.lang.CharSequence)'
    位于 jacob.fragile.contactlist.ContactsAdapter$ViewHolder.bindTo(ContactsAdapter.java:69)
    在 jacob.fragile.contactlist.ContactsAdapter.onBindViewHolder(ContactsAdapter.java:43)
    在 jacob.fragile.contactlist.ContactsAdapter.onBindViewHolder(ContactsAdapter.java:19)

因为我几天没有碰过Contacts适配器了并且之前它是正常工作的所以我认为那里没有问题这是我的主活动

public class MainActivity extends AppCompatActivity {
    // ...(省略其他代码)

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mRecyclerView = findViewById(R.id.recyclerView);

        mContacts = new ArrayList<>();

        mAdapter = new ContactsAdapter(this, mContacts);
        mRecyclerView.setAdapter(mAdapter);

        // 获取数据。
        initializeData();

        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
    }

    private void initializeData() {
        // ...(省略部分代码)

        nameList.add("nameValue");
        ageList.add("ageValue");
        colorList.add("colorValue");

        // 获取列表数据。
        String[] names = nameList.toArray(new String[nameList.size()]);
        String[] age = ageList.toArray(new String[ageList.size()]);
        String[] color = colorList.toArray(new String[colorList.size()]);
        TypedArray imageResources = getResources().obtainTypedArray(R.array.images);
        
        mContacts.clear();

        for (int i = 0; i < names.length; i++) {
            mContacts.add(new Contacts(names[i], age[i], color[i], imageResources.getResourceId(i, 0)));
        }

        mAdapter.notifyDataSetChanged();
        imageResources.recycle();
    }

    public void fabClick(View view) {
        Intent intent = new Intent(this, AddContact.class);
        startActivity(intent);
    }
}
public class ContactsAdapter extends RecyclerView.Adapter<ContactsAdapter.ViewHolder> {
    // ...(省略其他代码)

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Log.d(TAG, "On viewHolder: called");
        Contacts contacts = mContacts.get(position);

        holder.bindTo(contacts);
    }

    // ...(省略其他代码)

    public class ViewHolder extends RecyclerView.ViewHolder {
        // ...(省略其他代码)

        void bindTo(Contacts contacts) {
            name.setText(contacts.getName());
            age.setText(contacts.getAge());
            color.setText(contacts.getColor());

            Glide.with(mContext).load(contacts.getImageResource()).into(imageView);
        }
    }
}

最后,这是list_item,其中的TextView在第二个活动中将其转换为字符串,因此使用TextView是有效的。

<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="8dp">

    <RelativeLayout
        android:id="@+id/relativeLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/contact_image"
            android:layout_width="96dp"
            android:layout_height="96dp" />

        <TextView
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_toRightOf="@+id/contact_image"
            android:padding="8dp"
            android:text="@string/placeholder_name" />

        <TextView
            android:id="@+id/age"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/name"
            android:layout_toRightOf="@+id/contact_image"
            android:padding="8dp"
            android:text="@string/placeholder_number"
            android:textColor="?android:textColorSecondary" />

        <TextView
            android:id="@+id/color"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/age"
            android:layout_toRightOf="@+id/contact_image"
            android:padding="8dp"
            android:text="@string/placeholder_color"
            android:textColor="?android:textColorSecondary" />

    </RelativeLayout>
</androidx.cardview.widget.CardView>

我不知道为什么突然出现了问题。请帮忙看看。谢谢。

英文:

I'm trying to make an activity that displays a list of objects in a card, in a recyclerview list. The list in the main activity takes values set by an EditText in a second activity. I got everything working fine, but when I got the intent from the second activity, I got this error, and I get the error even when working with dummy data, which I didn't before.

    java.lang.NullPointerException: Attempt to invoke virtual method &#39;void android.widget.TextView.setText(java.lang.CharSequence)&#39; on a null object reference
    at jacob.fragile.contactlist.ContactsAdapter$ViewHolder.bindTo(ContactsAdapter.java:69)
    at jacob.fragile.contactlist.ContactsAdapter.onBindViewHolder(ContactsAdapter.java:43)
    at jacob.fragile.contactlist.ContactsAdapter.onBindViewHolder(ContactsAdapter.java:19)

As I haven't touched the Contacts Adapter in several days, and it was working before, I don't think there is an issue there. This is my main activity.

public class MainActivity extends AppCompatActivity {

ArrayList&lt;Contacts&gt; mContacts;
private RecyclerView mRecyclerView;
private ContactsAdapter mAdapter;

//Declare lists to be filled with Data from Add Contact Activity
public static ArrayList&lt;String&gt; nameList = new ArrayList&lt;&gt;();
public static ArrayList&lt;String&gt; ageList = new ArrayList&lt;&gt;();
public static ArrayList&lt;String&gt; colorList = new ArrayList&lt;&gt;();


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mRecyclerView = findViewById(R.id.recyclerView);

    mContacts = new ArrayList&lt;&gt;();

    mAdapter = new ContactsAdapter(this, mContacts);
    mRecyclerView.setAdapter(mAdapter);

    // Get the data.
    initializeData();

    mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
}

private void initializeData() {

    //Listen for the intent
    /*Intent intent = getIntent();
    String nameValue = intent.getStringExtra(AddContact.NAME_MESSAGE);
    String ageValue = intent.getStringExtra(AddContact.AGE_MESSAGE);
    String colorValue = intent.getStringExtra(AddContact.COLOR_MESSAGE);*/

    nameList.add(&quot;nameValue&quot;);
    ageList.add(&quot;ageValue&quot;);
    colorList.add(&quot;colorValue&quot;);

    // Get the data from the lists.
    String[] names = nameList.toArray(new String[nameList.size()]);
    String[] age = ageList.toArray(new String[ageList.size()]);
    String[] color = colorList.toArray(new String[colorList.size()]);
    TypedArray imageResources =
                getResources().obtainTypedArray(R.array.images);
        // Clear the existing data (to avoid duplication).
        mContacts.clear();

        // Create the ArrayList of contacts  with names and
        // ages.
        for(int i=0;i&lt;names.length;i++){
            mContacts.add(new Contacts(names[i],age[i], color[i], imageResources.getResourceId(i, 0)));
        }

        // Notify the adapter of the change.
        mAdapter.notifyDataSetChanged();
        //Recycle the typed array
        imageResources.recycle();

    }

public void fabClick(View view) {
    Intent intent = new Intent(this, AddContact.class);
    startActivity(intent);
}

}

Here's my ContactAdapter.java, though that isn't the actual issue

public class ContactsAdapter extends RecyclerView.Adapter&lt;ContactsAdapter.ViewHolder&gt; {

public static final String TAG = &quot;RecyclerViewAdapter&quot;;

private ArrayList&lt;Contacts&gt; mContacts;
private Context mContext;

public ContactsAdapter(Context context, ArrayList&lt;Contacts&gt; contacts) {
    this.mContacts = contacts;
    this.mContext = context;
}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    return new ViewHolder(LayoutInflater.from(mContext).
            inflate(R.layout.list_item, parent, false));
}

@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
Log.d(TAG,&quot;On viewHolder: called&quot;);
Contacts contacts = mContacts.get(position);

holder.bindTo(contacts);
}

@Override
public int getItemCount() {return mContacts.size();}

public class ViewHolder extends RecyclerView.ViewHolder{

    ImageView imageView;
    TextView name;
    TextView age;
    TextView color;

    public ViewHolder(@NonNull View itemView) {
        super(itemView);
        imageView = itemView.findViewById(R.id.contact_image);
        name = itemView.findViewById(R.id.name);
        age = itemView.findViewById(R.id.age);
        color = itemView.findViewById(R.id.colorSpinner);
    }

    void bindTo(Contacts contacts) {
        //Set the text views
        name.setText(contacts.getName());
        age.setText(contacts.getAge());
        color.setText(contacts.getColor());
        //Load in the images
        Glide.with(mContext).load(contacts.getImageResource()).into(imageView);

    }
}

}

Finally, here's the list_item that the Textviews are setting to. colorSpinner is a spinner in the second activity that gets converted to a string, so using a textview is valid

&lt;androidx.cardview.widget.CardView xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;wrap_content&quot;
android:layout_margin=&quot;8dp&quot;&gt;

&lt;RelativeLayout
    android:id=&quot;@+id/relativeLayout&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;wrap_content&quot;&gt;

    &lt;ImageView
        android:id=&quot;@+id/contact_image&quot;
        android:layout_width=&quot;96dp&quot;
        android:layout_height=&quot;96dp&quot; /&gt;

    &lt;TextView
        android:id=&quot;@+id/name&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:layout_alignParentTop=&quot;true&quot;
        android:layout_toRightOf=&quot;@+id/contact_image&quot;
        android:padding=&quot;8dp&quot;
        android:text=&quot;@string/placeholder_name&quot; /&gt;

    &lt;TextView
        android:id=&quot;@+id/age&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:layout_below=&quot;@id/name&quot;
        android:layout_toRightOf=&quot;@+id/contact_image&quot;
        android:padding=&quot;8dp&quot;
        android:text=&quot;@string/placeholder_number&quot;
        android:textColor=&quot;?android:textColorSecondary&quot; /&gt;

    &lt;TextView
        android:id=&quot;@+id/color&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:layout_below=&quot;@id/age&quot;
        android:layout_toRightOf=&quot;@+id/contact_image&quot;
        android:padding=&quot;8dp&quot;
        android:text=&quot;@string/placeholder_color&quot;
        android:textColor=&quot;?android:textColorSecondary&quot; /&gt;

&lt;/RelativeLayout&gt;

</androidx.cardview.widget.CardView>

I don't know why there's suddenly an issue. Please help. Thanks.

huangapple
  • 本文由 发表于 2020年4月10日 14:01:41
  • 转载请务必保留本文链接:https://java.coder-hub.com/61134827.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定