spinner defined in main activity is null - android

I have populated a spinner with items in xml file using entries option. I have defined the spinner in main activity class as "s1". In debug mode i found that s1 is null. That is why setOnItemSelectedListener is not working for spinner. When an item is selected, toast message is not displayed. I am giving mainactivity.java, activity_main.xml and strings.xml files.
MainActivity.java
public class MainActivity extends ActionBarActivity{
String[] presidents;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
presidents = getResources().getStringArray(R.array.presidents);
Spinner s1 = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.presidents, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
if(s1 != null){
s1.setAdapter(adapter);
s1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0,
View arg1, int arg2, long arg3)
{
int index = arg0.getSelectedItemPosition();
Toast.makeText(getBaseContext(), presidents[index], Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> arg0){
}
});
}
}
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
activity_main.xml
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Spinner
android:id="#+id/spinner1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawSelectorOnTop= "true"
android:entries="#array/presidents" />
strings.xml
<resources>
<string-array name = "presidents">
<item>eisenhower</item>
<item>kennedy</item>
</string-array>
</resources>

your setContentView(R.layout.activity_main); is wrong, use R.layout.fragment_main instead

You have initialized your Spinner at the class level. At this point, the Spinner object is null. You should instead initialize your Spinner within the onCreate() method. So you can have it like this:
Spinner s1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // Only here is the layout inflated and only after this can Android see the Spinner
s1 = (Spinner) findViewById(R.id.spinner);
// Other statements
}

Try this way,hope this will help you to solve your problem.
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
MainActivity.java
public class MainActivity extends ActionBarActivity {
private Spinner s1;
private String[] presidents;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
s1 = (Spinner) findViewById(R.id.spinner1);
presidents = getResources().getStringArray(R.array.presidents);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,R.array.presidents, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
if(s1 != null){
s1.setAdapter(adapter);
s1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0,View arg1, int arg2, long arg3)
{
Toast.makeText(MainActivity.this, presidents[arg2], Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> arg0){
}
});
}
}
}

Related

Spinner not working (Android)

I have made a simple demo for spinners in android with one activity. I have tried the following code but it's not working. when I run this app on my phone it shows:- "Unfortunately the app has stopped working "
MainActivity.Java
public class MainActivity extends AppCompatActivity implements
AdapterView.OnItemClickListener {
Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner=findViewById(R.id.spinner);
ArrayAdapter Adapter=ArrayAdapter.createFromResource
(this,R.array.days,R.layout.support_simp
le_spinner_dropdown_item);
spinner.setAdapter(Adapter);
spinner.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long
l) {
TextView mytext=(TextView)view;
Toast.makeText(this,"you selected"+mytext.getText(),
Toast.LENGTH_SHORT).show();
}
}
XML code
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.rakib.myapplication.MainActivity">
<Spinner
android:id="#+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="91dp">
</Spinner>
use this
String[] myarray =getResources().getStringArray(R.array.days);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,R.layout.support_simp le_spinner_dropdown_item, myarray);
(or)
ArrayAdapter<String> adapter = new ArrayAdapter<String>
(this, android.R.layout.simple_spinner_item,
myarray); //selected item will look like a spinner set from XML
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
Use this code to get values from the spinner.
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Toast.makeText(this,"you selected"+parent.getItemAtPosition(pos),Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> parent) {
}
});

Android: Can't seemed to assign variable with new value

I am having trouble with the variable: URL_STRING. I can't seem to add a value from another variable to URL_String. It just null for some reason. Your assistance would be appreciated.
public class HomeScreen extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
ListView listView;
Spinner spinner;
EditText search;
Button bt;
String URL_STRING;
String entity;
String term;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
listView = (ListView) findViewById(R.id.listView);
spinner = (Spinner) findViewById(R.id.spinner);
search = (EditText) findViewById(R.id.search);
term = search.getText().toString();
bt = (Button) findViewById(R.id.searchBtn);
ArrayAdapter<CharSequence> entityAdapter = ArrayAdapter
.createFromResource(this, R.array.Entities,
android.R.layout.simple_spinner_item);
spinner.setAdapter(entityAdapter);
spinner.setOnItemSelectedListener(this);
}
This is where I am having trouble. URL_STRING is still null
public void addURL(View view) {
if(entity == "Select" && term != null){
URL_STRING = String.format(getResources().getString(R.string.url1),term);
SearchDownloader searchDownloader = new SearchDownloader(this);
searchDownloader.execute();
listView.setVisibility(View.VISIBLE);
}else if(term == null){
Toast.makeText(getApplicationContext(), "Please enter a search term",
Toast.LENGTH_LONG).show();
}else{
URL_STRING = String.format(getResources().getString(R.string.url2), term, entity);
SearchDownloader searchDownloader = new SearchDownloader(this);
searchDownloader.execute();
listView.setVisibility(View.VISIBLE);
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
entity = String.valueOf(spinner.getSelectedItem());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
entity = null;
}
}
I am not very sure about the adapter and the array being assigned to it.
I have created something which are looking for, Kindly try this, code is available on Github as well have a look at it if i may have missed something. to load the imgae I am using a library called picasso which you can easily import by adding following code to the dependencies block in the build.gradle file like this
compile 'com.squareup.picasso:picasso:2.5.2'
and you would be able to use picasso
public class SpinnerTestTwoActivity extends Activity {
private Spinner url_Spinner;
private Button load_image_Button;
private ImageView url_image_ImageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spinner_test_two);
initializeUI();
}
private void initializeUI() {
url_Spinner = (Spinner) findViewById(R.id.SpinnerTestTwoActivity_url_spinner);
load_image_Button = (Button) findViewById(R.id.SpinnerTestTwoActivity_load_image_button);
url_image_ImageView = (ImageView) findViewById(R.id.SpinnerTestTwoActivity_image_from_url_imageView);
String[] url_array = getResources().getStringArray(R.array.url_images);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.simple_spinner_dropdown_item, url_array);
url_Spinner.setAdapter(adapter);
url_Spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String image_url = (String)url_Spinner.getItemAtPosition(position);
Picasso.with(getApplicationContext()).load(image_url).into(url_image_ImageView);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
activity_spinner_test_two.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="8dp"
android:gravity="center"
android:orientation="vertical">
<Spinner
android:id="#+id/SpinnerTestTwoActivity_url_spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="4dp" />
<Button
android:id="#+id/SpinnerTestTwoActivity_load_image_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:text="Load Image"
android:textAllCaps="false" />
<ImageView
android:id="#+id/SpinnerTestTwoActivity_image_from_url_imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_margin="4dp"
android:layout_weight="1"
android:scaleType="fitCenter" />
</LinearLayout>
url_images
This is the array which you will make in the arrays.xml file which is in the res/values directory
<array name="url_images">
<item>https://material-design.storage.googleapis.com/publish/material_v_4/material_ext_publish/0Bx4BSt6jniD7emgtQk5rdEE3bW8/style_icons_system_intro_principles_simple.png</item>
<item>https://material-design.storage.googleapis.com/publish/material_v_4/material_ext_publish/0Bx4BSt6jniD7MGhHV055eGk0R2M/style_icons_system_intro_principles_intuitive.png</item>
<item>https://material-design.storage.googleapis.com/publish/material_v_4/material_ext_publish/0Bx4BSt6jniD7MG80dmpHT0RidGs/style_icons_system_intro_principles_actionable.png</item>
<item>https://material-design.storage.googleapis.com/publish/material_v_4/material_ext_publish/0Bx4BSt6jniD7blViQzF0azNqZU0/style_icons_system_intro_principles_consistent.png</item>
<item>https://material-design.storage.googleapis.com/publish/material_v_4/material_ext_publish/0Bx4BSt6jniD7VXlvR05VSWhPZTg/style_icons_system_grid_geometry2.png</item>
<item>https://material-design.storage.googleapis.com/publish/material_v_4/material_ext_publish/0Bx4BSt6jniD7SUV1b2Z3b3NBazA/style_icons_system_best_do1.png</item>
<item>https://material-design.storage.googleapis.com/publish/material_v_4/material_ext_publish/0Bx4BSt6jniD7azQ4WThPb25NOGc/style_icons_system_best_do3.png</item>
</array>
Output

Spinner, setOnItemSelectedListener is not working for Spinner when items are selected

setOnItemSelecctedListener is not working for the spinner. Following is the code in mainactivity.java. I have populated spinner in xml file using entries option. When an item is selected, toast message is not displayed showing the item selected.
public class MainActivity extends ActionBarActivity{
String[] presidents;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
presidents = getResources().getStringArray(R.array.presidents);
Spinner s1 = (Spinner) findViewById(R.id.spinner1);
if(s1 != null){
s1.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> arg0,
View arg1, int arg2, long arg3)
{
int index = arg0.getSelectedItemPosition();
Toast.makeText(getBaseContext(), presidents[index], Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> arg0){
}
});
}
}
}
activity_main.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="10dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<!-- Spinner Element -->
<Spinner
android:id="#+id/spinner1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:entries="#array/presidents"
android:drawSelectorOnTop="true"
/>
</LinearLayout>
Strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">My First App</string>
<string-array name = "presidents">
<item>eisenhower</item>
<item>kennedy</item>
</string-array>
</resources>
That's because your Spinner s1 is null.
Your xml code:
<Spinner
android:id="#+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawSelectorOnTop="true"
/>
In Activity, you use id spinner1
Spinner s1 = (Spinner) findViewById(R.id.spinner1);
So here s1 will be null.
And you check this:
if(s1 != null){
s1.setAdapter(adapter);
...
}
Just change your id to spinner here:
Spinner s1 = (Spinner) findViewById(R.id.spinner);
So s1 won't be null, and it will be populated with data using adapter.
Hope it helps.
NOTE:
If you have spinner1 in a fragment, you would need to do something like:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v= inflater.inflate(R.layout.fragment_main, container, false);
Spinner s1 = (Spinner) v.findViewById(R.id.spinner1);
return container;
}

Setting color for textview dynamically using spinner?

I want to create one textview, the colour of that text is to be changed by the user by selecting colour from spinner object.
The spinner object contains list of colours, that is options for user to change the colour of textview dynamically.
Excuse for my english and help me out..
Try this way,hope this will help you to solve your problem.
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"/>
<Spinner
android:id="#+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"/>
</LinearLayout>
strings.xml
<array name="colorname">
<item>Red</item>
<item>Yellow</item>
<item>Green</item>
<item>Blue</item>
<item>Pink</item>
</array>
<array name="colorcode">
<item>#FF0000</item>
<item>#ffff00</item>
<item>#00ff00</item>
<item>#0000ff</item>
<item>#FF0080</item>
</array>
MainActivity.java
public class MainActivity extends Activity {
private Spinner spinner;
private TextView textview;
private ArrayList<String> colorNameList;
private ArrayList<String> colorCodeList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview = (TextView) findViewById(R.id.textview);
spinner = (Spinner) findViewById(R.id.spinner);
colorNameList = new ArrayList<String>(Arrays.asList(getResources().getStringArray(R.array.colorname)));
colorCodeList = new ArrayList<String>(Arrays.asList(getResources().getStringArray(R.array.colorcode)));
final ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, colorNameList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
textview.setTextColor(Color.parseColor(colorCodeList.get(position)));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
YourSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id)
{
YourTextView.setTextColor(getResources().getColor(R.color.some_color));
// your code here
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
It would be nice if you've tried searching on Stack Site.
public class MainActivity extends ActionBarActivity {
private TextView text;
private Spinner spin;
ArrayList al;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text=(TextView)findViewById(R.id.textView1);
spin=(Spinner)findViewById(R.id.spinner1);
al=new ArrayList();
al.add("RED");
al.add("BLUE");
ArrayAdapter adapter=new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_activated_1,al);
spin.setAdapter(adapter);
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
switch(arg2)
{
case 0:
text.setText("srikanth");
text.setTextColor(Color.RED);
break;
case 1:
text.setText("SRIkANTH BLUE");
text.setTextColor(Color.BLUE);
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
I hope it helps you

ListActivity Android

Does somebody know why ListActivity won't work and when I change it to Activity base class, with slight changes it works, but onClick() method still doesn't. I'm trying only to put some strings into the list... Here's the code:
public class TestDataBaseActivity extends Activity implements OnClickListener {
private CommentsDataSource datasource;
ListView m_list;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
datasource = new CommentsDataSource(this);
datasource.open();
List<Comment> values = datasource.getAllComments();
m_list = (ListView) findViewById(R.id.listView1);
// Use the SimpleCursorAdapter to show the
// elements in a ListView
ArrayAdapter<Comment> adapter = new ArrayAdapter<Comment>(this,
android.R.layout.simple_list_item_1, values);
m_list.setAdapter(adapter);
Button add = (Button)findViewById(R.id.button_add);
Button delete = (Button)findViewById(R.id.button_delete);
add.setOnClickListener(this);
delete.setOnClickListener(this);
}
// Will be called via the onClick attribute
// of the buttons in main.xml
#Override
public void onClick(View view) {
#SuppressWarnings("unchecked")
ArrayAdapter<Comment> adapter = (ArrayAdapter<Comment>) m_list.getAdapter();
Comment comment = null;
switch (view.getId()) {
case R.id.button_add:
String[] comments = new String[] {
"Cool", "Very nice", "Hate it"
};
int nextInt = new Random().nextInt(3);
// Save the new comment to the database
comment = datasource.createComment(comments[nextInt]);
adapter.add(comment);
break;
case R.id.button_delete:
if (m_list.getAdapter().getCount() > 0) {
comment = (Comment) m_list.getAdapter().getItem(0);
datasource.deleteComment(comment);
adapter.remove(comment);
}
break;
}
adapter.notifyDataSetChanged();
}
#Override
protected void onResume() {
datasource.open();
super.onResume();
}
#Override
protected void onPause() {
datasource.close();
super.onPause();
}
}
Here is XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".TestDataBaseActivity" >
<Button
android:id="#+id/button_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/add_new" />
<Button
android:id="#+id/button_delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/button_add"
android:text="#string/delete_first" />
<ListView
android:id="#+id/listView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#id/button_add"
android:padding="15dp" >
</ListView>
</RelativeLayout>
I edited now to extend Activity, now "only" onClick() dont work...
Thanks in advance!
For a ListActivity, you should override onListItemClick() instead:
#Override
protected void onListItemClick(ListView lv, View v, int position, long id){
}
Since you are extending ListActivity you need to have an Listview with android:id="#android:id/list".
if you want to use #+id/lst_id then dont extend ListActivity, just extended Activity.
And whenever you are using Listview you need to implement OnItemClickListener not OnClickListener.
and override the default OnItemClick method
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
}
you should implement OnClickListener
public class TestDatabaseActivity extends ListActivity implements
OnClickListener{
try following code a simple list activity
public class MainActivity extends ListActivity implements OnItemClickListener {
ListView listView;
static final String[] SPORTS = {"Shuttle Badminton", "Tennis", "FootBall",
"Basket Ball","Table Tennis", "Chess","Hockey"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listView = getListView();
//setting adapter
listView.setAdapter(new ArrayAdapter<String>(getApplicationContext(),R.layout.list_item,SPORTS));
listView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
TextView tv = (TextView)view.findViewById(R.id.text1);
Toast.makeText(getApplicationContext(),"Position is: "+position,Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),"Text is: "+tv.getText().toString(),Toast.LENGTH_SHORT).show();
}
}
here list_item is an xml having following code
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/text1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textColor="#android:color/black"
android:padding="10dp" />
Use this code for list activity and modify row xml according to your needs.
hope this helps..
This is what's troubling you:
ArrayAdapter<Comment> adapter = (ArrayAdapter<Comment>) m_list.getAdapter();
Build a global object for your adapter instead. ( Declare it before onCreate() )

Categories

Resources