Android display search results approach
I want to display search result on the screen, i have implemented in such a way that.
From the search form user fill the 'search field' and 'search location' i set values into bean and that bean is static so that i can access it from every where.
Then i start search result screen开发者_StackOverflow中文版 intent using
Intent mainIntent = new Intent(SearchVenueResults.this, SearchResults.class);
startActivity(mainIntent);
on the 'SearchResults' activity 'oncreate' method i load data on the behalf of static bean which values filled from search form and then display data.
@Override
public void onCreate(Bundle savedInstanceState) {
loadDataAndSetupUI();
super.onCreate(savedInstanceState);
}
My question is is it the correct approach to use it or in Android there is another preferable approach ?
any quick idea or quick code is appreciated.
Well, generally, the onCreate
handler of your result screen activity is definitely a good place to do this. However, reading between the lines of your question, there are at least two things I noticed which may cause problems:
First, using a static object to transport values from one activity to another is definitely the wrong approach. That's because for one, there already is a well defined mechanism in Android for exchanging data between contexts, and that's via Bundles and Intents. So, to tell your result activity about the things your user is searching for, do something like this:
Intent mainIntent = new Intent(SearchVenueResults.this, SearchResults.class);
mainIntent.putExtra("search_query", getValueFromSearchBox());
startActivity(mainIntent);
In your SearchResults activity, do this in onCreate:
public void onCreate(Bundle savedInstanceState) {
String searchQuery = getIntent().getExtras().getStringExtra("search_query");
loadDataAndSetupUI(searchQuery);
super.onCreate(savedInstanceState);
}
Moreover, Android behaves pretty much unpredictable with respect to the life-time of static variables. I noticed several times that maintaining a static variable in an activity class does not guarantee that this variable is still valid when launching a new activity, so you should never rely on statics as a means of exchanging data between classes.
Second, you most definitely don't want to implement loadDataAndSetupUI
to run synchronously. Doing so will lock up your UI until the search has terminated, and Android may even decide to kill your app. Use AsyncTask for background jobs instead.
精彩评论