Android: problems with getSelectedItem on a spinner - java

I have a Spinner, and put the selected item in the body of a mail.
this is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_modulo);
Spinner spinnerTaglia = (Spinner) findViewById(R.id.spinnerTaglia);
// Create an ArrayAdapter using the string array and a default spinner layout ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.Taglie, 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);
spinnerTaglia.setPrompt("Seleziona la taglia!");
// Apply the adapter to the spinner
spinnerTaglia.setAdapter(new NothingSelectedSpinnerAdapter(
adapter,
R.layout.contact_spinner_row_nothing_selected,
// R.layout.contact_spinner_nothing_selected_dropdown, // Optional
this));
final String taglia = spinnerTaglia.getSelectedItem().toString();
Button btnCompilaOrdine = (Button) findViewById(R.id.btnCompilaOrdine);
btnCompilaOrdine.setOnClickListener(new View.OnClickListener(){
public void onClick(View arg0) {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"MAIL#gmail.com"});
i.putExtra(Intent.EXTRA_SUBJECT, "MAIL OBJECT");
i.putExtra(Intent.EXTRA_TEXT , "Taglia: "+taglia);
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(Modulo.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
});
}
The application start correctly in the emulator and the debugger show me nothing (I'm using Android Studio) but when i click on the button that take me in this activity the application crash and the Android Studio's Debugger show me a java.lang.NullPointerException in the row:
final String taglia = spinnerTaglia.getSelectedItem().toString();
how can i fix this?

getSelectedItem() returns null if there is nothing selected on your spinner and calling toString() is making your application crash. Get rid of
final String taglia = spinnerTaglia.getSelectedItem().toString();
and in your onClick do:
if (spinnerTaglia.getSelectedItem() == null) {
return;
}
String taglia = spinnerTaglia.getSelectedItem().toString();
// the other code

Move the line
final String taglia = spinnerTaglia.getSelectedItem().toString();
to inside your OnClickListener
Currently, you're trying to read the selected item before anything has been selected. You should also ensure that getSelectedItem() isn't returning null because, unless you enable / disable the btnCompilaOrdine button (when an item is selected), the user can press the button without selecting an item in the spinner.

Maybe you should OnItemSelectedListener inseatead of a button.
Android Spinner

It seems that Item is returned with NULL value try to Invoking the method from a null object.
TheNullPointerException is a RuntimeException and thus, the Javac compiler does not force you to use a try-catch block to handle it appropriately.
Hope this will help you to solve your issue.
for further reference visit the link below:-
http://examples.javacodegeeks.com/java-basics/exceptions/java-lang-nullpointerexception-how-to-handle-null-pointer-exception/

Your are getting the selected item before the actual rendering of the spinner. It depends on device to device that how fast it renders the screen.
Rather then getting the selected item in getSelectionItem() in the onCreate() method try out to do it in the onClickListener() of your Button.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_modulo);
Spinner spinnerTaglia = (Spinner) findViewById(R.id.spinnerTaglia);
// Create an ArrayAdapter using the string array and a default spinner layout ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.Taglie, 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);
spinnerTaglia.setPrompt("Seleziona la taglia!");
// Apply the adapter to the spinner
spinnerTaglia.setAdapter(new NothingSelectedSpinnerAdapter(
adapter,
R.layout.contact_spinner_row_nothing_selected,
// R.layout.contact_spinner_nothing_selected_dropdown, // Optional
this));
Button btnCompilaOrdine = (Button) findViewById(R.id.btnCompilaOrdine);
btnCompilaOrdine.setOnClickListener(new View.OnClickListener(){
public void onClick(View arg0) {
//Get the Selected item from the spinner
final String taglia = spinnerTaglia.getSelectedItem().toString();
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"MAIL#gmail.com"});
i.putExtra(Intent.EXTRA_SUBJECT, "MAIL OBJECT");
i.putExtra(Intent.EXTRA_TEXT , "Taglia: "+taglia);
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(Modulo.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
});
}

mSpinner.setSelected(true);
If you implement this with your spinner, it will not give null.

Related

Set up spinner depends on which button is clicked

What I want to do is change the spinner values depends on the button clicked. For example, the spinner value will be Japan, Thailand show in the 2nd activity if I clicked the Asia button. However, the spinner value did not show up after I clicked the Asia button and start 2nd activity.
This is my code in activity 1:
spinnerDestination=findViewById(R.id.spinnerDestination);
Bundle extras=getIntent().getExtras();
int i=extras.getInt("asia",-1);
if(i==2)
{
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.asia, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerDestination.setAdapter(adapter);
}
code in activity 2:
btn.add(findViewById(R.id.buttonAsia));
btn.add(findViewById(R.id.buttonEurope));
btn.add(findViewById(R.id.buttonOceanic));
for(int i=0;i<btn.size();i++)
{
int j=i;
btn.get(i).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(getApplicationContext(),MainActivity2.class);
intent.putExtra("destination", j);
startActivity(intent);
}
});
}
Did I miss anything or did it wrongly in the code. I'm new to android actually.

AutoCompleteTextView wont work as EditText did

I replaced an EditText with an AutoCompleteTextView in my app to make things a little more user friendly, but I am having an error.
In the app, the user types in the name of a plant, and then clicks a button to be taken to a new activity where some information about the plant is displayed.
The error: the app crashes after I press the button to be taken to the next activity after the user types in the name of the plant. This didnt happen when I still had an EditText. Perhaps I am using the AutoCompleteTextView wrong?
Heres the relevant code:
public class Main2Activity extends AppCompatActivity {
AutoCompleteTextView edit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
//this is the AutoComplete
AutoCompleteTextView edit = (AutoCompleteTextView) findViewById(R.id.et_item);
//this is the list of suggestions for the AutoComplete
String[] items = getResources().getStringArray(R.array.items_array);
java.util.Arrays.sort(items);
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
edit.setAdapter(adapter);
//this is the method that is called when the button is pressed
public void find(View view) {
String name = edit.getText().toString();
//basically, whatever is typed into the AutoComplete is turned into a string, and
//if the string matches one of the existing plants, the user is taken to
//the next activity
if(name.equalsIgnoreCase("Sunflower")){
Intent intent = new Intent(this, Sunflower.class);
startActivity(intent);
}
else if(name.equalsIgnoreCase("Cactus")){
Intent intent = new Intent(this, Cactus.class);
startActivity(intent);
}
Can anyone see why this does not work?
Change below:
AutoCompleteTextView edit = (AutoCompleteTextView) findViewById(R.id.et_item);
To:
edit = (AutoCompleteTextView) findViewById(R.id.et_item);
Your autocomplete textview scope is limited to onCreate() and
edit.getText().toString();
You are trying to get text from it which is not initialized yet. So it will get null pointer exception.

Simple validation of editText not working (Eclipse)

I'm a beginner to Java and I want to validate an EditText. What I have in mind: my editText has to match "helloworld". When you press a button this has to be validated. If this is true--> go to a new class in which I have a setContentView to display a new layout.
If the text which I have just typed does not match "helloworld", it should do nothing. It seems very easy but since I'm a beginner you would help me BIGTIME!
Here's most of the logic handled. You will need to fill in your actual layout id's and make your launch intent. Put this code in your onCreate method in the activity with the layout that contains the edit text box
EditText editText = (EditText)findViewById(R.id.editTextBox);
Button btn = (Button)findViewById(R.id.checkBtn);
btn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
if(editText.getText().toString().equalsIgnoreCase("helloworld")){
//Launch activity with new view
}
}
});
In an activity (or android class) you have to get the instance of your EditText. Your edit text has an id, and you can get it using R. R is the resources for your app.
EditText t = (EditText)findViewById(R.id.<Name of your textfield>);
Then you can get the value of that textfield and compare it
t.getText().toString().equals("helloworld");
will return true or false. If you dont care about the case of the letters use
t.getText().toString().toLowerCase().equals("helloworld");
you will need an onClickListener for your button, check out the android api
http://developer.android.com/reference/android/view/View.OnClickListener.html
in your onCreate, when declaring your submit button, add a listener
Button submit = (Button) findViewById(R.id.submit);
submit.setOnClickListener(submitListener);
make a new onClick listener and fire an Intent to start a new activity
View.OnClickListener submitListener = new View.OnClickListener() {
public void onClick(View v) {
//if string matches helloworld fire new activity
Intent newActivity = new Intent();
startActivity(newActivity);
}
};
// create a reference to the EditText in your layout
EditText editText = (EditText)findViewById(R.id.editTextIdInLayout);
// create a reference to the check Button in your layout
Button btn = (Button)findViewById(R.id.buttonIdInLayout);
// set up an onClick listener for the button reference
btn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String userInput = editText.getText().toString(); // get the user input
if (userInput.equals("helloworld") // see if the input is "helloworld"
{
setContentView(R.layout.newLayout); // change the content view
}
}
});

Android adapter.add() crashing my application

in android application, i'm filling my spinner with some data coming from EditText object.
And when i'm trying to add it with adapter.add(somestring) method it crashes, so i need help.
...here's the code
public class OptionsMenu extends Activity implements View.OnClickListener{
Spinner users;
EditText input;
Button add,remove;
public static String filename = "savedData";
SharedPreferences sharedData;
String stringUsers;
ArrayAdapter<CharSequence> adapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.options_menu);
Create();
sharedData = getSharedPreferences(filename, 0);
}
private void Create() {
// TODO Auto-generated method stub
users = (Spinner) findViewById(R.id.sp_op_users);
input = (EditText) findViewById(R.id.tb_op_inputUsers);
add = (Button) findViewById(R.id.bt_op_add);
remove = (Button) findViewById(R.id.bt_op_remove);
add.setOnClickListener(this);
remove.setOnClickListener(this);
//------------ADAPTER-----------------
adapter = ArrayAdapter.createFromResource(this, R.array.users,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
users.setAdapter(adapter);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.bt_op_add:
if (!input.getText().toString().equals("")) {
CharSequence inputData = input.getText().toString();
adapter.add(inputData);
adapter.notifyDataSetChanged();
users.setAdapter(adapter);
}
input.setText("");
users.setSelection(Adapter.NO_SELECTION);
break;
case R.id.bt_op_remove:
break;
}
}
Not very sure why you are getting the error but your if condition is wrong.
Change the following line:
if (input.getText().toString() != "")
to
if (!input.getText().toString().equals(""))
You don't compare strings using a = sign.
EDIT
Maybe you could first get the array from the resource file and create a local version of it:
String[] usersList=getResources().getStringArray(R.array.users);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, usersList)
and use this usersList as the list of data for your adapter.
You created the adapter using createFromResource() and provided it with the data from your resource. If you do it this way the list is fixed and you cannot add to or remove elements from it. This is why it crashed when you try to call adapter.add().
If you want to have the spinner contain dynamic data, then you'll have to add all the elements to it using add() and not create it from a resource.
EDIT: Add code example
in onCreate() we create and initialize the spinner adapter
List<String> items = ... // These are your items you get from a resource or read
// from a file or whatever
// Create the adapter, initializing it with the list of items, attach to spinner
adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item);
for (String item : items) {
adapter.add(item);
}
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
users.setAdapter(adapter);
in onClick(), to add an item to the spinner:
case R.id.bt_op_add:
if (!input.getText().toString().equals("")) {
CharSequence inputData = input.getText().toString();
adapter.add(inputData);
// You shouldn't need to reset the adapter on the spinner, nor call
// notifyDataSetChanged() here
}
input.setText("");
users.setSelection(Adapter.NO_SELECTION);
break;

Options Menu on Spinner

I'm looking for a way to add items to a spinner from within the spinner item list dialog.
Ideally, I could hit the menu button and select an option to add, prompt the user with an edittext dialog and update the item list. Is there a way to make the options menu accessible on a dialog?
I thought I might need to create an activity but then how do I make it look like a spinner item list dialog and how would I get it to show up when the spinner is clicked?
All I'm trying to do is add an unobtrusive way to launch a prompt to add items to the spinner item list from within the dialog. Any ideas?
How about allowing them to long-click the list and handling the long click event?
Spinner s=(Spinner) findViewById(R.id.yourspinner);
s.setOnLongClickListener(new OnLongClickListener(){}...
public class Main extends Activity {
/** Called when the activity is first created. */
private ArrayList<String> array_spinner;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner s = (Spinner) findViewById(R.id.Spinner01);
array_spinner=new ArrayList<String>();
array_spinner.add("value");
array_spinner.add("value 2");
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, array_spinner);
adapter.setNotifyOnChange(true);
s.setAdapter(adapter);
s.setLongClickable(true);
s.setOnLongClickListener(new OnLongClickListener(){
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
array_spinner.add("value 3");
return false;
}}
);
}
}

Categories