gpt4 book ai didi

java - 如何将 SQlite 数据库加载到 Recyclerview 中?

转载 作者:行者123 更新时间:2023-11-29 19:22:15 25 4
gpt4 key购买 nike

我在一个 fragment Activity 中有一个 recyclerview,它使用一个按钮来调出一个警告对话框来获取 2 个字符串变量的输入。我已经成功创建了数据库并且可以从 alertdialog 输入向数据库添加项目,但是我想在应用程序最初启动时用数据库填充 recyclerview。数据库用于存储输入,我希望它填充 recyclerview,以便用户可以看到他们之前输入的项目。

这是我的 fragment :

public class tab1Expenses extends Fragment {

SqlDatabase dbEntry;

ArrayList<ExRow> expenseList = new ArrayList<>();
RecyclerView recyclerView;
ExpensesAdapter mAdapter;
Button btnEx;
String Na;
String Am;
String message = "Name must be longer than 2 characters";
String message2 = "Please enter valid amount";
Double value;
String am;

public void expenseData() {
ExRow exs = new ExRow(Na, Am);
expenseList.add(exs);
mAdapter.notifyDataSetChanged();
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final View rootView = inflater.inflate(R.layout.tab1expense, container, false);
btnEx = (Button) rootView.findViewById(R.id.btnEx);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
recyclerView.addItemDecoration(new DividerItemDecoration(tab1Expenses.this.getActivity(), LinearLayoutManager.VERTICAL));

mAdapter = new ExpensesAdapter(expenseList);
final RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this.getActivity());

recyclerView.setHasFixedSize(true);
recyclerView.setClickable(true);
recyclerView.isFocusable();
recyclerView.setFocusableInTouchMode(true);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);

btnEx.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Brings up Alert Dialog when Add income button is pressed
add();
}
});
return rootView;
}


public int add() {
View view = LayoutInflater.from(tab1Expenses.this.getActivity())
.inflate(R.layout.add_ex, null);
final EditText txtExName = (EditText) view.findViewById(R.id.exName);
final EditText txtExAmount = (EditText) view.findViewById(R.id.exAmount);
//Creates Alert Dialog
AlertDialog.Builder add = new AlertDialog.Builder(tab1Expenses.this.getActivity());
add.setCancelable(true)
.setTitle("Enter Expense:")
.setView(view)
.setPositiveButton("Add",
//AlertDialog positive button ClickListener
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Checks for invalid input
//If criteria met, expenseData() is called
if (txtExAmount.getText().length() > 0 && txtExName.getText().length() > 2 && txtExAmount.getText().length() < 6 && txtExName.getText().length() < 25) {
Na = txtExName.getText().toString();
am = txtExAmount.getText().toString();
value = Double.parseDouble(am);
Am = NumberFormat.getCurrencyInstance().format(value);
expenseData();

}
//Toast for invalid input
if (txtExName.getText().length() <= 2) {
Toast.makeText(tab1Expenses.this.getActivity(), message, Toast.LENGTH_SHORT).show();
} else if (txtExAmount.getText().length() == 0) {
Toast.makeText(tab1Expenses.this.getActivity(), message2, Toast.LENGTH_SHORT).show();
} else if (txtExAmount.getText().length() >= 6) {
Toast.makeText(tab1Expenses.this.getActivity(), "You don't make that much", Toast.LENGTH_SHORT).show();
} else if (txtExName.getText().length() >= 25) {
Toast.makeText(tab1Expenses.this.getActivity(), "Name must be less than 25 characters", Toast.LENGTH_SHORT).show();
}
}
});
Dialog dialog = add.create();
dialog.show();

return 0;
}

public void viewAll() {

ExRow exrow = new ExRow();
Cursor res = dbEntry.getAllData();
exrow.setTitle(res.getString(1));
exrow.setAmount(res.getString(2));

}
}

这是我的数据库:

public class SqlDatabase extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "Expenses.db";
public static final String TABLE_NAME = "Expense_Table";
public static final String ID = "id";
public static final String Col_NAME = "Na";
public static final String Col_AMOUNT = "Am";


public SqlDatabase(Context context) {
super(context, DATABASE_NAME, null, 1);
}

@Override
//Set up database here
public void onCreate(SQLiteDatabase db) {
db.execSQL("Create table " + TABLE_NAME +
"(ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT, AMOUNT TEXT)");

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String Na, String Am) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Col_NAME, Na);
contentValues.put(Col_AMOUNT, Am);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1) {
return false;
} else {
return true;
}

}
public static Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from " + TABLE_NAME, null);
return res;

}
}

这是我的 RecyclerView Adapter + View holder:

public class ExpensesAdapter extends RecyclerView.Adapter<ExpensesAdapter.MyViewHolder> {
public ImageButton mRemoveButton;
private ArrayList<ExRow> expenseList;

public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title, amount;

public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.name);
amount = (TextView) view.findViewById(R.id.amount);
mRemoveButton = (ImageButton) view.findViewById(R.id.ib_remove);
}
}

public ExpensesAdapter(ArrayList<ExRow> expenseList) {
this.expenseList = expenseList;
}

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

return new MyViewHolder(itemView);
}

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

ExRow expense = expenseList.get(holder.getAdapterPosition());
holder.title.setText(expense.getTitle());
holder.amount.setText(expense.getAmount());
mRemoveButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// Remove the item on remove/button click
int adapterPosition = holder.getAdapterPosition();

expenseList.remove(adapterPosition);
notifyItemRemoved(adapterPosition);
notifyDataSetChanged();
}
});
}
@Override
public int getItemCount() {
return expenseList.size();

最佳答案

您需要在 SQLiteOpenHelper 中获取 ExRow 的列表,而不是游标。所以不是:

public static Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from " + TABLE_NAME, null);
return res;

}

你需要返回像这样的列表:

// Your column 
private String[] allColumns = { "ID", "COLUMN_1", "COLUMN_2" };

public List<ExRow> getAllData() {
List<ExRow> exrows = new ArrayList<>();

Cursor cursor = database.query("YOUR_TABLE", allColumns, null, null,
null, null, null);

if (cursor != null && cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {

ExRow exrow = populateModel(cursor);
exrows.add(exrow);
cursor.moveToNext();
}
cursor.close();
}
return exrows;
}


private ExRow populateModel(Cursor c) {
ExRow model = new ExRow();
model.setId(c.getLong("ID"));
model.setColumn1(c.getString(c.getColumnIndex("COLUMN_1")));
model.setColumn2(c.getString(c.getColumnIndex("COLUMN_2")));

return model;
}

然后您可以使用从 getAllData() 返回的值并将其传递给您的适配器。

关于java - 如何将 SQlite 数据库加载到 Recyclerview 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42176807/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com