5

在我的 android 应用程序中,我希望能够将字符串值添加到我在主要 android 活动中声明的静态数组列表中。逻辑是这样的:

1)当您单击按钮并开始活动时。在 oncreate 方法上,我想将作为当前活动的类的名称保存为字符串值。例如:

String className = "com.lunchlist.demo";

分配此值后,我想立即将此字符串值添加到我在主要 android 活动中声明的静态 ArrayList(意味着第一个启动的 android 活动)添加值后

我做了这样的事情:

static String List<String> members = new ArrayList<String>();

这是在我的主要活动中声明的。现在,当我单击一个按钮开始另一个活动时,我使用它在我的 oncreate 方法中将当前活动的字符串类名添加到我的数组列表中:

  String className = "com.lunchlist.demo" 
  members.add(className);

我现在的问题是,这会将字符串值添加到我的数组列表中并保存以备后用吗?例如,如果我单击三个不同的按钮,这会将三个不同的 className 值添加到 arraylist。这是否会存储一个字符串值,该字符串值将为我的成员数组列表保存三个不同的字符串值?如何检查我的数组列表中的每个项目以查看在启动新活动时是否正在添加值?

我问这个是因为我需要检索它并使用共享首选项存储这些值,然后检索它们并使用作为启动活动的类的字符串值启动意图。我让活动从一个类名的字符串值开始,我只是在存储它们时遇到了麻烦。

4

3 回答 3

22

Answering to all of your questions:

would this add the string value to my arraylist and save it for later use?

Yes. Your code seems perfect to do it with no problems.

For example If I click three different buttons this will add three different className values to the arraylist. Would this then store a string value that would hold three different string values for my members arraylist?

If you tell to your button's onClickListener to add a string to the members ArrayList then it will be done and no matter if you already had previously added that member to the ArrayList because array lists don't care if there is duplicated data or not.

How would I check each item in my arraylist to see if the values are being added when a new activity is started?

You have to iterate your array list with a for or a for-each cicle and then print that member name as a log entry.

  • For-each cicle

    for (String member : members){
        Log.i("Member name: ", member);
    }
    
  • Simple For cicle

    int listSize = members.size();
    
    for (int i = 0; i<listSize; i++){
        Log.i("Member name: ", members.get(i));
    }
    

If you try to print/ log a value which index is out of range, i.e., i < 0 || i >= listSize then a IndexOutOfBoundsException will be thrown and crash your app.

于 2012-07-15T17:34:14.173 回答
6

使用 Java 1.5 中引入的 For-Each 进行迭代:

for (String s : members){
    Log.d("My array list content: ", s);
}

有关详细信息,请参阅此链接:

http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html

于 2012-07-15T17:05:39.183 回答
2

Try this:)

We can implement by these two way

  1. foreach

  2. for loop

String type arraylist

ArrayList<String> limits = new ArrayList<String>(); // String arrayList 
                
               

Using foreach

                for (String str_Agil : limits)   // using foreach 
                {
                    Log.e("Agil_Limits - " , str_Agil);
                }

Using forloop

                for(int agil=0; agil<=limits.size(); agil++) // using for loop
                {
                    Log.e("Agil_Limits - " , limits.get(agil).toString());
                }
于 2016-12-05T09:48:52.780 回答