我正在为我的应用程序制作一个功能,用户可以在RecyleView中添加新的食物项目。但我选择了一个弹出窗口,该窗口出现在主活动中,您可以输入食物和价格,这意味着活动不会刷新。我如何在不重新启动应用程序的情况下在RecyleView中显示项目?
主要活动代码:
public class SecondScreen extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_screen);
myDB = new MyDataBaseHelper(SecondScreen.this);
foodID = new ArrayList<>();
foodName = new ArrayList<>();
foodPrice = new ArrayList<>();
popUp();
//Data from Sql Tables
storeDataInArrays();
customAdapater = new CustomAdapater(SecondScreen.this, foodID, foodName, foodPrice);
recyclerView.setLayoutManager(new LinearLayoutManager(SecondScreen.this));
recyclerView.setAdapter(customAdapater);
//Storing the data from the sql table
public void storeDataInArrays(){
Cursor cursor = myDB.readAllData();
//Gets the count of the rows
if(cursor.getCount() == 0){
Toast.makeText(this, "No data", Toast.LENGTH_SHORT).show();
}else{
while(cursor.moveToNext()){
foodID.add(cursor.getString(0));
foodName.add(cursor.getString(1));
foodPrice.add(cursor.getString(2));
}
}
}
}
public void PopUP(){
btnAddFood.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MyDataBaseHelper myDB = new MyDataBaseHelper(SecondScreen.this);
myDB.addFood(edtFoodName.getText().toString().trim(),
edtFoodPrice.getText().toString().trim());
//Dismisses the popUp after button click
myDialog.dismiss();
}
});
}
}
RecycleView适配器代码
public class CustomAdapater extends RecyclerView.Adapter<CustomAdapater.MyViewHolder> {
Context context;
private ArrayList foodID, foodName, foodPrice;
CheckBox chkItem;
//Constructor
CustomAdapater(Context context, ArrayList foodID, ArrayList foodName, ArrayList foodPrice){
//Declares to global variables that can be used in the MainAcivity
this.context = context;
this.foodID = foodID;
this.foodName = foodName;
this.foodPrice = foodPrice;
}
@NonNull
@Override
public CustomAdapater.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
//Inflates the item_row layout
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.item_row, parent, false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull CustomAdapater.MyViewHolder holder, int position) {
holder.checkItem.setText(String.valueOf(foodName.get(position)));
holder.foodPrice_txt.setText(String.valueOf(foodPrice.get(position) + "$"));
}
@Override
public int getItemCount() {
return foodID.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView foodPrice_txt;
CheckBox checkItem;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
checkItem = itemView.findViewById(R.id.chkItemRow);
foodPrice_txt = itemView.findViewById(R.id.txtPriceRow);
}
}
}
1条答案
按热度按时间pod7payv1#
在将项添加到数据库和数组列表之后,调用
notifyItemInserted
来更新适配器。就像这样: