gpt4 book ai didi

java - 如何停止替换共享首选项中的先前条目?

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

我的代码用于替换以前的条目,我意识到我需要使用不同的键来存储共享首选项。现在我的代码不会在 ListView 中输出任何内容。请帮忙

Java 代码,我在其中询问有关此人的信息(姓名、最爱颜色、最爱食物)

public class personInfo extends AppCompatActivity {

EditText editText_name;
EditText editText_favfood;
EditText editText_favcolor;
Button button_save;
static int count = 0;
SharedPreferences sharedPreferences;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_personinfo);
Log.d(MainActivity.class.getSimpleName(), "onCreate");

editText_name = (EditText) findViewById(R.id.editText_name);
editText_favcolor = (EditText) findViewById(R.id.editText_favcolor);
editText_favfood = (EditText) findViewById(R.id.editText_favfood);
button_save = (Button) findViewById(R.id.button_save);


button_save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

count++;
SharedPreferences sharedPreferences = getSharedPreferences("ENTRIES", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();

editor.putString("name" + count, editText_name.getText().toString());
editor.putString("favcolor" + count, editText_favcolor.getText().toString());
editor.putString("favfood" + count, editText_favfood.getText().toString());

editor.apply();
editor.putInt("numOfEntries", count);


Intent it = new Intent(personInfo.this, listOfPeople.class);
startActivity(it);

}
});
}
}
<小时/>

Java 代码,应该显示条目的页面

public class listOfPeople extends AppCompatActivity {

ListView listView;
ArrayList<listEntry> list = new ArrayList<>();
listEntry le;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);

listView = (ListView) findViewById(R.id.listView_persons);

SharedPreferences sharedPreferences = getSharedPreferences("ENTRIES", MODE_PRIVATE);
int count = sharedPreferences.getInt("numOfEntries", 0);

for(int i = 1; i <= count; i++){
String nameValue = sharedPreferences.getString("name" + i, "");
String favcolorValue = sharedPreferences.getString("favcolor" + i, "");
String favfoodValue = sharedPreferences.getString("favfood" + i, "");

le = new listEntry(nameValue, favcolorValue, favfoodValue);
list.add(le);
}

personListAdapter adapter = new personListAdapter(this, R.layout.entryrow, list);
listView.setAdapter(adapter);
}
}

最佳答案

您正在应用(保存)首选项,然后再输入count

 editor.apply();
editor.putInt("numOfEntries", count);

只需在申请前放置即可

 editor.putInt("numOfEntries", count);
editor.apply();

关于java - 如何停止替换共享首选项中的先前条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58510068/

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