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);
}

Answers


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.


Need Your Help

Change labels of panels with two conditions

r lattice

I have a lattice graph with two conditions: one condition (x1) has 4 levels and one has 2 levels (x2). The graph has a stripes for each variable x1 and x2:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.