片段中的Arraylist总是返回0

时间:2018-03-17 12:16:36

标签: android arraylist fragment

我使用片段在recyclerview中的sqlite数据库中显示数据。我设置了一个textView,如果在arraylist.size()== 0,它将显示一条消息,如果不是,它将不显示。问题是即使数据库中有数据,arraylist.size()也总是返回零。

在向数据库添加数据时,我使用此

add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            TextView errorWeight = (TextView)weight.getSelectedView();
            TextView errorPer = (TextView)per.getSelectedView();
            TextView errorRepeat = (TextView)repeat.getSelectedView();

            if (name_food.getText().toString().trim().equalsIgnoreCase("")) {
                name_food.setError("Please add a title to the task");
            }
            else if (date.getText().toString().trim().equalsIgnoreCase("")) {
                date.setError("Set date to start");
            }
            else if (time.getText().toString().trim().equalsIgnoreCase("")) {
                time.setError("Set time to start");
            }
            else if (quantity.getText().toString().trim().equalsIgnoreCase("")) {
                quantity.setError("Set amount of food");
            }
            else if (weight.getSelectedItem().toString().trim().equalsIgnoreCase("Weight")) {
                errorWeight.setError("Set weight of food");
            }
            else if (per.getSelectedItem().toString().trim().equalsIgnoreCase("Per")) {
                errorPer.setError("Set Per meal or per day");
            }
            else if (repeat.getSelectedItem().toString().trim().equalsIgnoreCase("Repeat Task after")) {
                errorRepeat.setError("Set task repetition");
            }
            else
            {
                name_food.setError(null);
                date.setError(null);
                time.setError(null);
                quantity.setError(null);
                errorWeight.setError(null);
                errorPer.setError(null);
                errorRepeat.setError(null);
                arrayLists=new ArrayList<>();
                food_model item=new food_model();
                db=new food_database(add_food.this);
                adapter=new foodRecyclerAdapter(add_food.this,arrayLists);
                item.setPet_id(Integer.valueOf(petid.getText().toString()));
                item.setPet_name(name_pet.getText().toString());
                item.setType_food(name_food.getText().toString());
                item.setDate(date.getText().toString());
                item.setTime(time.getText().toString());
                item.setQuantity(quantity.getText().toString());
                item.setFood_weight(weight.getSelectedItem().toString());
                item.setMeal(per.getSelectedItem().toString());
                item.setNote(note.getText().toString());
                item.setSched(repeat.getSelectedItem().toString());
                boolean addfood=db.insertDataTofood(item);
                if(addfood)
                {
                    adapter.addItem(item);
                    Toast.makeText(add_food.this,"Task has been added",Toast.LENGTH_SHORT).show();
                    Toast.makeText(add_food.this,"Item added"+arrayLists.size(),Toast.LENGTH_SHORT).show();
                    Intent intent=new Intent(add_food.this,foodActivity.class);
                    intent.putExtra("name",name);
                    intent.putExtra("id",id);
                    intent.putExtra("breed",breed);
                    intent.putExtra("type",type);
                    startActivity(intent);
                    finish();
                }
                else
                {
                    Toast.makeText(add_food.this,"Task not added",Toast.LENGTH_SHORT).show();
                }

            }

        }
    });

然后在Recyclerview适配器中,我使用此方法将数据添加到arraylist

 public void addItem(food_model item) {
    foodarraylist.add(0, item);
    notifyItemInserted(0);
}

然后是片段

    public class food_sched extends Fragment {
FloatingActionButton floatingActionButton;
RecyclerView recyclerView;
TextView reminder,subreminder;
Context context;
ArrayList<food_model> model;
Cursor c;
foodRecyclerAdapter adapter;
    LinearLayoutManager linearLayoutManager;
    String name,id,type,breed;
    public food_sched() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        model=new ArrayList<>();
        Intent taker=getActivity().getIntent();
        name=taker.getStringExtra("name");
        id=taker.getStringExtra("id");
        type=taker.getStringExtra("type");
        breed=taker.getStringExtra("breed");
        context=getActivity();
        if(model.size()==0)
        {
            Toast.makeText(context,"size is "+model.size(),Toast.LENGTH_SHORT).show();
        }
        else
        {
            Toast.makeText(context,"size is "+model.size(),Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view= inflater.inflate(R.layout.frag_food_sched, container, false);

        recyclerView=(RecyclerView) view.findViewById(R.id.food_recyclerview);
        reminder=(TextView) view.findViewById(R.id.food_reminder);
        subreminder=(TextView) view.findViewById(R.id.food_reminder_sub);
        floatingActionButton=(FloatingActionButton)view.findViewById(R.id.add_food);
        linearLayoutManager = new LinearLayoutManager(getContext());
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(linearLayoutManager);
        loadfoodDB(context);
        setFoodAlarms(context);
        updateviews(context);
        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            Intent intent=new Intent(getContext(),add_food.class);
            intent.putExtra("petname",name);
            intent.putExtra("petid",id);
                intent.putExtra("petbreed",breed);
                intent.putExtra("pettype",type);
            getContext().startActivity(intent);
            getActivity().finish();
            }
        });

        adapter.updateDataOnNotification(model);
        recyclerView.setVisibility(View.VISIBLE);
        return view;

    }

这种从数据库加载数据的方法

public void loadfoodDB(Context context)
{
    food_database db=new food_database(context);
    food_db_retrieve foodDbRetrieve=new food_db_retrieve(context);
    foodDbRetrieve.openDB();
    model=new ArrayList<>();
    int newid=Integer.valueOf(id);

    c = db.queryData("select * from food_schedule WHERE pet_id ='"+newid+"' ORDER BY food_ID DESC");

    try {
        if(c != null)
        {
            if(c.moveToFirst())
            {
                do{
                    food_model items=new food_model();
                    items.setFood_id(c.getInt(0));
                    items.setPet_id(c.getInt(1));
                    items.setPet_name(c.getString(2));
                    items.setType_food(c.getString(3));
                    items.setDate(c.getString(4));
                    items.setTime(c.getString(5));
                    items.setQuantity(c.getString(6));
                    items.setFood_weight(c.getString(7));
                    items.setMeal(c.getString(8));
                    items.setNote(c.getString(9));
                    items.setSched(c.getString(10));
                    model.add(items);
                }while (c.moveToNext());
            }
        }
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    adapter = new foodRecyclerAdapter(context,model);
    recyclerView.setAdapter(adapter);
    adapter.notifyDataSetChanged();
    foodDbRetrieve.closeDB();
}

你能告诉我为什么它会返回0吗?

1 个答案:

答案 0 :(得分:1)

因为你在创建ArrayList之后就显示了toast。

将Toast移至onCreateView()或加载onCreate()

中的数据

因为在onCreateView()

之后调用了onCreate()

您的onCreateView()应该是这样的。

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view= inflater.inflate(R.layout.frag_food_sched, container, false);

        -------------------
        -------------------
        loadfoodDB(context);


      if(model.size()==0)
        {
            Toast.makeText(context,"size is "+model.size(),Toast.LENGTH_SHORT).show();
        }
        else
        {
            Toast.makeText(context,"size is "+model.size(),Toast.LENGTH_SHORT).show();
        }

         ------------------------
         ------------------------

        return view;

    }