我正在做一个Chat with bubble
,其对话框为saved in a ListView
,运行正常,现在我想save this Chat in memory
,当我重新打开应用程序时,我可以跟踪对话, similar to WhatsApp
。有人可以告诉我是否可以使用SharePreference
来完成此操作吗?
以下是MainActivity代码:
public class MainActivity extends AppCompatActivity {
private ListView listView;
private View btnSend;
private EditText editText;
boolean myMessage = true;
private List<ChatBubble> ChatBubbles;
private ArrayAdapter<ChatBubble> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ChatBubbles = new ArrayList<>();
listView = (ListView) findViewById(R.id.list_msg);
btnSend = findViewById(R.id.btn_chat_send);
editText = (EditText) findViewById(R.id.msg_type);
adapter = new MessageAdapter(this, R.layout.left_chat_bubble, ChatBubbles);
listView.setAdapter(adapter);
btnSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (editText.getText().toString().trim().equals("")) {
Toast.makeText(MainActivity.this, "Please input some text...", Toast.LENGTH_SHORT).show();
} else {
//add message to list
ChatBubble ChatBubble = new ChatBubble(editText.getText().toString(), myMessage);
ChatBubbles.add(ChatBubble);
adapter.notifyDataSetChanged();
editText.setText("");
if (myMessage) {
myMessage = false;
} else {
myMessage = true;
}
}
}
});
}
}
答案 0 :(得分:2)
您可以使用Gson
:implementation 'com.google.code.gson:gson:2.8.5'
例如
Gson gson = new Gson();
String json = gson.toJson(ChatBubble);
mSharedPref.putString("chatList", json);
mSharedPref.apply();
然后检索它:
Gson gson = new Gson();
ArrayList<ChatBubble> mList = ArrayList<ChatBubble>();
String json = mSharedPref.getString("chatList", "");
mList = gson.fromJson(json, ArrayList<ChatBubble>.class);
另一种方法是在您的类上实现Serializable
,然后只需添加getString
和putExtra
getExtra
要创建SharedPreferences
SharedPreferences mSharedPref = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = mSharedPref.edit();
editor.putString()...
创建如下的arrayList
ArrayList<ChatBubble> mList = new ArrayList<ChatBubble>();
您必须将列表存储在例如onDestroy()或onStop()
中private void saveChat(){
SharedPreferences mSharedPref = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = mSharedPref.edit();
Gson gson = new Gson();
String json = gson.toJson(ChatBubble);
editor.putString("chatList", json);
editor.apply();
}
然后每次您在onCreate()方法中进入MainActivity时
private void setUpChat(){
SharedPreferences mSharedPref = PreferenceManager.getDefaultSharedPreferences(this);
Gson gson = new Gson();
String json = mSharedPref.getString("chatList", "");
ChatBubble[] mArray = gson.fromJson(json,ChatBubble[].class)
mList = new ArrayList<>(Arrays.asList(mArray));
adapter = new MessageAdapter(this, R.layout.left_chat_bubble, mList);
listView.setAdapter(adapter);
}