在活动中将数据保存在 ArrayList 中。

huangapple go评论82阅读模式
英文:

Save data in ArrayList in activity

问题

我是一名新的安卓程序员。
我有4个活动:A、B、C、D。
顺序是 A -> B -> C -> D -> A 以及 A -> D,使用按钮控制。
我想要在 D 活动中保存数据到 ArrayList 中。
问题是,当我从 D 切换到 A,然后再回到 D,ArrayList 中的数据没有保存。
D 活动的代码如下:

public class SchedulerActivity extends AppCompatActivity {

    public String name = "";
    public String number = "";
    public String date = "";
    public String hour = "";
    public ArrayList<EventClass> scheduler = new ArrayList<>();

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scheduler);
        Bundle extras = getIntent().getExtras();

        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(SchedulerActivity.this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                startActivity(intent);
                finish();
            }
        });
        if (extras != null) {
            String sender = extras.getString("sender");
            if(sender.compareTo("Hours") == 0) {
                name = extras.getString("name");
                number = extras.getString("number");
                date = extras.getString("date");
                hour = extras.getString("hour");
                Date real_date = new Date();
                SimpleDateFormat formatter1 = new SimpleDateFormat("dd/MM/yyyy");
                try {
                    real_date = formatter1.parse(date);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                scheduler.add(new EventClass(real_date, name, number, "", hour));
                for (EventClass event : scheduler){
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                            LinearLayout.LayoutParams.MATCH_PARENT,
                            LinearLayout.LayoutParams.WRAP_CONTENT);
                    final TextView t = new TextView(this);
                    t.setText(event.toString());
                    LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linearLayout);
                    linearLayout.addView(t, params);
                }

            }
            else{
                for (EventClass event : scheduler){
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                            LinearLayout.LayoutParams.MATCH_PARENT,
                            LinearLayout.LayoutParams.WRAP_CONTENT);
                    final Button btn = new Button(this);
                    final TextView t = new TextView(this);
                    t.setText(event.toString());
                    LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linearLayout);
                    linearLayout.addView(btn, params);
                }
            }
        }
    }

当 C->D 发生时,我想要修改我的 ArrayList 并打印它,当 D->A 发生时,我只想打印它。我知道可以使用 SharedPreferences 实现,但对于第一步,我想使用 ArrayList 来实现。最好的方法是什么?

英文:

I am a new android programmer.
I have 4 activities: A B C D.
The order is A -> B -> C -> D -> A and A -> D using buttons.
I want to save data in ArrayList that is in activity D.
The problem is that when I move from D to A and come back to D, the data in the ArrayList didn't save.
Code for D activity here:

public class SchedulerActivity extends AppCompatActivity {
public String name = &quot;&quot;;
public String number = &quot;&quot;;
public String date = &quot;&quot;;
public String hour = &quot;&quot;;
public ArrayList&lt;EventClass&gt; scheduler = new ArrayList&lt;&gt;();
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scheduler);
Bundle extras = getIntent().getExtras();
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(SchedulerActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
finish();
}
});
if (extras != null) {
String sender = extras.getString(&quot;sender&quot;);
if(sender.compareTo(&quot;Hours&quot;) == 0) {
name = extras.getString(&quot;name&quot;);
number = extras.getString(&quot;number&quot;);
date = extras.getString(&quot;date&quot;);
hour = extras.getString(&quot;hour&quot;);
Date real_date = new Date();
SimpleDateFormat formatter1=new SimpleDateFormat(&quot;dd/MM/yyyy&quot;);
try {
real_date = formatter1.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
scheduler.add(new EventClass(real_date, name, number, &quot;&quot;, hour));
for (EventClass event : scheduler){
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
final TextView t = new TextView(this);
t.setText(event.toString());
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linearLayout);
linearLayout.addView(t, params);
}
}
else{
for (EventClass event : scheduler){
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
final Button btn = new Button(this);
final TextView t = new TextView(this);
t.setText(event.toString());
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linearLayout);
linearLayout.addView(btn, params);
}
}
}
}

I want to change my ArrayList when C->D occurs and print it and when D->A occurs I just want to print it. I know that I can with SharedPreferences but for the first step, I want to do this with ArrayList.
What's the best way to do this?

答案1

得分: 1

创建静态对象不是一个好的方法。所以,您可以使用Android活动堆栈来替代使用静态Arraylist。Android活动存储在活动堆栈中。返回到以前的活动可能意味着两件事。

您从另一个活动中使用startActivityForResult打开了新活动。在这种情况下,您可以只需从您的代码中调用finishActivity()函数,它会将您带回到先前的活动。
跟踪活动堆栈。无论何时您使用意图启动新活动,您都可以指定一个意图标志,比如FLAG_ACTIVITY_REORDER_TO_FRONT或FLAG_ACTIVITY_PREVIOUS_IS_TOP。您可以使用这个来在应用程序的活动之间进行切换。

英文:

Creating static objects is not a good approach. So you can use android activity stack in-place of using static Arraylist. Android activities are stored in the activity stack. Going back to a previous activity could mean two things.

You opened the new activity from another activity with startActivityForResult. In that case you can just call the finishActivity() function from your code and it'll take you back to the previous activity.
Keep track of the activity stack. Whenever you start a new activity with an intent you can specify an intent flag like FLAG_ACTIVITY_REORDER_TO_FRONT or FLAG_ACTIVITY_PREVIOUS_IS_TOP. You can use this to shuffle between the activities in your application.

答案2

得分: 0

调度程序是SchedulerActivity中的非静态字段,这意味着它的存在与活动实例相关联。当活动实例被销毁时,例如当屏幕方向被销毁或者切换到另一个活动时,所有非静态字段也会被销毁。您可以通过在字段之前添加static关键字来更改这一点:

public static ArrayList<EventClass> scheduler = new ArrayList<>();

现在,您的字段与类本身关联,而不是实例,这意味着它不会随实例一起被销毁。但这也意味着它在所有实例之间共享,并且必须在类体外部使用类名引用它:

EventClass event = SchedulerActivity.scheduler.get(0);
英文:

The scheduler is a non-static field in the SchedulerActivity which means that its existance is tied to the instance of the activity. When the activity instance is destroyed, and that might happen for example when the screen orientation is destroyed or you move to another activity, so are all its non-static fields. You can change that by adding a static keyword before your field:

public static ArrayList&lt;EventClass&gt; scheduler = new ArrayList&lt;&gt;();

Now, your field is tied to the class itself, not the instance, whitch means it wont be destroyed along with the instance. But it also means that it is shared between all instances and must be referenced with the class name outside of the class body:

EventClass event = SchedulerActivity.scheduler.get(0)

答案3

得分: 0

一个好的方法是将数据保存在本地数据库中,比如Room。你需要在跳转到新的活动之前进行保存,然后在 OnResume() 中将其取回。

英文:

A good approach is saving your data in a local database, like Room. You need to save before go to new activity, and get it back on OnResume().

huangapple
  • 本文由 发表于 2020年8月19日 01:50:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/63474068.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定