У меня есть приложение, которое использует RecyclerView для отображения имен после добавления в базу данных SQLite. Я вставляю данные, такие как контактный номер, адрес и т. Д. c. с DialogFragment. Если я нажимаю на элемент в RecyclerView, я хочу, чтобы он go отображал новое действие, содержащее информацию, которую я добавил в базу данных для каждого элемента в RecyclerView. Как я могу заставить RecyclerView определить, по какому элементу была нажата кнопка, и сделать так, чтобы в новом действии была другая информация в зависимости от того, по какому элементу я щелкнул?
package com.example.ctdc;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
public class RecordFragment extends Fragment implements RecordsDialog.OnInputSelected, RecylerViewAdapter.OnRecordListener {
private SQLiteDatabase mDatabase;
private static final String TAG = "MainFragment";
private RecylerViewAdapter mAdapter;
private RecyclerView mrecyclerview;
private Toolbar toolbar;
private FloatingActionButton addRecord;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_records, container, false);
toolbar = (Toolbar) v.findViewById(R.id.toolbar);
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Medical Records");
mrecyclerview = (RecyclerView) v.findViewById(R.id.record_recylerView);
mrecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
mAdapter = new RecylerViewAdapter(getActivity(), getAllRecord(), this);
mrecyclerview.setAdapter(mAdapter);
addRecord = (FloatingActionButton) v.findViewById(R.id.add_circle);
addRecord.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RecordsDialog dialog = new RecordsDialog();
dialog.setTargetFragment(RecordFragment.this, 1);
dialog.show(getFragmentManager(), "MyCustomDialog");
}
});
return v;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DatabaseHelper1 dbHelper = new DatabaseHelper1(getActivity());
mDatabase = dbHelper.getWritableDatabase();
}
public Cursor getAllRecord(){
return mDatabase.query(
DatabaseHelper1.TABLE_NAME,
null,
null,
null,
null,
null,
DatabaseHelper1.COL_1 + " DESC"
);
}
@Override
public void sendInput(String FirstName, String Surname) {
Log.d(TAG, "sendInput: found incoming input" + FirstName + ", " + Surname);
mAdapter.swapCursor(getAllRecord());
}
@Override
public void onRecordClick(int position) {
Log.d(TAG, "onRecordClick: clicked" );
Intent intent = new Intent(getActivity(), RecordLayout_Activity.class);
startActivity(intent);
}
}
Здесь мой элемент RecordFragment мой адаптер:
package com.example.ctdc;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class RecylerViewAdapter extends RecyclerView.Adapter<RecylerViewAdapter.MyViewHolder> {
private OnRecordListener mOnRecordListener;
private Context mContext;
private Cursor mCursor;
public RecylerViewAdapter(Context Context, Cursor cursor, OnRecordListener onRecordListener) {
this.mContext = Context;
this.mCursor = cursor;
this.mOnRecordListener = onRecordListener;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v;
v = LayoutInflater.from(mContext).inflate(R.layout.item_record, parent,false);
MyViewHolder vHolder = new MyViewHolder(v, mOnRecordListener);
return vHolder;
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
if (!mCursor.moveToPosition(position)){
return;
}
String tv_name = mCursor.getString(mCursor.getColumnIndex(DatabaseHelper1.COL_3)) + ", " + mCursor.getString(mCursor.getColumnIndex(DatabaseHelper1.COL_2));
holder.tv_name.setText(tv_name);
if(position %2 == 1)
{
holder.itemView.setBackgroundColor(Color.parseColor("#e9f2f3"));
}
else
{
holder.itemView.setBackgroundColor(Color.parseColor("#cfe2e3"));
}
}
@Override
public int getItemCount() {
return mCursor.getCount();
}
public void swapCursor(Cursor newCursor) {
if (mCursor != null) {
mCursor.close();
}
mCursor = newCursor;
if (newCursor != null) {
notifyDataSetChanged();
}
}
public static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView tv_name;
RelativeLayout parentlayout;
OnRecordListener onRecordListener;
public MyViewHolder(@NonNull View itemView, OnRecordListener onRecordListener) {
super(itemView);
tv_name = (TextView) itemView.findViewById(R.id.name_record);
parentlayout = itemView.findViewById(R.id.parent_layout_record);
this.onRecordListener = onRecordListener;
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
onRecordListener.onRecordClick(getAdapterPosition());
}
}
public interface OnRecordListener{
void onRecordClick(int position);
}
}
DatabaseHelper
package com.example.ctdc;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
public class DatabaseHelper1 extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "record.db";
public static final String TABLE_NAME = "record_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "FIRST_NAME";
public static final String COL_3 = "SURNAME";
public static final String COL_4 = "SEX";
public static final String COL_5 = "ADDRESS";
public static final String COL_6 = "CONTACT_NO";
public static final String COL_7 = "CIVIL_STATUS";
public static final String COL_8 = "OCCUPATION";
public static final String COL_9 = "REFERRED_BY";
public static final String COL_10 = "BIRTH_DATE_MONTH";
public static final String COL_11 = "BIRTH_DATE_DAY";
public static final String COL_12 = "BIRTH_DATE_YEAR";
public DatabaseHelper1(@Nullable Context context) {
super(context, DATABASE_NAME, null, 3);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, FIRST_NAME TEXT, SURNAME TEXT ,SEX TEXT, ADDRESS TEXT, " +
"CONTACT_NO INTEGER, CIVIL_STATUS TEXT, OCCUPATION TEXT, REFERRED_BY TEXT, BIRTH_DATE_MONTH INTEGER, BIRTH_DATE_DAY INTEGER, BIRTH_DATE_YEAR INTEGER) ");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String firstname, String lastname, String sex, String address, String contactno, String civilstatus, String occupation,
String referredby, String birthdatemonth, String birthdateday, String birthdateyear) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2, firstname);
contentValues.put(COL_3, lastname);
contentValues.put(COL_4, sex);
contentValues.put(COL_5, address);
contentValues.put(COL_6, contactno);
contentValues.put(COL_7, civilstatus);
contentValues.put(COL_8, occupation);
contentValues.put(COL_9, referredby);
contentValues.put(COL_10, birthdatemonth);
contentValues.put(COL_11, birthdateday);
contentValues.put(COL_12, birthdateyear);
long result = db.insert(TABLE_NAME,null , contentValues);
if (result == - 1)
return false;
else
return true;
}
}