当前位置: 首页 > 知识库问答 >
问题:

当滚动超过最初可见的内容时,无法访问回收器视图中的textviews

贺善
2023-03-14

我在这里算是个新手。我正在尝试使用recyclerview来显示SQlite表中的项。我需要它做的是,当一个项目被单击时,一个上下文菜单显示,要求采取三个操作之一。其中一项要求我从所选位置的一个textviews中获取数据。当我单击一个最初可查看的项目时,它工作得很好,但是,如果我向下滚动到一个最初不可查看的项目,它会在试图访问TextView的地方崩溃。以下是错误:

尝试对空对象引用调用虚拟方法“Android.View.View Android.Widget.RelativeLayout.FindViewById(int)”

活动:

package com.cascadia.nutrak;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.Date;
import static com.cascadia.nutrak.FoodDbHelper.s1;


public class MyKitchen2 extends AppCompatActivity {

    SQLiteDatabase mDatabase;
    DBRecyclerViewAdapter mAdapter;

    RecyclerView myFoodDBRecView;

    String qty;
    FoodDbHelper myFoodDB;
    public String foodItemSelected;
    boolean isInserted;
    TextView idView;
    String dBaseID;

    String selPosition;




    public void gotoCupboard(View view) {

        //Create an "Intent" to go to ManageFoodActivity
        Intent myIntent = new Intent(getApplicationContext(), ManageFoodActivity.class);

        //pass info to second activity

        //myIntent.putExtra("Friend Chosen", friendList.get(i));  //pass chosen friend as a string

        //Start the intent
        startActivity(myIntent);

    }

    public void goHome(View view) {

        startActivity(new Intent(getApplicationContext(),MainActivity.class));
    }


    public void goToMngTodaysFood(View view) {

        //Create an "Intent" to go to next activity SecondActivity
        Intent myIntent = new Intent(getApplicationContext(), ManageTodaysFood2.class);

        //Start the intent
        startActivity(myIntent);

    }




    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_kitchen2);

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);

        myFoodDB = new FoodDbHelper(this);
        mDatabase = myFoodDB.getWritableDatabase();

        myFoodDBRecView = (RecyclerView) findViewById(R.id.myFoodDBRecView);

        myFoodDBRecView.setHasFixedSize(false);
        myFoodDBRecView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));

        //Use class DBRecyclerViewAdapter to create a new adapter and Run getAllItems function to get and put the masterFoodDB into the adapter "mAdapter".
        mAdapter = new DBRecyclerViewAdapter(this, getAllItems());

        //Assign the adapter and its contents (should be the whole MF database) to the recyclerView
        myFoodDBRecView.setAdapter(mAdapter);


        itemClickSupport.addTo(myFoodDBRecView).setOnItemClickListener(

                new itemClickSupport.OnItemClickListener() {

                    @Override
                    public void onItemClicked(RecyclerView recyclerView, int position, View view) {

                    selPosition = String.valueOf(position) ;

                    registerForContextMenu(recyclerView); //This means that when touched it will popup a context menu setup below.
                    recyclerView.showContextMenuForChild(view);
                    unregisterForContextMenu(recyclerView); //This means that when touched it will popup a context menu setup below.

                    }
                }
        );

    }//End onCreate



    //Get the entire master food database and order by description
    private Cursor getAllItems() {
        return mDatabase.query(
                dBaseContract.masterFoodDB.TABLE_NAME,
                null,
                null,
                null,
                null,
                null,
                dBaseContract.masterFoodDB.MF_COL_1 + " DESC"
        );
    }


        @Override
        public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
            super.onCreateContextMenu(menu, v, menuInfo);

            getMenuInflater().inflate(R.menu.popup_menu, menu);
        }


        @Override
        public boolean onContextItemSelected(MenuItem item) {

            Log.i("The item is", String.valueOf(item));


            switch (item.getItemId()) {

                case R.id.iatethis:

                    Toast.makeText(this, "I ate this seleted", Toast.LENGTH_SHORT).show();

                    //Here we ask for a quantity
                    AlertDialog.Builder alert = new AlertDialog.Builder(this);
                    alert.setTitle(foodItemSelected);
                    alert.setMessage("Enter Quantity Consumed");

                    // Set an EditText view to get user input
                    final EditText qtyInput = new EditText(this);

                    //limit edit text to numbers only

                    qtyInput.setInputType(InputType.TYPE_CLASS_NUMBER |
                            InputType.TYPE_NUMBER_FLAG_DECIMAL |
                            InputType.TYPE_NUMBER_FLAG_SIGNED);

                    //Set alert dialog view to use
                    alert.setView(qtyInput);

                    alert.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {

                            qty = qtyInput.getText().toString();
                            Log.d("", "Pin Value : " + qty);

                            //Get todays date
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                            String date = sdf.format(new Date());

                            RecyclerView myFoodDBRecView = (RecyclerView) findViewById(R.id.myFoodDBRecView);

                            //get the child record at the positionb
                            RelativeLayout relativeLayout = (RelativeLayout) myFoodDBRecView.getChildAt(Integer.parseInt(selPosition));

                            //Get access to text view in recylcer view child
                            TextView idView = (TextView) relativeLayout.findViewById(R.id.idView);

                            dBaseID = idView.getText().toString();

                            Log.i("The position is", selPosition);
                            Log.i("The dBaseID is", dBaseID);

                            FoodDbHelper getRecordHelper = new FoodDbHelper(MyKitchen2.this);

                            //go get entire record for the selected dBaseID
                            getRecordHelper.returnAllSingleRecord2(dBaseID); //delete fooditemselected from above

                            //Debug code to make sure we have all the data from the record.
                            for (int i = 0; i <= 10; i++) {
                                Log.i("s1 " + i, " = " + s1[i]); //Verify we have all data in array
                            }
                            isInserted = myFoodDB.insertConsumedData( //run the insertConsumedData boolean method in FoodDBHelper on main database

                                    date, qty, s1[1], s1[2], s1[3], s1[4], s1[5], s1[6], s1[7], s1[8], s1[9], s1[10], s1[11] //Insert data returned in S1 into consumed table
                                    // leave out s1[0] as it is the key from mstr table
                                    //add date and qty and then data from master 1-10
                            );

                            if (isInserted = true) {

                                Toast.makeText(MyKitchen2.this, "Data inserted into todays food", Toast.LENGTH_LONG).show();


                            } else {

                                Toast.makeText(MyKitchen2.this, "Data failed to insertinto todays food", Toast.LENGTH_LONG).show();
                            }

                            return;
                        }
                    });


                    alert.setNegativeButton("Cancel",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    // TODO Auto-generated method stub
                                    return;
                                }
                            });
                    alert.show();

            return true; //always when item was handled

                case R.id.viewedit:

                    Toast.makeText(this, "view/edit selected", Toast.LENGTH_SHORT).show();

                return true; //always when item was handled
                case R.id.delete:

                    Toast.makeText(this, "deleted", Toast.LENGTH_SHORT).show();


                    FoodDbHelper dbHelper = new FoodDbHelper(MyKitchen2.this);
                    // Log.i("Still Have it?", "?  " + selPosition);
                    dbHelper.remMasterSingleRecord(dBaseID); //delete fooditemselected from above

                    mAdapter = new DBRecyclerViewAdapter(this, getAllItems());
                    myFoodDBRecView.setAdapter(mAdapter);


                    Toast.makeText(MyKitchen2.this, "Item removed from Cupboard", Toast.LENGTH_SHORT).show();


                    return true; //always when item was handled

                default: //This has to be at end
                return super.onContextItemSelected(item);  //put return super inside default case


            }

        }

    //----------------------------------------------------------------------------------------------------------------------------------
    //Special functions

    //This disables the back button
    @Override
    public void onBackPressed() {}

}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:clickable="true"
    android:focusable="true"
    android:foreground="?android:attr/selectableItemBackground"
    android:layout_width="360dp"
    android:layout_height="55dp">

    <TextView
        android:id="@+id/foodItemView"
        android:layout_width="180dp"
        android:layout_height="25dp"
        android:layout_marginLeft="0dp"
        android:layout_marginTop="0dp"
        android:gravity="left|center_vertical"
        android:textSize="16sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/descView"
        android:layout_width="180dp"
        android:layout_height="25dp"
        android:layout_alignParentTop="true"
        android:layout_marginStart="0dp"
        android:layout_marginTop="0dp"
        android:layout_toEndOf="@+id/foodItemView"
        android:gravity="left|center_vertical" />

    <TextView
        android:id="@+id/textView52"
        android:layout_width="45dp"
        android:layout_height="25dp"
        android:layout_below="@+id/foodItemView"
        android:layout_marginTop="0dp"
        android:gravity="center_horizontal|center_vertical"
        android:text="Cals" />

    <TextView
        android:id="@+id/calsView"
        android:layout_width="45dp"
        android:layout_height="25dp"
        android:layout_below="@+id/foodItemView"
        android:layout_marginStart="45dp"
        android:layout_marginTop="0dp"
        android:gravity="left|center_vertical" />

    <TextView
        android:id="@+id/textView54"
        android:layout_width="45dp"
        android:layout_height="25dp"
        android:layout_below="@+id/foodItemView"
        android:layout_marginStart="90dp"
        android:layout_marginTop="0dp"
        android:gravity="center_horizontal|center_vertical"
        android:text="Carbs" />

    <TextView
        android:id="@+id/carbsView"
        android:layout_width="45dp"
        android:layout_height="25dp"
        android:layout_below="@+id/foodItemView"
        android:layout_marginStart="135dp"
        android:layout_marginTop="0dp"
        android:gravity="left|center_vertical" />

    <TextView
        android:id="@+id/textView56"
        android:layout_width="45dp"
        android:layout_height="25dp"
        android:layout_below="@+id/descView"
        android:layout_marginStart="180dp"
        android:layout_marginLeft="50dp"
        android:layout_marginTop="0dp"
        android:gravity="center_horizontal|center_vertical"
        android:text="Prot" />

    <TextView
        android:id="@+id/protView"
        android:layout_width="45dp"
        android:layout_height="25dp"
        android:layout_below="@+id/descView"
        android:layout_marginStart="225dp"
        android:layout_marginLeft="50dp"
        android:layout_marginTop="0dp"
        android:gravity="left|center_vertical" />

    <TextView
        android:id="@+id/textView58"
        android:layout_width="45dp"
        android:layout_height="25dp"
        android:layout_below="@+id/descView"
        android:layout_marginStart="270dp"
        android:layout_marginLeft="50dp"
        android:layout_marginTop="0dp"
        android:gravity="center_horizontal|center_vertical"
        android:text="Fat" />

    <TextView
        android:id="@+id/fatView"
        android:layout_width="45dp"
        android:layout_height="25dp"
        android:layout_below="@+id/descView"
        android:layout_marginStart="315dp"
        android:layout_marginLeft="50dp"
        android:layout_marginTop="0dp"
        android:gravity="left|center_vertical" />

    <TextView
        android:id="@+id/textView60"
        android:layout_width="400dp"
        android:layout_height="5dp"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="-1dp"
        android:background="#000000"
        android:text="TextView" />

    <TextView
            android:id="@+id/idView"
            android:layout_width="50dp"
            android:layout_height="25dp"
            android:layout_marginLeft="300dp"
            android:visibility="visible" />

</RelativeLayout>

package com.cascadia.nutrak;

import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

public class DBRecyclerViewAdapter extends RecyclerView.Adapter<DBRecyclerViewAdapter.masterFoodViewHolder> {

    private Context mContext;
    private Cursor mCursor;


    public DBRecyclerViewAdapter(Context context, Cursor cursor) {
        mContext = context;
        mCursor = cursor;
    }


    public class masterFoodViewHolder extends RecyclerView.ViewHolder { //} implements View.OnClickListener {

        //Initialize all the text views
        public TextView idText;
        public TextView nameText;
        public TextView calsText;
        public TextView protText;
        public TextView carbsText;
        public TextView fatText;
        public TextView descText;


        //Here we fill the viewholder
        public masterFoodViewHolder(View itemView) {
            super(itemView);


            //Here we assign the listLayout.xml TextView components to the TextView variables
            idText = itemView.findViewById(R.id.idView);
            nameText = itemView.findViewById(R.id.foodItemView);
            calsText = itemView.findViewById(R.id.calsView);
            protText = itemView.findViewById(R.id.protView);
            carbsText = itemView.findViewById(R.id.carbsView);
            fatText = itemView.findViewById(R.id.fatView);
            descText = itemView.findViewById(R.id.descView);
        }
    }


        @Override
        public masterFoodViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

            //Inflate the Recycler View using mContext and listLayout.xml
            LayoutInflater inflater = LayoutInflater.from(parent.getContext());
            View view = inflater.inflate(R.layout.listlayout, parent, false);


            return new masterFoodViewHolder(view);
        }


        @Override
        public void onBindViewHolder(masterFoodViewHolder holder, final int position) {

            //Bind your datasource, in this case SQlite dbase, to the ViewHolder

            //Cursor through all records
            if (!mCursor.moveToPosition(position)) {
                return;
            }

            //Here we are loading the dbase column values into variables
            String id = mCursor.getString(mCursor.getColumnIndex(dBaseContract.masterFoodDB.MF_ID));
            String name = mCursor.getString(mCursor.getColumnIndex(dBaseContract.masterFoodDB.MF_COL_1));
            String cals = mCursor.getString(mCursor.getColumnIndex(dBaseContract.masterFoodDB.MF_COL_2));
            String prot = mCursor.getString(mCursor.getColumnIndex(dBaseContract.masterFoodDB.MF_COL_3));
            String carbs = mCursor.getString(mCursor.getColumnIndex(dBaseContract.masterFoodDB.MF_COL_4));
            String fat = mCursor.getString(mCursor.getColumnIndex(dBaseContract.masterFoodDB.MF_COL_5));
            String desc = mCursor.getString(mCursor.getColumnIndex(dBaseContract.masterFoodDB.MF_COL_11));

            //Here we are loading the dbase columns, now in variables, into the listlayout textviews to display to user
            holder.idText.setText(id);
            holder.nameText.setText(name);
            holder.calsText.setText(cals);
            holder.protText.setText(prot);
            holder.carbsText.setText(carbs);
            holder.fatText.setText(fat);
            holder.descText.setText(desc);



        }//end onbindviewholder

        @Override
        public int getItemCount() {
            return mCursor.getCount();
        }





    //declare interface for recycler view on item click listener
    private  OnItemClicked onClick;

    //make interface like this
    public interface OnItemClicked {
        void onItemClick(final int position);
    }

    public void setOnClick(OnItemClicked onClick)
    {
        this.onClick=onClick;
    }


    }
    //end of activity



共有1个答案

水麒
2023-03-14

Recyclerer列出不可见的回收视图。所以我不希望textview具有您想要的值。相反,您应该尝试从任何用于将数据设置到视图的数组中提取字符串,如

mAdapter.get(position)

很难说,因为我不明白你说的是哪一行代码

我想你说的是这个

  //get the child record at the positionb
                        RelativeLayout relativeLayout = (RelativeLayout) myFoodDBRecView.getChildAt(Integer.parseInt(selPosition));

                        //Get access to text view in recylcer view child
                        TextView idView = (TextView) relativeLayout.findViewById(R.id.idView);
dBaseID = myFoodDBRecView.adapter.get(selPosition);
 类似资料:
  • 在其他回收器视图中有一个回收器视图。两者都需要垂直滚动。外部回收器视图滚动正常,但内部回收器视图滚动不正常。 这是代码: ViewAdapter如下: 我尝试了以下两种回收商观点,但都无法解决问题 也尝试了这个:

  • 我在Scrollview中有Recyclerview 现在,滚动时,layoutStaticContent保持固定在顶部

  • 我正在使用下面的代码创建一个回收器视图。recyclerview有一个网格布局管理器,其项计数最多为每行2个。 不幸的是,我嵌套在ConstraintLayout中的回收器视图根本没有滚动。我错过了什么?约束布局是否支持相同的?

  • 我有一个endless Recycler视图,其中包含使用JSoup从一个在线论坛线程中提取的数据。recyclerview将不断填充自己,直到用户到达最后一页。我想膨胀一个“端视图”,一旦用户到达最后一页,滚动到最后一个可见的项目,但我无法检索它。 我尝试使用getItemCount()和findLastVisibleItemPotion()从回收器视图linearlayoutManager。它

  • 我有一个水平回收视图。每个子级包含一个TextView和一个垂直RecyclerView。垂直RecyclerView的子级仅包含TextView。 垂直滚动非常平滑,但水平滚动滞后很多。我已经尝试在onBindViewHolder中使用swapAdapter,而不是setAdapter,但这并没有解决问题。我也尝试过更改数据集并调用notifyDataSetChanged(),但这也没有帮助。

  • 问题内容: 我有一个用CSS3进行动画处理的条形图,当前该动画在页面加载时激活。 我的问题是,由于之前有很多内容,因此给定的条形图不在屏幕上,因此当用户向下滚动到该条形图时,动画已经结束。 我正在寻找通过CSS3或jQuery仅在查看者看到图表时激活条形图上的CSS3动画的方法。 如果在页面加载后立即快速向下滚动,则可以看到该动画。 另外,我不知道这是否重要,但是我在页面上有此条形图的多个实例。