简体   繁体   中英

how can i pass my instance variable througout my entire activity?

I am trying to make a custom list view adapter. In my public void function I am trying to set the adapter.. (after make the list from the web

This is in my onCreate():

rowItems = new ArrayList<RowItem>();
listView = (ListView) findViewById(R.id.list);
CustomListViewAdapter adapter = new CustomListViewAdapter(this,R.layout.activity_main, rowItems);
listView.setAdapter(adapter);

My question is: how can I make my custom listview adapter adapter variable available throughout my activity????

Here is a snippet from when i set my names city and icon and i try to set my adapter

item.setTitle(p.getString("name"));
item.setDesc(p.getString("city"));
item.setImageId(p.getString("icon"));
rowItems.add(item);

listView.setAdapter(adapter);

but eclipse can't find it. I even tried to recall the instance in the public void function with no luck....

Any suggestions?

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    new ReadWeatherJSONFeedTask().execute();

    rowItems = new ArrayList<RowItem>();
    listView = (ListView) findViewById(R.id.list);
    CustomListViewAdapter adapter =
        new CustomListViewAdapter(this,R.layout.activity_main, rowItems);
    listView.setAdapter(adapter);
}

Move the declaration into a class field, like this:

public class MyActivity extends Activity{

    CustomListViewAdapter adapter;

    ...

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new ReadWeatherJSONFeedTask().execute();

        rowItems = new ArrayList<RowItem>();

        listView = (ListView) findViewById(R.id.list);

        adapter = new CustomListViewAdapter(this,R.layout.activity_main, rowItems);

        listView.setAdapter(adapter);

    }


}

Class fields are accessible in all methods of a class. It's all about "scope". Declaring the adapter inside onCreate limits it's scope (it's visibility) to that method and classes declared within it.

BTW, you don't say why you are trying to "reset" your adapter but usually, you should only set it once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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