gpt4 book ai didi

java - 如何修复sqlite在android中多次插入最后一个EditText值

转载 作者:行者123 更新时间:2023-12-02 01:22:17 24 4
gpt4 key购买 nike

我正在尝试在 android 的 sqlite 数据库中插入 3 个 Edittext 值插入功能运行良好,但它插入了最后一个 edittext 值 3 次。我插入(约翰,史密斯,安娜)和sqlite插入(安娜,安娜,安娜)这是我的代码

LinearLayout ll;
EditText editText;
TextView textView;
String room;
Button save;

private DBHelper dbHelper;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_room_name);

final SharedPreferences mSharedPreferences =
PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String room_number = (mSharedPreferences.getString("room_number",
""));

ll = findViewById(R.id.ll);

final int num = Integer.valueOf(room_number);

dbHelper = new DBHelper(this);

for (int i = 0; i < num; i++) {
editText = new EditText(this);
editText.setHint("Room " + (i + 1) + " Name");

textView = new TextView(this);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10);

ll.addView(editText);
ll.addView(textView);

}
save = new Button(this);
save.setText("save");

ll.addView(save);

save.setOnClickListener(v ->{

for (int j = 0; j < num; j++){
if(dbHelper.insertRoom(editText.getText().toString())){
Toast.makeText(getApplicationContext(), "done",
Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(), "No", Toast.LENGTH_LONG).show();
}
}

});

}

最佳答案

您在执行插入操作的循环中使用相同的 EditText,这是您以编程方式创建的 3 个 EditText 中的最后一个。
而不是:

EditText editText;

使用数组来存储3个EditText:

EditText[] editText;

并将代码更改为:

LinearLayout ll;
EditText[] editText;
TextView textView;
String room;
Button save;

private DBHelper dbHelper;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_room_name);
final SharedPreferences mSharedPreferences =
PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String room_number = (mSharedPreferences.getString("room_number",
""));

ll = findViewById(R.id.ll);

final int num = Integer.valueOf(room_number);

dbHelper = new DBHelper(this);

editText = new EditText[num];
for (int i = 0; i < num; i++) {
editText[i] = new EditText(this);
editText[i].setHint("Room " + (i + 1) + " Name");

textView = new TextView(this);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10);

ll.addView(editText[i]);
ll.addView(textView);

}
save = new Button(this);
save.setText("save");

ll.addView(save);

save.setOnClickListener(v -> {

for (int j = 0; j < num; j++) {
if (dbHelper.insertRoom(editText[j].getText().toString())) {
Toast.makeText(getApplicationContext(), "done",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "No", Toast.LENGTH_LONG).show();
}
}

});
}

关于java - 如何修复sqlite在android中多次插入最后一个EditText值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57476095/

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