Trying to simply get a Spinner going in my Application but the lines (commented out, the app works fine without these 2 lines) give me errors every time I try to start the Activity. I setup an Array in Strings.XML to be used in conjunction with the Spinner to view the data.
My XML contains a Spinner like so:
<Spinner
android:id="#+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
In Strings.XML I have my Array:
<string-array name="spinner_array">
<item>Mercury</item>
<item>Venus</item>
<item>Earth</item>
<item>Mars</item>
<item>Jupiter</item>
<item>Saturn</item>
<item>Uranus</item>
<item>Neptune</item>
</string-array>
My Main Activity, 2 lines that are commented cause error.
public class BusPurchase extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.spinner_array, android.R.layout.simple_spinner_item);
super.onCreate(savedInstanceState);
//adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//spinner.setAdapter(adapter);
setContentView(R.layout.activity_bus_purchase);
}
Log Cat Displays this:
http://chopapp.com/#cbz5r823
call setContentView before accessing views from xml layout as:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bus_purchase); // set layout here
Spinner spinner = (Spinner) findViewById(R.id.spinner);
//..your code here
}
because you are trying to access views before setting layout for Activity
You are getting a Null Pointer on your references to spinner (R.id.spinner) because you are trying to reference items in your layout before you inflate the layout. Try calling setContentView(R.layout.activity_bus_purchase); first thing in your onCreate() method and see if that doesn't fix it.
Related
I have an android spinner that allows the user to select a translation. I can tap the spinner and it will reveal a list with available translations, but when I select an item in the list it will not appear in the spinner and neither does the onItemSelected method get called.
Here is the xml code for the spinner:
<Spinner
android:id="#+id/trans_list"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_toRightOf="#+id/chap_list"
android:layout_weight="1" />
Here is the relevant code for initiating the spinner. (edit) This code is ran from inside a Fragment class and not from my MainActivity class:
trans_spinner = v.findViewById(R.id.trans_list);
ArrayAdapter<String> adapter = new ArrayAdapter<>(v.getContext(), android.R.layout.simple_spinner_dropdown_item, translations);
trans_spinner.setAdapter(adapter);
trans_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String translation = trans_spinner.getItemAtPosition(trans_spinner.getSelectedItemPosition()).toString();
Log.d("trans", translation);
Toast.makeText(view.getContext(), translation, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Log.d("test", "1");
}
});
trans_spinner.setSelection(1);
Neither the onItemSelected() or onNothingSelected() method gets called when I select an item. I found this page describing an issue very similar to mine:
Android Spinner will not launch OnItemSelected and current selected item is not displayed in Spinner
However the user did not present a clear solution to their problem so it doesn't help me much.
I am not sure if it is relevant, but the items in the spinner are taken from an online webpage that provides JSON data to fill the spinner. This seems to work, as the options do appear in the spinner list. The issue is that upon selecting one of them, the spinner appears empty and the listener doesn't do anything.
So I found out that the issue was actually because of how I obtained the list of strings to put inside the spinner. As mentioned in the original post, I am loading the string values from a webpage in JSON format. I'm using the Retrofit2 API for this.
The problem was caused by the fact that I was downloading this data and then initializing the spinner both in the onCreateView() method of my fragment. What I did to fix it is I created a new method that initializes the spinner, and then I would call it from the onResponse() method used by the Retrofit API. This means that it doesn't initialize the spinner until after it has finished downloading/populating the list of strings.
<Spinner
android:id="#+id/planets_spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
f the available choices for your spinner are pre-determined, you can provide them with a string array defined in a string resource file:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="planets_array">
<item>Mercury</item>
<item>Venus</item>
<item>Earth</item>
<item>Mars</item>
<item>Jupiter</item>
<item>Saturn</item>
<item>Uranus</item>
<item>Neptune</item>
</string-array>
</resources>
With an array such as this one, you can use the following code in your Activity or Fragment to supply the spinner with the array using an instance of ArrayAdapter:
Spinner spinner = (Spinner) findViewById(R.id.spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.planets_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
When the user selects an item from the drop-down, the Spinner object receives an on-item-selected event.
To define the selection event handler for a spinner, implement the AdapterView.OnItemSelectedListener interface and the corresponding onItemSelected() callback method. For example, here's an implementation of the interface in an Activity:
public class SpinnerActivity extends Activity implements OnItemSelectedListener {
...
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
}
The AdapterView.OnItemSelectedListener requires the onItemSelected() and onNothingSelected() callback methods.
Then you need to specify the interface implementation by calling setOnItemSelectedListener():
Spinner spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);
If you implement the AdapterView.OnItemSelectedListener interface with your Activity or Fragment (such as in the example above), you can pass this as the interface instance.
Java Code
public class MainActivity extends AppCompatActivity {
Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = findViewById(R.id.spinner);
List<String> translations = new ArrayList<>();
translations.add("string1");
translations.add("string2");
translations.add("string3");
translations.add("string4");
translations.add("string5");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, translations);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Object getPosition = parent.getItemAtPosition(position);
String value = getPosition.toString();
Toast.makeText(getActivity(), value, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
XML Code
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/spinner">
</Spinner>
Add this code after init adapter
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
And to get the selected item inside onItemSelected
translations.get(position)
I'm new to android and want to populate listview items that have id as value and string as caption.
All I could find searching was that they suggest using string array like:
<string-array name="test">
<item>first item</item>
<item>second item</item>
</string-array>
What i'm looking for is something like:
<string-array name="test">
<item value="1">first item</item>
<item value="2">second item</item>
</string-array>
just like the option tags of a select in html
Create a new Activity (this will make a xml file (layout) and a Java class.
On the layout, create a Layot that has a ListView on int:
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:orientation=”vertical” >
<ListView
android:id=”#+id/itemList”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:entries="#array/test"
/>
On your activity, you have to:
Create a ListView variable
Map your view on the XML on this variable
Get a list of Strings from your resource array-adapter
Instanciate an Adapter (an object that you have to set on your listview to get your list (in your case, of strings) and add them in your recycler view. You can create a customized class for your adapter it, but when dealing with Strings, you can use a simple one called ArrayAdapter).
Set your adapter on your ListView object
To do all of those things, you put this in your code:
public class MyActivity extends Activity {
// Creating variable
ListView listView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Mapping with your XML view
listView = (ListView) findViewById(R.id.itemList);
/// Getting list of Strings from your resource
String[] testArray = getResources().getStringArray(R.array.test);
List<String> testList = Arrays.asList(test);
// Instanciating Adapter
ArrayAdapter<String> adapter = new ArrayAdapter<>(getBaseContext(),
android.R.layout.simple_list_item_1, testList);
// setting adapter on listview
listview.setAdapter(adapter);
}
}
This will help you to retrieve string by position..
String[] some_array = getResources().getStringArray(R.array.your_string_array)
I have been going through spinners for my application but I don't know where to declare the items that are to be shown in the spinner i.e either I declare them in the string.xml or in my main_activity like this ..
String[] data = { "Hello", "There", "I", "Am", "Taking", "Values" };
Which method is best to use and why?
After declaring values in resources tag in strings.xml like below:
<string-array name="spinner_values">
<item>a</item>
<item>b</item>
</string-array>
you can use entries attribute in spinner tag in your xml layout, instead of use it pro-grammatically in java file. Like below:
<Spinner
android:id="#+id/my_spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/spinner_values" />
Declaring the array in string.xml is better because:
If you want to translate your app into another language, you just
need this one file which has all the arrays and strings that your app uses.
If you have to make any changes to any string/array, you know by default where to look for(All at one place).
Re-use is possible using this way. In any other activity you can just use from there, instead of declaring again.
you can try in this way ....
public void addItemsOnSpinner1() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
List<String> list = new ArrayList<String>();
list.add("Small");
list.add("Medium");
list.add("Large");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter);
}
public void addListenerOnSpinnerItemSelection() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
apply = (Button) findViewById(R.id.apply);
spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
apply.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(String.valueOf(spinner1.getSelectedItem()).equals("Small"))
{
// your code
}
if(String.valueOf(spinner1.getSelectedItem()).equals("Medium"))
{
// your code
}
else if(String.valueOf(spinner1.getSelectedItem()).equals("Large"))
{
// your code
}
}
});
If content of your spinner is fixed then declare it in String.xml . its best practice
You should declare array in strings.xml
<string-array name="data">
<item>Hello</item>
<item>There</item>
<item>I am</item>
<item>Taking</item>
</string-array>
and obtain values in activity
String [] array =getResources().getStringArray(R.array.data);
this is what I am trying to do.
I have a listview that is populated from a xml resource file saved in /values/menu.xml
it has this code in it:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="menuchoices">
<item name="pv">Present Value</item>
<item name="fv">Future Value</item>
<item name="bond">Bond Pricing</item>
</string-array>
</resources>
So far so simple. Then my Main.java file looks like this: (adapted from other listview questions here)
public class Main extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
getResources().getStringArray(R.array.menuchoices)
));
}
public void onListItemClick(ListView partent, View v, int position, long id) {
if ("pv".equals(getResources().getStringArray(R.array.menuchoices)[position])){
setContentView(R.layout.presentvalue);
}
}
}
Basically I read that launching new activities all the time is not the best practice so i just told the if statement to change the contentview. The problem is -- Nothing happens when i click on the first item in the list. i also tried substituting "pv" with "Present Value" but it did not help either.
I think this i beacuase i took the code from posts like this here List View selection to start a new Activity) but I don't know how to change it so it works with the external xml resource file.
This should be a simple fix right?
THanks in advance
Max
P.s. all the other stuff works (the presentvalue.xml file is in the layout folder and the list is properly displayed when i run the app)
EDIT //
here is the problematic line
public void onListItemClick(ListView parent, View v, int position, long id) {
if (view.getText().toString().equals("Present Value")){
startActivity(new Intent(Main.this, PresentValue.class));
}
}
The function onListItemClick() is typically used with a ListActivity. There are a couple fixes to this:
Change the line extends Activity to extends ListActivity.
Remove your ListView definition.
Change your main.xml id from #+id/listView1 to #android:id/list
add implements OnItemClickListener in your class definition after extends Activity
Change the function onListItemClick to onItemClick
Try moving your menuchoices block:
<string-array name="menuchoices">
<item name="pv">Present Value</item>
<item name="fv">Future Value</item>
<item name="bond">Bond Pricing</item>
</string-array>
Into your string.xml file, then we can simplify your adapter (assuming you did changes #1 above):
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
R.array.menuchoices));
We can also condense how you test the menu choice:
"pv".equals(getResources().getStringArray(R.array.menuchoices)[position])
Becomes:
view.getText().toString().equals("Present Value");
(Minor point, you have a typo in the word "parent")
How's that?
I want to know about basics to create ListView.
How many methods to use the create ListView.
Hey i too new to android, there are two different ways to implement listview. 1) we can assign listview by giving values in main.xml.
<ListView android:id="#+id/ListView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
public class ListviewExample extends Activity
{
private ListView lv1;
private String lv_arr[]={"Android","iPhone","BlackBerry","AndroidPeople"};
#Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
lv1=(ListView)findViewById(R.id.ListView01);
// By using setAdpater method in listview we an add string array in list.
lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , lv_arr));
}
}
2) In second method, we can assign values in string.xml.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="countries_array">
<item>Bahrain</item>
<item>Bangladesh</item>
<item>Barbados</item>
<item>Belarus</item>
<item>Belgium</item>
<item>Belize</item>
<item>Benin</item>
</string-array>
</resources>
String[] countries = getResources().getStringArray(R.array.countries_array);
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, countries));
This tutorial should guide you
http://developer.android.com/resources/tutorials/views/hello-listview.html
Take a look at the ApiDemos sample code, particularly the group of examples dealing with list views (follow the Views link and scroll down).