Right place for code of populating spinner - android

I have form with a spinner control and a text box; and tables are stored in the SQLite database.
I am populating spinner inside onCreate method of activity. Is it right place to call database query & update ui?
Depending upon value user selects from spinner, i have to give auto suggestion in text box. (which control i can use instead of text box, i want to force user to select from list coming from database.)
Also i have heard about fragment, can anyone guide me is it helpful for improving performance of the application.

it would be better u call a function inside onCreate method and fill the spinner value in that function like
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.spinner);
addItemsOnSpinner1();
}
public void addItemsOnSpinner1() {
Spinner spinner = (Spinner) findViewById(R.id.spinnerSource);
List<String> list = new ArrayList<String>();
list.add("sony");
list.add("apple");
list.add("samsung");
list.add("htc");
list.add("blackberry");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Collections.sort(list);
spinner.setAdapter(dataAdapter);
And for using fragment use this linkWhen should I use fragments in Android applications ? Why to use fragments?

You must populate your spinner with data from that moment on you want to provide it to the user. So just in the onCreate of the containing Activity.
For more info I guess Spinner | Android Developers .
Fragments give you the ability to create independent parts for your UI. For example a Fragment which contains a List and another showing detail information to the selected element. On Tablet you could display both beside each other. On a small display handheld device you have to display the list and on item selection the details. With Fragments you have reusability. Take a look here Fragments | Android Developers - I recommend to read this if you will use Fragments. It will save you the trouble.

Related

Why do we use single adapter per class in android?

I have just started learning android using Big Nerd Ranch Guide. In a project, we were to implement a listView and get the data from an array using an ArrayAdapter, as the crime objects were stored in some list.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActivity().setTitle(R.string.crimes_title);
mCrimes = CrimeLab.get(getActivity()).getCrimes();
ArrayAdapter<Crime> adapter =
new ArrayAdapter<Crime>(getActivity(),
android.R.layout.simple_list_item_1,
mCrimes);
setListAdapter(adapter);
}
After that, we were to create custom list to display the title as well as the checkbox and date so we created a custom layout. Now, we used a different adapter for that purpose.
private class CrimeAdapter extends ArrayAdapter<Crime> {
public CrimeAdapter(ArrayList<Crime> crimes) {
super(getActivity(), 0, crimes);
}
My question is why cant we use the same adapter that we used earlier?I mean we can just give it new values or create a new object.I searched the internet and found that we can create multiple adapters with some restrictions. why we extend it to ArrayAdapter? cant we just do it like we did previously by creating the adapter?
Please explain in detail, as I have just started.
Thanks.
Let us talk about the list view adapter implementation in android first of all in your first example you used the default implementation of listview adapter in android which provide you with list view of text
but most of the time this is not enough for your user interface you want to add an image a checkbox like in your second example so android OS gives you the ability to make your own custom cell (each row in list) that's why you would find yourself in a need to extend array adapter
in your first example you used
android.R.layout.simple_list_item_1
which is a layout containing only textview
and you provide a data source mCrimes
so when you extend array adapter you do the same you provide your own layout which represent the cell and a data source which will populate your list
hope that clarify it for you and welcome aboard :)

Change text of listview in onItemClick (listview is filled by a string-array/arrayAdapter)

I want to change the text in my listview.
In my onCreate I fill my listview and setting an OnItemClicklistener:
onCreate:
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, trainingstage);
setListAdapter(adapter);
ListView listView = getListView();
listView.setOnItemClickListener(this);
onItemClick:
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
TextView tv = (TextView)view.findViewById(android.R.id.text1);
switch (position) {
case 0:
tv.setText("Hello");
IF I CLICK TEXT SHOULD CHANGE!
break;
That works fine, but if I restart the activity the old text is back. I want to change the text forever, if I click on the listitem!
You can achieve this by two options:
Easier way
Change text in trainingstage and set string array to STATIC!
Better way
If you want to save the text after click, you need some kind of database to store the change. Either use sqlite if you want to save different text. If number of text is fixed, better to use SharedPreferences. You would also need to restore the text from here to set the TextView on Activity start.
ListViews as the name implies is the VIEW where data is presented to users. You use your ArrayAdapter to populate the ListView from your DATA. The DATA in this example is your trainingstage String list.
This is a good data separation technique used all over Android. If you just change the textview anything else that uses that data wont be updated, you have only updated the view. What you need to do is actually update the DATA layer(trainingstage) which in turn will be passed to the adapter then rendered by the list view.
Without knowing exactly where and how you get trainingstage data it's hard to give you a suggestion on how to do that but a simple example would be:
in onItemClick
trainingstage.get(position) = "My New String";
parent.notifyDatasetChanged();
This probably won't persist when you restart your activity. You will need to do additional steps to save the STATE of your DATA. Aashish talks briefly about that in an above post.

Save the state of listview when the application closes (after turning the screen)

I need to save the state of listview when the application closes (after turning the screen). SQL does not want to use. I know that there are standard methods: SharedPreferences, onSaveInstanceState. My code is:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//-----------listitem------------
ListView listView = (ListView) findViewById(R.id.listView1);
catnames = new ArrayList<String>();
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, catnames);
listView.setAdapter(adapter);
listView.setAdapter(adapter);
}
And put Adapter
catnames.add(0, name);
adapter.notifyDataSetChanged();
Maybe I should not use ArrayAdapter? Help please ...
I want to save catnames)
ps application extends SherlockActivity.
You need to use the SQLite datababse to persist the data. When the application closes, save the data to the database. When the application starts, retrieve the data from the database. All you need to learn is simple SQL :)
This should give you a head start: http://www.vogella.com/tutorials/AndroidSQLite/article.html
Update:
If you are looking to use onSavedInstanceState() then you need to use Bundles which are, in simple terms, key-value pairs.
Once you get your adapter to populate the data, just use the setSelection() or the smoothScrollToPosition() to go to the element you want. This implies that you current position of the list when your screen goes off. For that, you need the getFirstVisiblePosition() method. This will be saved in your Bundle and this is what you will use when your screen comes back on.

Android ListAdapter or Possibly ListView Updating Text at Runtime

Hello folkes I have this little problem for which I cannot find a suitable answer looking around the web and on these forums. Please don't direct me to articles in which people have requested list view text color changes at run time, as I read lots of them and not found one to help me out.
I have a simple ListView that displays an array of String objects via the use of a ListAdapter.
I need to update some of ListView Strings at run time, based on their contents. Using a global reference to the list adapter used in the lists views creation I can get the contents of each list view String using following code below.
However, in addition to retrieval I'd like to be able to modify each string in turn, then put it back in the same index position and have the list view reflect the changes. How?
for (int x = 0; x <= listAdapter.getCount();x++)
{
Object o = this.listAdapter.getItem(x);
if (o.getClass().getSimpleName().equals("String"))
{
String s = (String) o;
s = modifyString(s);
//s is the string I want to modify then put back in the same place.
}//end if
}//end for
As far as I know you cannot change the items in an Adapter - unless you are using a custom Adapter (by extending a BaseAdapter etc...)
So, I think you will have to:
make sure you Adapter's constructor takes in the data structure that holds your strings
make sure your data structure is global
make the changes in that data structure whenever you need to
call myAdapter.notifyDataSetChanged();
This will tell adapter that there were changes done in the list and listview should be recreated.
And after your listview is renewed you can even take the user back to the index by:
list.setSelection(positionWhereTheUserClicked);
I hope this helps, let me know if you need more code references.
Here is some code
private ArrayList<String> results = new ArrayList<String>(); //global
private BaseAdapter searchAdapter = new BaseAdapter (results, this); //global
private void updateResults(final ArrayList<String> updatedList){
results = updatedList;
final ListView list = (ListView)findViewById(R.id.search_results);
list.setAdapter(searchAdapter);
list.setOnItemClickListener(new ListView.OnItemClickListener(){
// implementation of what happens when you click on an item //
});
searchAdapter.notifyDataSetChanged();
}
This code works just fine on my end, I hope it helps.
Just stumbled on this problem and found a solution.
I'm using a
m_ListAdapter = new SimpleAdapter(this, m_List, R.layout.option_list_row, columns, renderTo);
Each item in my listView is a manu option causing a dialog to show, once data is received through the dialog, all I have to do is just create a new SimpleAdapter with an updated ArrayList that includes the new data, then just setAdapter to the new adapter.
The ListView will update instantly.

I need help populating a listview from a remote source in android

I've searched far and wide for this answer and can't seem to find it.
I'm looking to populate a very simple 3 line listview, no more then 5-6 words per line at the most inside of my android app.
I'm currently using a base adapter and a string array to enable the actual text to show up on the screen.
I want to have the ability to update the information inside of my listview remotely using
some sort of means whether that's xml, SQLite, plain text, etc and then have that hosted file populate my listview.
Can anyone here help me to figure out how to do this? I'm still pretty new to android development so please go easy on me. Hopefully this question wont be too hard answer and also not too difficult to enable for a newbie like myself.
If the most you're going to ever have in there is just 3 lines of text, I think a SQLite DB may be a bit much for your situation. I'd look into using a Typed Array.
Here's a link to the Android Dev Guide on this subject:
http://developer.android.com/guide/topics/resources/more-resources.html#TypedArray
Here's a code sample:
public class YourListActivity extends ListActivity {
String[] mTestArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create an ArrayAdapter to contain your items
ArrayAdapter<String> adapter;
mTestArray = getResources().getStringArray(R.array.yourArray);
// Assign your array to an adapter with your layout file
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mTestArray);
// Assign the adapter to this ListActivity
setListAdapter(adapter);
}
}
EDIT
Just realized that your data will be on a remote server, so this approach may not work for you, but it can still give you an idea of how to take your data once received from your remote server and place it into a ListView.

Categories

Resources