我可以在recyclerView
为ArrayList的另一个类中检索单个字符串数据的共享首选项吗
我在活动中有一个保存按钮,它将保存应用程序本身中指定的日期和时间、日期和时间,并且我想在recyclerView
为ArrayList的另一个活动中检索相同的数据。
保存按钮将只保存数据,还有另一个按钮,我将通过它转到另一个活动
public class StudentListActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.Adapter rAdapter;
private RecyclerView.LayoutManager layoutManager;
ArrayList<ListOfNames> listOfNames;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
String t1 = "10";
String t2 = "100%";
Bundle bundle;
String subName;
Toolbar toolbar;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.student_list);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
bundle = getIntent().getExtras();
subName = bundle.getString("Subject Name");
if (bundle != null) {
getSupportActionBar().setTitle(subName);
}
loadData();
Calendar calendar = Calendar.getInstance();
String currentDate = DateFormat.getDateTimeInstance().format(calendar.getTime());
toolbar.setSubtitle(currentDate);
fabButton();
buildRecyclerView();
}
@Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(this, ScrollingActivity.class);
intent.putExtra("count", listOfNames.size());
startActivity(intent);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.item1:
handleDate();
return true;
case R.id.item2:
Intent intent = new Intent(this, PastAttendences.class);
startActivity(intent);
return true;
case R.id.title3:
//我想在这里使用sharedPrefrences来保存日期/时间
return true;
}
return super.onOptionsItemSelected(item);
}
public void handelTime(final CharSequence charSequence) {
final Calendar calendar = Calendar.getInstance();
int Hour = calendar.get(Calendar.HOUR);
int Minute = calendar.get(Calendar.MINUTE);
boolean is24Hour = android.text.format.DateFormat.is24HourFormat(this);
TimePickerDialog timePickerDialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int Hour, int Minute) {
Calendar calendar1 = Calendar.getInstance();
calendar1.set(Calendar.HOUR, Hour);
calendar1.set(Calendar.MINUTE, Minute);
CharSequence charSequence1 = android.text.format.DateFormat.format("HH.mm", calendar1);
toolbar.setSubtitle(charSequence + " " + charSequence1);
}
}, Hour, Minute, is24Hour);
timePickerDialog.show();
}
public void handleDate() {
final Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int date = calendar.get(Calendar.DATE);
DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int date) {
Calendar calendar1 = Calendar.getInstance();
calendar1.set(Calendar.YEAR, year);
calendar1.set(Calendar.MONTH, month);
calendar1.set(Calendar.DATE, date);
CharSequence charSequence = android.text.format.DateFormat.format("dd-MMM-yyyy", calendar1);
handelTime(charSequence);
}
}, year, month, date);
datePickerDialog.show();
}
private void buildRecyclerView() {
recyclerView = findViewById(R.id.recyclerView2);
recyclerView.hasFixedSize();
layoutManager = new LinearLayoutManager(StudentListActivity.this);
rAdapter = new AdapterForStudentList(listOfNames);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(rAdapter);
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleCallback);
itemTouchHelper.attachToRecyclerView(recyclerView);
}
public void insertData(String text, String t1, String t2) {
ListOfNames lt = new ListOfNames(text, t1, t2);
listOfNames.add(lt);
rAdapter.notifyDataSetChanged();
}
public void saveData() {
sharedPreferences = getSharedPreferences("SHARED PREF", MODE_PRIVATE);
editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(listOfNames);
editor.putString(subName, json);
editor.apply();
}
public void loadData() {
sharedPreferences = getSharedPreferences("SHARED PREF", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString(subName, null);
Type type = new TypeToken<ArrayList<ListOfNames>>() {
}.getType();
listOfNames = gson.fromJson(json, type);
if (listOfNames == null) {
listOfNames = new ArrayList<>();
}
}
ListOfNames deletedItem = null;
ItemTouchHelper.SimpleCallback simpleCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
@Override
public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
return false;
}
@Override
public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
final int position = viewHolder.getAdapterPosition();
String name = listOfNames.get(position).getStudentName();
deletedItem = listOfNames.get(position);
listOfNames.remove(deletedItem);
sharedPreferences = getSharedPreferences("SHARED PREF", MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.remove("text");
saveData();
editor.apply();
rAdapter.notifyItemRemoved(position);
Snackbar.make(recyclerView, name + "Deleted", Snackbar.LENGTH_LONG)
.setAction("Undo", new View.OnClickListener() {
@Override
public void onClick(View v) {
listOfNames.add(position, deletedItem);
rAdapter.notifyItemInserted(position);
saveData();
}
}).show();
}
@Override
public void onChildDrawOver(@NonNull Canvas c, @NonNull RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
new RecyclerViewSwipeDecorator.Builder(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
.addSwipeLeftBackgroundColor(ContextCompat.getColor(StudentListActivity.this, R.color.my_background))
.addSwipeLeftActionIcon(R.drawable.ic_delete_black_24dp)
.create()
.decorate();
super.onChildDrawOver(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
}
};
public void fabButton() {
FloatingActionButton floatingActionButton = findViewById(R.id.fab2);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder b = new AlertDialog.Builder(StudentListActivity.this);
View view = getLayoutInflater().inflate(R.layout.dialogbox_frontpage, null);
final EditText editText = view.findViewById(R.id.editText);
b.setView(view);
b.setTitle("Student name");
b.setPositiveButton("ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String text = editText.getText().toString();
if (text.isEmpty()) {
Toast.makeText(StudentListActivity.this, "Please add subject name", Toast.LENGTH_SHORT).show();
} else {
insertData(text, t1, t2);
saveData();
}
}
});
b.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
b.setCancelable(false);
b.show();
}
});
}
}
下一个活动
public class PastAttendences extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<ListOfPastAttendences> mItems;
public static final String DATETIME = "dateTime";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.past_attendence);
Toolbar toolbar = findViewById(R.id.attendenceToolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Past Attendances");
mItems = new ArrayList<>();
buildRecyclerView();
}
public void buildRecyclerView() {
recyclerView = findViewById(R.id.pARecyclerView);
recyclerView.hasFixedSize();
layoutManager = new LinearLayoutManager(this);
adapter = new PastAttendenceAdapter(mItems);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
}
}
U可以初始化sharedPref(如https://www.tutorialspoint.com/android/android_shared_preferences.htm):-
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
Editor editor = sharedpreferences.edit();
editor.putString("key", "value");
editor.commit();
U可以使用(如中所示https://stackoverflow.com/a/48001112/12987677):-
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
preferences.getString(key, null);
您可以将数组存储为字符串
editor.putString(key,Array.toString());
editor.apply();
你可以从字符串中获得数组(下面的一些代码是kotlin语法(
variableOne =JSONArray(preferences.getString(key, null));
VariableThreeList = ArrayList()
for (i in 0 until variableOne !!.length()) {
variableTwo = JSONObject(variableOne !![i].toString())
VariableThreeList!!.add(variableTwo.getString("Name"))
}
}
注意:JSONArray,JSONObject来自import org.json.JSONArray,import org.json.JSONObject