【问题标题】:Pass data between Activitys before start the new activity在开始新活动之前在活动之间传递数据
【发布时间】:2014-04-24 11:19:40
【问题描述】:

我正在尝试将一些数据传递给另一个活动,但是当我单击按钮时我需要传递数据,而不是启动新活动,当我有多个过去的数据时,启动新活动并查看所有内容我以前通过的。

这个过程类似于一个购物车,添加产品然后你看到购物车列表的另一个活动。

我一直在尝试使用 SharePrerences,但我只传递了一个数据。

final SharedPreferences mSettings = this.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = mSettings.edit();    
editor.putString(NOMBRE_TAG, tvNotas.getText().toString());
editor.putString(PRECIO_TAG, pantalla.getText()+"");
editor.commit();

使用 putExtra 我认为它不起作用,因为我不知道我会传递多少数据

Intent intent = new Intent(this, NAME.class);
intent.putextra("SOMETHING","value");
startActivity(intent);
String data = getIntent().getExtras().getString("SOMETHING");

而且我不知道其他形式可以做到这一点。

过程类似

【问题讨论】:

  • 为什么不能使用 Intent 的 putExtra 方法发送?
  • 因为我不知道我会传递多少数据
  • 您应该知道为了移动或触发新活动而传递的数据。只有你知道它已经结束,所以可以告诉活动要启动。

标签: android android-intent android-activity sharedpreferences cart


【解决方案1】:

当您使用共享偏好时,每个“键”都像您的标签 (NOMBRE_TAG,PRECIO_TAG) 只会保存一项。 这意味着,每次您使用此键保存项目时,它都会替换旧项目。

我推荐使用 SQLITE 数据库。

这里有一些如何开始的例子:

Android SQLite Example

【讨论】:

    【解决方案2】:

    您可以使用静态类还是单例?这样,您可以从第一个活动中放入您想要的任何内容,并从第二个活动中检索它。唯一的缺点是它无法在应用程序重新启动后继续存在。

    【讨论】:

      【解决方案3】:

      使用putParcelableArrayList将所有数据作为数组列表传递---

          @Override
          public void onSaveInstanceState(final Bundle outState) {
          outState.putParcelableArrayList("data", myData);
          super.onSaveInstanceState(outState);
          }
      

      然后要获取这些数据,只需使用----

      ArrayList<String> myData = new ArrayList<String>();
      
      @Override
         public View onCreateView(LayoutInflater inflater, ViewGroup container,
                  Bundle savedInstanceState) 
         {
              super.onCreateView(inflater, container, savedInstanceState);
      
              if (savedInstanceState != null) {
      
                  try
                  {
                     myData = savedInstanceState.getParcelableArrayList("data");
                  }
      
              }
      
              myData.add(0, tvNotas.getText().toString());
              myData.add(1, pantalla.getText()+"");
          }
      

      【讨论】:

      • 您将数据放在共享首选项中并从 saveInstanceState 中获取?什么鬼?
      • @IlyaDemidov - 对不起,别打扰。是一个快速的错误。谢谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多