类实例化不起作用

时间:2014-04-13 13:25:35

标签: java android

我有一个类,我想实例化它以使用它的setter和getter方法。但由于某些原因,我无法设置其他外部类的值。

这是基类Fila.java:

public class Fila {

    int icon;
    String name;



    public int getIcon() {
        return icon;
    }

    public void setIcon(int icon) {
        this.icon = icon;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

在这里,我尝试将值设置为此类:

public class agregar extends Activity implements OnItemClickListener{

    ListView lview3;
    MyAdapter adapter;
    private ArrayList<Object> itemList;
    private Fila fila;
    SharedPreferences settings;
    public static final String PREFS_NAME = "MyPrefsFile";
    int img_ah;
    String nom_ah;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        this.setContentView(R.layout.principal);

        settings = getSharedPreferences(this.PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();

        editor.putBoolean("hasLoggedIn", false);
        editor.commit();

        img_ah = settings.getInt("icono",0);
        nom_ah = settings.getString("nombre",null);

        prepareArrayLits();
        lview3 = (ListView) findViewById(R.id.lista);
        adapter = new MyAdapter(this, itemList);
        lview3.setAdapter(adapter);
        lview3.setOnItemClickListener(this);


    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
        // TODO Auto-generated method stub
       Fila bean = (Fila) adapter.getItem(position);

    }


    public void prepareArrayLits()
    {
        itemList = new ArrayList<Object>();
       AddObjectToList(img_ah, nom_ah);

    }


    public void AddObjectToList(int imagen, String nombre)
    {


        fila = new Fila();
        fila.setIcon(imagen);
        fila.setName(nombre);
        itemList.add(fila);
    }
}

当我想要得到这个值时,没有任何东西出现。

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

将类实例化为全局私有(例如

)时
private Fila fila = new Fila();

然后在方法中使用该inscance

public void foo() {
   fila.setIcon(icon);
   fila.getIcon();
}

或在方法/或构造函数中进行实例化

public void foo() {
   Fila fila = new Fila();

   fila.setIcon(icon);
   fila.getIcon();
}

此外,如果您有字段变量,请在它们旁边放置一个访问修饰符

private int icon;
private String name;

protected int icon;
protected String name;

取决于您对这些字段的访问限制