将任务添加到RecyclerView

时间:2019-03-03 23:54:40

标签: java android

我是Android新手,仅通过一本书就已经学习了大约一个月的Android应用开发知识,而现在,我正在从事自己的项目,这是一个管理用户任务和计划的基本应用。我有这个问题。我正在尝试将一个新任务添加到包含主要任务列表的RecyclerView列表中,但是我一直遇到错误。这就是我所拥有的(我不想显示所有内容,因为它是一个项目):

RecyclerView列表(main_task_window.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"
  android:layout_width="match_parent"
  android:layout_height="match_parent">

<android.support.v7.widget.RecyclerView
    android:id="@+id/MainTaskList"
    android:layout_width="match_parent"
    android:layout_height="449dp"
    android:layout_alignParentStart="true"
    android:layout_alignParentBottom="true"
    android:layout_marginStart="0dp"
    android:layout_marginTop="1dp"
    android:layout_marginBottom="61dp" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/AddaMainTask"
    android:onClick="addnewtask"
    android:layout_width="54dp"
    android:layout_height="51dp"
    android:layout_alignParentEnd="true"
    android:layout_alignParentBottom="true"
    android:layout_marginEnd="13dp"
    android:layout_marginBottom="10dp"
    android:clickable="true"
    app:srcCompat="@android:drawable/ic_input_add" />

</RelativeLayout>

允许用户添加新的主要任务以及其他注释的窗口(add_new_main_task_window.xml):

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

<EditText
    android:id="@+id/maintasks"
    android:layout_width="match_parent"
    android:layout_height="62dp"
    android:hint="Main Task"/>

<EditText
    android:id="@+id/notes"
    android:layout_width="match_parent"
    android:layout_height="62dp"
    android:hint="Additional notes"/>

<Button
    android:id="@+id/addButton"
    android:onClick="sendButton"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Add to main task" />

</LinearLayout>

现在,以下是Java文件:  1. MainTasks.java(包含主要任务的get和set方法以及其他说明)

package com.ricstudios.daymanager;

public class MainTasks
{
    private String mt, an; //'mt' stands for "main tasks". 'an' stands for "additional notes"

    //MainTasks class constructor
    public MainTasks(String mt, String an)
    {
        //mt and an in the parameters is equal to the mt and an variables above
        this.mt = mt;
        this.an = an;
    }

    public String getMainTasks() //this get method obtains the main task string input)
    {
       return mt;
    }
    public void setMainTasks(String MainTasks) //this set methods stores the main task string input)
    {
       this.mt = MainTasks;
    }
    public String getAdditionalNotes() //this get method obtains the main task string input
    {
       return an;
    }
    public void setAdditionalNotes(String AddNotes) //this set method stores the main task string
    {
       this.an = AddNotes;
    }
}
  1. MainTaskAdapter.java(包含用于呈现数据的适配器)

package com.ricstudios.daymanager;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import java.util.List;

public class MainTaskAdapter extends RecyclerView.Adapter<MainTaskAdapter.ViewHolder>
{
    private List<MainTasks> maintasklist; //will contain the main task and additional notes string inputs

    public class ViewHolder extends RecyclerView.ViewHolder
    {
        public EditText maintask, addnotes;

        //provides a reference to the views for each data item
        public ViewHolder(View view)
        {
            super(view);

            maintask = (EditText)view.findViewById(R.id.maintasks);
            addnotes = (EditText)view.findViewById(R.id.notes);
        }
    }

    //MainTaskAdapter class constructor
    public MainTaskAdapter(List<MainTasks> maintasklist)
    {
        this.maintasklist = maintasklist;
    }

    //create new view (invoked by the layout manager)
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
    {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.add_new_main_task_window, parent, false);

        return new ViewHolder(itemView);
    }

    //replaces the contents of the main task view (invoked by the layout manager)
    @Override
    public void onBindViewHolder(ViewHolder holder, int position)
    {
        MainTasks obj = maintasklist.get(position); //MainTasks class obj called 'obj', which allows access to the MainTasks class

        //obtains the main task and additional notes from the MainTask class
        holder.maintask.setText(obj.getMainTasks());
        holder.addnotes.setText(obj.getAdditionalNotes());
    }

    //returns the size of the main task list (invoked by the layout manager)
    @Override
    public int getItemCount()
    {
        return maintasklist.size();
    }
}

  1. AddNewMainTask.java(将任务和其他注释添加到RecyclerView)

package com.ricstudios.daymanager;

import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Button;
import android.view.View;

import java.util.ArrayList;
import java.util.List;

/*This class handles the window for adding new main tasks to the main task list (this window is the add_new_main_task_window.xml layout)*/
public class AddNewMainTask extends AppCompatActivity
{
    private Button addbutton; //Button element from the add_new_main_task_window.xml layout
    private EditText maintask, addnotes; //EditText elements from the add_new_main_task_window.xml layout
    private List<MainTasks> maintasklist = new ArrayList<>();
    private RecyclerView ListofMainTasks; //RecyclerView list element from the add_new_main_task_window.xml layout (containing the Main Task list)
    private MainTaskAdapter TAdapter; //MainTaskAdapter class object 'TAdapter', allows access to the MainTaskAdapter class

    /*sendButton method from the Button element in the add_new_main_task_window.xml and adds the main task and additional notes to the RecyclerView main task list*/
    public void sendButton(View view)
    {
        maintask = (EditText)view.findViewById(R.id.maintasks);
        addnotes = (EditText)view.findViewById(R.id.notes);

        ListofMainTasks = (RecyclerView)findViewById(R.id.MainTaskList);

        TAdapter = new MainTaskAdapter(maintasklist);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        ListofMainTasks.setLayoutManager(mLayoutManager);
        ListofMainTasks.setItemAnimator(new DefaultItemAnimator());
        ListofMainTasks.setAdapter(TAdapter);

        /*Passes the EditText element values into the MainTask.java parameters*/
        MainTasks mnt = new MainTasks(maintask.getText().toString(), addnotes.getText().toString());
        maintasklist.add(mnt);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_new_main_task_window); //displays the window that allows users to add new main tasks (which is the add_new_main_task_window.xml layout)

        addbutton = (Button)findViewById(R.id.addButton);

        /*When user clicks button, the values the user puts in the EditText fields will be added to the RecyclerView list of the main_task_window.xml layout*/
        addbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                sendButton(v);
            }
        });
    }
}

每当我按下“添加到主要任务”按钮时,应用程序都会突然停止。请帮忙。哦,关于main_task_window.xml中的floatactionbutton,不用担心。只是将用户发送到add_new_main_task_window.xml

更新:19年3月5日

我从logcat收到此错误: 03年5月5日15:22:49.298 10335-10335 / com.project.daymanager E / Android运行时:致命异常:主要     流程:com.project.daymanager,PID:10335     java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'void android.support.v7.widget.RecyclerView.setLayoutManager(android.support.v7.widget.RecyclerView $ LayoutManager)'         在com.project.daymanager.AddNewMainTask.sendButton(AddNewMainTask.java:39)         在com.project.daymanager.AddNewMainTask $ 1.onClick(AddNewMainTask.java:63)         在android.view.View.performClick(View.java:5702)         在android.widget.TextView.performClick(TextView.java:10887)         在android.view.View $ PerformClick.run(View.java:22541)         在android.os.Handler.handleCallback(Handler.java:739)         在android.os.Handler.dispatchMessage(Handler.java:95)         在android.os.Looper.loop(Looper.java:158)         在android.app.ActivityThread.main(ActivityThread.java:7229)         在java.lang.reflect.Method.invoke(本机方法)         在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:1230)         在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

2 个答案:

答案 0 :(得分:0)

  1. 替换 view.findViewById();findViewById();

  2. MainTasks.java中不要使用构造函数

public MainTasks(String mt, String an)
只需保留设置并获取方法并执行

 MainTasks mt = new MainTasks();
 mt.setMainTasks("Title");
 mt.setAdditionalNotes("Note");
 list.add(mt);

如果仍然无法正常运行,请发布错误日志,以便我们了解错误原因。

更新:19年3月5日

您正在尝试访问

recyclerView的{​​{1}}

MainTaskActivity

从活动的外部(从另一个活动),这是不可能的,

您可以通过将ListofMainTasks = (RecyclerView)findViewById(R.id.MainTaskList);中的RecyclerView设置为MainTaskActivity并在static活动中使用它
AddNewMainTask

答案 1 :(得分:0)

问题在这一行:

 ListofMainTasks = (RecyclerView)findViewById(R.id.MainTaskList);

程序无法找到回收站视图及其空值。并且您不能将布局管理器设置为空对象。我已经检查了您的代码,您做错的是,在您的onCreate方法中,您正在设置布局setContentView(R.layout.add_new_main_task_window);,并且您正在尝试查找不在此布局中的recylerview。

您的回收站视图在 main_task_window.xml 中。使用setContentView(R.layout.main_task_window.xml);,您的活动将很容易找到recyclerview。

注意:如果您还希望按钮/控件也位于此布局中 add_new_main_task_window.xml ,请使用recyclerview在布局中移动它们。