在Android中存储字符串的最有效方法

时间:2011-02-06 19:25:09

标签: android serialization save memory-management sharedpreferences

在我的应用程序中,我有5个String数组,表示不同的对象字段。

String_A[1],
String_B[1],
String_C[1],
String_D[1],
String_E[1],

所有都是同一个对象的属性(实际上不是对象)。


现在我想存储这些内容,以便能够在我正在创建的新活动中使用它们。由于你无法传递对象,我认为我应该将它们保存在共享首选项中。

我的问题是:我应该将它们保存为单独的字符串,还是创建一个包含所有字段的新类,然后序列化对象?

就内存使用而言,哪种方式最好?实际上还有其他方法可以实现类似的功能吗?

提前致谢 麦克

3 个答案:

答案 0 :(得分:2)

如果这些字符串数组中的每一个都足够大并且看起来你确实要存储它们 - 你考虑过Sqlite吗? SharedPreferences最有效地将原始数据存储在键值对中。检查此链接 - 它与您拥有的选项 - http://developer.android.com/guide/topics/data/data-storage.html

进行了简洁的比较

答案 1 :(得分:0)

您可以通过意图传递对象。 intent的extras函数可以存储bundle并将其发送到指定的活动,但是它们不能在任何时候被调用(例如来自稍后的活动而没有被明确发送)。如果这是一次性传递给不同的活动,您可能想要使用它。

http://developer.android.com/reference/android/content/Intent.html#putExtras%28android.content.Intent%29

以下是我之前做过的测试应用程序的示例:

public void onClick(View v) {
            switch(v.getId()) { //this references the unique ID of the view that was clicked
                case R.id.Button01: //this is what happens when the Button in the XML with android:id="@+id/Button01" is clicked
            Intent nameGreet = new Intent(this, MainMenu.class);//creates Intent which will send the EditText input
                    String theName = firstName.getText().toString();// creates a new string named "theName" which is the text from an EditText called "firstName"
                    nameGreet.putExtra("helloName", theName);//puts the input from EditText into the Intent, this is a key/value pair
                    this.startActivity(nameGreet);//setting off the Intent
                    break;

然后你就这样抓住它:

@Override
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState);
    this.setContentView(R.layout.main_menu);
    String personsname = this.getIntent().getStringExtra("helloName");
    welcome = (TextView)this.findViewById(R.id.TextView01);
    welcome.setText(personsname);

希望这有帮助。

答案 2 :(得分:0)

您可以使用Serializable传递Intent

Intent.putExtra(String name, Serializable value)