Android中的SharedPreferences是本地存储,用于在电话存储中存储字符串,整数和变量,以便我们可以管理应用程序的状态。我们已经看到将简单变量存储在具有键和值对的共享首选项中。在本文中,我们将看到如何在我们的Android应用程序中将ArrayList存储到共享首选项。
我们将在本文中构建什么?
我们将构建一个简单的应用程序,在其中将在简单的RecyclerView中显示课程名称及其描述,并将所有这些数据存储在共享的首选项中。因此,当我们关闭应用程序并重新打开应用程序时,所有数据将保存在共享的首选项中,并保持回收者视图的状态。下面提供了一个示例视频,以使您对我们在本文中将要做的事情有个大概的了解。注意,我们将使用Java语言实现该项目。
分步实施
步骤1:创建一个新项目
要在Android Studio中创建新项目,请参阅如何在Android Studio中创建/启动新项目。请注意,选择Java作为编程语言。
步骤2:在build.gradle中为gson添加依赖项
导航到应用程序> Gradle脚本> build.gradle(app)并在依赖项部分添加以下依赖项。
implementation ‘com.google.code.gson:gson:2.8.5’
添加此依赖项后,同步您的项目。
第3步:创建用于存储数据的模式类
导航到应用程序> Java >您的应用程序的程序包名称>右键单击它>新建> Java类,并将您的类命名为CourseModal,然后将以下代码添加到其中。
Java
public class CourseModal {
// variables for our course
// name and description.
private String courseName;
private String courseDescription;
// creating constructor for our variables.
public CourseModal(String courseName, String courseDescription) {
this.courseName = courseName;
this.courseDescription = courseDescription;
}
// creating getter and setter methods.
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public String getCourseDescription() {
return courseDescription;
}
public void setCourseDescription(String courseDescription) {
this.courseDescription = courseDescription;
}
}
XML
Java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class CourseAdapter extends RecyclerView.Adapter {
// creating a variable for array list and context.
private ArrayList courseModalArrayList;
private Context context;
// creating a constructor for our variables.
public CourseAdapter(ArrayList courseModalArrayList, Context context) {
this.courseModalArrayList = courseModalArrayList;
this.context = context;
}
@NonNull
@Override
public CourseAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
// below line is to inflate our layout.
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.course_rv_item, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull CourseAdapter.ViewHolder holder, int position) {
// setting data to our views of recycler view.
CourseModal modal = courseModalArrayList.get(position);
holder.courseNameTV.setText(modal.getCourseName());
holder.courseDescTV.setText(modal.getCourseDescription());
}
@Override
public int getItemCount() {
// returning the size of array list.
return courseModalArrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
// creating variables for our views.
private TextView courseNameTV, courseDescTV;
public ViewHolder(@NonNull View itemView) {
super(itemView);
// initializing our views with their ids.
courseNameTV = itemView.findViewById(R.id.idTVCourseName);
courseDescTV = itemView.findViewById(R.id.idTVCourseDescription);
}
}
}
XML
Java
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
// creating variables for our ui components.
private EditText courseNameEdt, courseDescEdt;
private Button addBtn, saveBtn;
private RecyclerView courseRV;
// variable for our adapter class and array list
private CourseAdapter adapter;
private ArrayList courseModalArrayList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initializing our variables.
courseNameEdt = findViewById(R.id.idEdtCourseName);
courseDescEdt = findViewById(R.id.idEdtCourseDescription);
addBtn = findViewById(R.id.idBtnAdd);
saveBtn = findViewById(R.id.idBtnSave);
courseRV = findViewById(R.id.idRVCourses);
// calling method to load data
// from shared prefs.
loadData();
// calling method to build
// recycler view.
buildRecyclerView();
// on click listener for adding data to array list.
addBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// below line is use to add data to array list.
courseModalArrayList.add(new CourseModal(courseNameEdt.getText().toString(), courseDescEdt.getText().toString()));
// notifying adapter when new data added.
adapter.notifyItemInserted(courseModalArrayList.size());
}
});
// on click listener for saving data in shared preferences.
saveBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// calling method to save data in shared prefs.
saveData();
}
});
}
private void buildRecyclerView() {
// initializing our adapter class.
adapter = new CourseAdapter(courseModalArrayList, MainActivity.this);
// adding layout manager to our recycler view.
LinearLayoutManager manager = new LinearLayoutManager(this);
courseRV.setHasFixedSize(true);
// setting layout manager to our recycler view.
courseRV.setLayoutManager(manager);
// setting adapter to our recycler view.
courseRV.setAdapter(adapter);
}
private void loadData() {
// method to load arraylist from shared prefs
// initializing our shared prefs with name as
// shared preferences.
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
// creating a variable for gson.
Gson gson = new Gson();
// below line is to get to string present from our
// shared prefs if not present setting it as null.
String json = sharedPreferences.getString("courses", null);
// below line is to get the type of our array list.
Type type = new TypeToken>() {}.getType();
// in below line we are getting data from gson
// and saving it to our array list
courseModalArrayList = gson.fromJson(json, type);
// checking below if the array list is empty or not
if (courseModalArrayList == null) {
// if the array list is empty
// creating a new array list.
courseModalArrayList = new ArrayList<>();
}
}
private void saveData() {
// method for saving the data in array list.
// creating a variable for storing data in
// shared preferences.
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
// creating a variable for editor to
// store data in shared preferences.
SharedPreferences.Editor editor = sharedPreferences.edit();
// creating a new variable for gson.
Gson gson = new Gson();
// getting data from gson and storing it in a string.
String json = gson.toJson(courseModalArrayList);
// below line is to save data in shared
// prefs in the form of string.
editor.putString("courses", json);
// below line is to apply changes
// and save data in shared prefs.
editor.apply();
// after saving data we are displaying a toast message.
Toast.makeText(this, "Saved Array List to Shared preferences. ", Toast.LENGTH_SHORT).show();
}
}
步骤4:为我们的RecyclerView项目创建一个布局文件
导航到应用程序> res>布局>右键单击它>新建>布局资源文件,并将您的布局命名为course_rv_item ,并将以下代码添加到其中。
XML格式
第5步:创建一个适配器类以将数据设置为我们RecyclerView的项目
导航到应用程序> Java >应用程序的程序包名称>右键单击它>新建> Java类,并将其命名为CourseAdapter,然后将以下代码添加到其中。
Java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class CourseAdapter extends RecyclerView.Adapter {
// creating a variable for array list and context.
private ArrayList courseModalArrayList;
private Context context;
// creating a constructor for our variables.
public CourseAdapter(ArrayList courseModalArrayList, Context context) {
this.courseModalArrayList = courseModalArrayList;
this.context = context;
}
@NonNull
@Override
public CourseAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
// below line is to inflate our layout.
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.course_rv_item, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull CourseAdapter.ViewHolder holder, int position) {
// setting data to our views of recycler view.
CourseModal modal = courseModalArrayList.get(position);
holder.courseNameTV.setText(modal.getCourseName());
holder.courseDescTV.setText(modal.getCourseDescription());
}
@Override
public int getItemCount() {
// returning the size of array list.
return courseModalArrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
// creating variables for our views.
private TextView courseNameTV, courseDescTV;
public ViewHolder(@NonNull View itemView) {
super(itemView);
// initializing our views with their ids.
courseNameTV = itemView.findViewById(R.id.idTVCourseName);
courseDescTV = itemView.findViewById(R.id.idTVCourseDescription);
}
}
}
步骤6:使用activity_main.xml文件
导航到应用程序> res>布局> activity_main.xml,然后将以下代码添加到该文件中。以下是activity_main.xml文件的代码。
XML格式
步骤7:使用MainActivity。 Java文件
转到MainActivity。 Java文件并参考以下代码。下面是MainActivity的代码。 Java文件。在代码内部添加了注释,以更详细地了解代码。
Java
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
// creating variables for our ui components.
private EditText courseNameEdt, courseDescEdt;
private Button addBtn, saveBtn;
private RecyclerView courseRV;
// variable for our adapter class and array list
private CourseAdapter adapter;
private ArrayList courseModalArrayList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initializing our variables.
courseNameEdt = findViewById(R.id.idEdtCourseName);
courseDescEdt = findViewById(R.id.idEdtCourseDescription);
addBtn = findViewById(R.id.idBtnAdd);
saveBtn = findViewById(R.id.idBtnSave);
courseRV = findViewById(R.id.idRVCourses);
// calling method to load data
// from shared prefs.
loadData();
// calling method to build
// recycler view.
buildRecyclerView();
// on click listener for adding data to array list.
addBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// below line is use to add data to array list.
courseModalArrayList.add(new CourseModal(courseNameEdt.getText().toString(), courseDescEdt.getText().toString()));
// notifying adapter when new data added.
adapter.notifyItemInserted(courseModalArrayList.size());
}
});
// on click listener for saving data in shared preferences.
saveBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// calling method to save data in shared prefs.
saveData();
}
});
}
private void buildRecyclerView() {
// initializing our adapter class.
adapter = new CourseAdapter(courseModalArrayList, MainActivity.this);
// adding layout manager to our recycler view.
LinearLayoutManager manager = new LinearLayoutManager(this);
courseRV.setHasFixedSize(true);
// setting layout manager to our recycler view.
courseRV.setLayoutManager(manager);
// setting adapter to our recycler view.
courseRV.setAdapter(adapter);
}
private void loadData() {
// method to load arraylist from shared prefs
// initializing our shared prefs with name as
// shared preferences.
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
// creating a variable for gson.
Gson gson = new Gson();
// below line is to get to string present from our
// shared prefs if not present setting it as null.
String json = sharedPreferences.getString("courses", null);
// below line is to get the type of our array list.
Type type = new TypeToken>() {}.getType();
// in below line we are getting data from gson
// and saving it to our array list
courseModalArrayList = gson.fromJson(json, type);
// checking below if the array list is empty or not
if (courseModalArrayList == null) {
// if the array list is empty
// creating a new array list.
courseModalArrayList = new ArrayList<>();
}
}
private void saveData() {
// method for saving the data in array list.
// creating a variable for storing data in
// shared preferences.
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
// creating a variable for editor to
// store data in shared preferences.
SharedPreferences.Editor editor = sharedPreferences.edit();
// creating a new variable for gson.
Gson gson = new Gson();
// getting data from gson and storing it in a string.
String json = gson.toJson(courseModalArrayList);
// below line is to save data in shared
// prefs in the form of string.
editor.putString("courses", json);
// below line is to apply changes
// and save data in shared prefs.
editor.apply();
// after saving data we are displaying a toast message.
Toast.makeText(this, "Saved Array List to Shared preferences. ", Toast.LENGTH_SHORT).show();
}
}
现在运行您的应用程序,并查看该应用程序的输出。