简体   繁体   English

从使用外部类的ArrayList获取变量

[英]Get a variable from an ArrayList that uses external class

I have an ArrayList called results that uses the class ItemObjects when I want to add an item in results . 我有一个名为resultsArrayList ,当我想在results添加项目时,该类使用ItemObjects类。 My problem is that I cannot manage to retrieve a specific String from an item. 我的问题是我无法从项目中检索特定的字符串。

The class code is: 类代码为:

public class ItemObjects {
    private String mText1;
    private String mText2;


    public ItemObjects(String text1, String text2){
        mText1 = text1;
        mText2 = text2;
    }

    public String getmText1() {
        return mText1;
    }

    public void setmText1(String mText1) {
        this.mText1 = mText1;
    }

    public String getmText2() {
        return mText2;
    }

    public void setmText2(String mText2) {
        this.mText2 = mText2;
    }
}

And I use the following code to add an item into the ArrayList : 我使用以下代码将一个项目添加到ArrayList

ArrayList results = new ArrayList<ItemObjects>();
//THis part goes inside a for using i as increment;
ItemObjects obj = new ItemObjects(type, sender);
results.add(i , obj); 

I have tried several things to retrieve the data such as: 我尝试了几种方法来检索数据,例如:

String type =  ItemObjects.getmText1();

or: 要么:

String type= results.get(i);

the first try, only retrieves the mText1 from the first item, and the second is an object and I dn't know how i should get the mText1 from it. 第一次尝试,仅从第一项中检索mText1,第二次是一个对象,我不知道该如何从中获得mText1。

Any help would be appreciated :) 任何帮助,将不胜感激 :)

For adding the Value 用于增加价值

ArrayList<ItemObjects> results = new ArrayList<ItemObjects>();
ItemObjects obj = new ItemObjects(type, sender);
results.add(obj);

For getting the Value 为了获得价值

for (int i=0, i<result.size(); i++)
{
    String type =  results.get(i).mText1;
    String sender=  results.get(i).mText2; 

    Toast.makeText(this, "" + type, Toast.LENGTH_LONG).show();
    Toast.makeText(this, "" + sender, Toast.LENGTH_LONG).show();

}

Change 更改

ArrayList results = new ArrayList<ItemObjects>();

to

ArrayList<ItemObjects> results = new ArrayList<>();

Then results.get() will return ItemObjects . 然后results.get()将返回ItemObjects

Or you can simply cast your current result.get() to ItemObjects 或者,您可以将当前的result.get() ItemObjectsItemObjects

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM