【问题标题】:Most effective way of storing Strings in Android在 Android 中存储字符串的最有效方法
【发布时间】:2011-06-22 09:08:02
【问题描述】:

在我的应用程序中,我有 5 个字符串数组,它们代表对象的不同字段。

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

所有都是同一个对象的属性(这不是一个真正的对象)。


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

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

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

提前致谢 迈克

【问题讨论】:

    标签: android serialization save memory-management sharedpreferences


    【解决方案1】:

    您可以使用Intent 传递Serializable

    Intent.putExtra(String name, Serializable value).

    【讨论】:

      【解决方案2】:

      您可以通过意图传递对象。 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);
      

      希望这会有所帮助。

      【讨论】:

      • 哦,不,我知道您可以传递原始数据。我说的是一个实际的对象。无论如何,谢谢您的回复...
      • 哦,我的错。您需要 SQLite 方面的帮助吗?
      • 您可以传递实际对象 - 它们需要是 ParcelableSerializable
      • @Heiko Rupp 这实际上是一个好点......序列化将对象传递给新活动并反序列化它......不需要存储任何东西......希望我早点看到你的评论。 ... :)
      【解决方案3】:

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

      【讨论】:

      • 是的,刚刚发现序列化对象相当大,无法存储在 SharedPreferences 中...我将不得不使用 db..谢谢您的回复..
      • 是的,很抱歉忘了这样做:)
      猜你喜欢
      • 2012-11-15
      • 2016-07-20
      • 1970-01-01
      • 2012-07-13
      • 1970-01-01
      • 1970-01-01
      • 2010-09-06
      • 2012-04-12
      相关资源
      最近更新 更多