Java 空指针异常错误应用程序在单击回收器列表项后崩溃

Java 空指针异常错误应用程序在单击回收器列表项后崩溃,java,android,listview,android-recyclerview,Java,Android,Listview,Android Recyclerview,我正在开发一个android应用程序,它在循环列表视图中显示数据。当我点击Recycler视图中的列表项时,应用程序崩溃 public class UserRecyclerAdapterSavedUsers extends RecyclerView.Adapter<UserRecyclerAdapterSavedUsers.UserViewHolder> { private List<User> listUsers; Context mContext; ItemClic

我正在开发一个android应用程序,它在循环列表视图中显示数据。当我点击Recycler视图中的列表项时,应用程序崩溃

public class UserRecyclerAdapterSavedUsers extends RecyclerView.Adapter<UserRecyclerAdapterSavedUsers.UserViewHolder> {

private List<User> listUsers;
Context mContext;
ItemClickListenerLongPressed itemClickListenerLongPressed;

public UserRecyclerAdapterSavedUsers(List<User> listUsers) {
    this.listUsers = listUsers;
}


@Override
public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.item_user_recycler_second, parent, false);

    return new UserViewHolder(itemView);
}



@Override
public void onBindViewHolder(UserViewHolder holder, int position) {
    holder.textViewID.setText(listUsers.get(position).getUserid());
    holder.textViewName.setText(listUsers.get(position).getName());
    holder.textViewPassword.setText(listUsers.get(position).getPassword());
    holder.textViewRole.setText(listUsers.get(position).getRole());

}

public void setItemClickListenerLongPressed(ItemClickListenerLongPressed itemClickListenerLongPressed){
    this.itemClickListenerLongPressed=itemClickListenerLongPressed;
}

@Override
public int getItemCount() {
    Log.v(UserRecyclerAdapterSavedUsers.class.getSimpleName(),""+listUsers.size());
    return listUsers.size();
}

/**
 * ViewHolder class
 */
public class UserViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    //public AppCompatTextView ID;
    public AppCompatTextView textViewID;
    public AppCompatTextView textViewName;
    public AppCompatTextView textViewPassword;
    public AppCompatTextView textViewRole;

    public UserViewHolder(View view) {
        super(view);

        textViewID = (AppCompatTextView) view.findViewById(R.id.textViewID);
        textViewName = (AppCompatTextView) view.findViewById(R.id.textViewName);
        textViewPassword = (AppCompatTextView) view.findViewById(R.id.textViewPassword);
        textViewRole = (AppCompatTextView) view.findViewById(R.id.textViewRole);
    }

    @Override
    public void onClick(View v) {
        if (itemClickListenerLongPressed != null) itemClickListenerLongPressed.onClick(v, getAdapterPosition());
        Toast.makeText(mContext, "USMAN", Toast.LENGTH_SHORT).show();

    }
}
}

这是用户列表活动

public class UsersListActivity extends AppCompatActivity implements ItemClickListenerLongPressed{

AppCompatActivity activity = UsersListActivity.this;

AppCompatTextView textViewName;
RecyclerView mRecyclerView;
AppCompatButton textViewButtonNewUser;
UserRecyclerAdapterSavedUsers userRecyclerAdapterSavedUsers;
List<User> listUsers;

DatabaseHelper databaseHelper;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_user_record_updated_list);
    mRecyclerView= (RecyclerView) findViewById(R.id.recyclerViewUsers);
    mRecyclerView.setAdapter(userRecyclerAdapterSavedUsers);
    userRecyclerAdapterSavedUsers.setItemClickListenerLongPressed(this);

    initViews();
    initObjects();
}

@Override
public void onBackPressed() {
    super.onBackPressed();
    startActivity(new Intent(UsersListActivity.this,AdminMain.class));
    finish();
}

@Override
protected void onRestart() {
    super.onRestart();
}


/**
 * This method is to initialize views
 */
private void initViews() {
    textViewName = (AppCompatTextView) findViewById(R.id.textViewName);
    textViewButtonNewUser = (AppCompatButton) findViewById(R.id.btnaddnew);
    mRecyclerView = (RecyclerView) findViewById(R.id.recyclerViewUsers);
    textViewButtonNewUser.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(UsersListActivity.this,UserRecordSaveActivity.class));
        }
    });

}

/**
 * This method is to initialize objects to be used
 */
private void initObjects() {
    listUsers = new ArrayList<>();
    userRecyclerAdapterSavedUsers = new UserRecyclerAdapterSavedUsers(listUsers);

    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
    mRecyclerView.setLayoutManager(mLayoutManager);
    mRecyclerView.setItemAnimator(new DefaultItemAnimator());
    mRecyclerView.setHasFixedSize(true);
    mRecyclerView.setAdapter(userRecyclerAdapterSavedUsers);
    databaseHelper = new DatabaseHelper(activity);

    String emailFromIntent = getIntent().getStringExtra("USERS");
    textViewName.setText(emailFromIntent);

    getDataFromSQLite();
}

/**
 * This method is to fetch all user records from SQLite
 */
private void getDataFromSQLite() {
    // AsyncTask is used that SQLite operation not blocks the UI Thread.
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            listUsers.clear();
            listUsers.addAll(databaseHelper.getAllUser());

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            userRecyclerAdapterSavedUsers.notifyDataSetChanged();
        }
    }.execute();
}

@Override
public void onClick(View view, int position) {

}
}

当我点击列表项时,它崩溃了,错误是由Toast引起的。当我删除toast时,由于使用了未单击的try-catch项,所以会出现错误

这是错误的图像

删除try catch后,它再次显示错误,但这次错误显示在AlertDialog上。建设者这是没有try-catch的错误图像

添加toast logcat错误后的图像

错误现在出现在用户列表活动中

删除单击侦听器时列表中的实际数据

这是我的回收器布局文件

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
card_view:cardCornerRadius="4dp">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/Indigo"
    android:orientation="vertical"
    android:padding="16dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <android.support.v7.widget.AppCompatTextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:text="User ID"
            android:textColor="@color/colorTextHint" />

        <android.support.v7.widget.AppCompatTextView
            android:id="@+id/textViewID"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="User ID"
            android:textColor="@android:color/darker_gray" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:orientation="horizontal">

        <android.support.v7.widget.AppCompatTextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:text="Name"
            android:textColor="@color/colorTextHint" />

        <android.support.v7.widget.AppCompatTextView
            android:id="@+id/textViewName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Name"
            android:textColor="@android:color/darker_gray" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:orientation="horizontal">

        <android.support.v7.widget.AppCompatTextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:text="@string/hint_password"
            android:textColor="@color/colorTextHint" />

        <android.support.v7.widget.AppCompatTextView
            android:id="@+id/textViewPassword"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/hint_password"
            android:textColor="@android:color/darker_gray" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:orientation="horizontal">

        <android.support.v7.widget.AppCompatTextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:text="Role"
            android:textColor="@color/colorTextHint" />

        <android.support.v7.widget.AppCompatTextView
            android:id="@+id/textViewRole"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Role"
            android:textColor="@android:color/darker_gray" />
    </LinearLayout>


</LinearLayout>
这是Logcat的图像

以下是IMEIRecord保存活动适配器,如用户记录

public class IMEIRecyclerAdapter extends RecyclerView.Adapter<IMEIRecyclerAdapter.ImeiViewHolder> {

private List<User> ListImei;
Context mContext;
ItemClickListenerLongPressed itemClickListenerLongPressed;
View itemView;

public IMEIRecyclerAdapter(List<User> ListImei) {
    this.ListImei = ListImei;
}


@Override
public ImeiViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.item_user_recycler_imei, parent, false);

    return new ImeiViewHolder(itemView);
}

@Override
public void onBindViewHolder(ImeiViewHolder holder, int position) {
    final User user= ListImei.get(position);
    holder.textViewImeiId.setText(ListImei.get(position).getImeiid());
     holder.textViewImeiNo.setText(ListImei.get(position).getImei());
}

public void setItemClickListenerLongPressed(ItemClickListenerLongPressed itemClickListenerLongPressed) {
    this.itemClickListenerLongPressed = itemClickListenerLongPressed;
}

@Override
public int getItemCount() {
    Log.v(UsersRecyclerAdapter.class.getSimpleName(),""+ListImei.size());
    return ListImei.size();
}

public void displayingAlertDialogimei() {
    final User user= new User();
    //displaying alert dialog box
    AlertDialog.Builder builder = new AlertDialog.Builder(itemView.getContext());
    builder.setTitle("Choose Option");
    builder.setMessage("Update or Delete?");
    builder.setPositiveButton("Update", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

            //go to update activity
            goToUpdateActivity(user.getUserid());
            dialog.cancel();

        }
    });
    builder.setNeutralButton("Delete", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

            //go to update activity
            dialog.cancel();

        }
    });
    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
    AlertDialog alert11 = builder.create();
    alert11.show();
}

private void goToUpdateActivity(String userid) {
    Intent goToUpdate = new Intent(mContext, RoughUser.class);
    goToUpdate.putExtra("USER_ID", userid);
    mContext.startActivity(goToUpdate);

}


public class ImeiViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

    public AppCompatTextView textViewImeiId;
    public AppCompatTextView textViewImeiNo;
    LinearLayout layout;


    public ImeiViewHolder(View view) {
        super(view);
        textViewImeiId = (AppCompatTextView) view.findViewById(R.id.textViewImeiId);
        textViewImeiNo = (AppCompatTextView) view.findViewById(R.id.textViewImeiNo);
        layout = (LinearLayout) view.findViewById(R.id.list_view_imei);

        layout.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        displayingAlertDialogimei();
    }
}
}

您尚未在适配器类中声明mContext。 在适配器类中,构造函数可能会这样更改

public UserRecyclerAdapterSavedUsers(List<User> listUsers,Context context) {
    this.mContext= context;
    this.listUsers1 = listUsers;
    user= new User();
}
首先将id添加到父LinearLayout,android:id=@+id/list\u视图

然后更新适配器类

public class UserRecyclerAdapterSavedUsers extends RecyclerView.Adapter<UserRecyclerAdapterSavedUsers.UserViewHolder> {

private List<User> listUsers;
Context mContext;
ItemClickListenerLongPressed itemClickListenerLongPressed;
View itemView;

public UserRecyclerAdapterSavedUsers(List<User> listUsers) {
this.listUsers = listUsers;
}


@Override
public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType)       {
itemView = LayoutInflater.from(parent.getContext())
        .inflate(R.layout.item_user_recycler_second, parent, false);

return new UserViewHolder(itemView);
}



@Override
public void onBindViewHolder(UserViewHolder holder, int position) {
holder.textViewID.setText(listUsers.get(position).getUserid());
holder.textViewName.setText(listUsers.get(position).getName());
holder.textViewPassword.setText(listUsers.get(position).getPassword());
holder.textViewRole.setText(listUsers.get(position).getRole());

}

public void setItemClickListenerLongPressed(ItemClickListenerLongPressed itemClickListenerLongPressed){
this.itemClickListenerLongPressed=itemClickListenerLongPressed;
}

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

private void displayingAlertDialog() {
    //displaying alert dialog box
    AlertDialog.Builder builder = new AlertDialog.Builder(itemView.getContext());
    builder.setMessage("your toast message here...");
    builder.setCancelable(true);

    builder.setPositiveButton(
            "Ok",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();

                }
            });

    AlertDialog alert11 = builder.create();
    alert11.show();
}

/**
 * ViewHolder class
 */
public class UserViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

//public AppCompatTextView ID;
public AppCompatTextView textViewID;
public AppCompatTextView textViewName;
public AppCompatTextView textViewPassword;
public AppCompatTextView textViewRole;
LinearLayout layout;

public UserViewHolder(View view) {
    super(view);

    textViewID = (AppCompatTextView) view.findViewById(R.id.textViewID);
    textViewName = (AppCompatTextView) view.findViewById(R.id.textViewName);
    textViewPassword = (AppCompatTextView) view.findViewById(R.id.textViewPassword);
    textViewRole = (AppCompatTextView) view.findViewById(R.id.textViewRole);
    layout = view.findViewById(R.id.list_view);

    layout.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    displayingAlertDialog();
}
}

使用Recyclerview项,像这样单击

然后您可以访问活动或片段中的接口,然后您可以添加任何需要的内容

在适配器中发送toast和填充AlertDialog不是正确的编码方式

AlertDialog需要一个主题上下文。最简单的方法就是传递一个活动而不是上下文!事实并非如此。活动是上下文子类。那么如何解决此问题我无法将活动传递给此它不允许我将活动传递给onclick添加后错误仍然相同请添加堆栈跟踪错误仍然相同我已在onclick下添加了getitemcount当我单击列表但当我在“点击”下添加祝酒词或其他内容时,它会再次显示相同的错误。这次在toastmake上也会给出相同的错误。制作全局膨胀视图,即itemView,然后尝试它可能会起作用。请添加因toastI导致的错误的完整日志。我刚刚添加了此全局视图以获取toast中的上下文。我正在尝试这样做,我已经完成了按照教程执行此操作,但之后仍然是相同的问题,但这次是在“用户列表”活动中。
public class UserRecyclerAdapterSavedUsers extends RecyclerView.Adapter<UserRecyclerAdapterSavedUsers.UserViewHolder> {

private List<User> listUsers;
Context mContext;
ItemClickListenerLongPressed itemClickListenerLongPressed;
View itemView;

public UserRecyclerAdapterSavedUsers(List<User> listUsers) {
this.listUsers = listUsers;
}


@Override
public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType)       {
itemView = LayoutInflater.from(parent.getContext())
        .inflate(R.layout.item_user_recycler_second, parent, false);

return new UserViewHolder(itemView);
}



@Override
public void onBindViewHolder(UserViewHolder holder, int position) {
holder.textViewID.setText(listUsers.get(position).getUserid());
holder.textViewName.setText(listUsers.get(position).getName());
holder.textViewPassword.setText(listUsers.get(position).getPassword());
holder.textViewRole.setText(listUsers.get(position).getRole());

}

public void setItemClickListenerLongPressed(ItemClickListenerLongPressed itemClickListenerLongPressed){
this.itemClickListenerLongPressed=itemClickListenerLongPressed;
}

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

private void displayingAlertDialog() {
    //displaying alert dialog box
    AlertDialog.Builder builder = new AlertDialog.Builder(itemView.getContext());
    builder.setMessage("your toast message here...");
    builder.setCancelable(true);

    builder.setPositiveButton(
            "Ok",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();

                }
            });

    AlertDialog alert11 = builder.create();
    alert11.show();
}

/**
 * ViewHolder class
 */
public class UserViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

//public AppCompatTextView ID;
public AppCompatTextView textViewID;
public AppCompatTextView textViewName;
public AppCompatTextView textViewPassword;
public AppCompatTextView textViewRole;
LinearLayout layout;

public UserViewHolder(View view) {
    super(view);

    textViewID = (AppCompatTextView) view.findViewById(R.id.textViewID);
    textViewName = (AppCompatTextView) view.findViewById(R.id.textViewName);
    textViewPassword = (AppCompatTextView) view.findViewById(R.id.textViewPassword);
    textViewRole = (AppCompatTextView) view.findViewById(R.id.textViewRole);
    layout = view.findViewById(R.id.list_view);

    layout.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    displayingAlertDialog();
}
}