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.
Related
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.
I want to display a spinner on the screen only if a radio button is clicked but I couldn't find a solution. Here is my current code.
RadioGroup radio_grp=(RadioGroup) rootView.findViewById(R.id.radio_grp);
RadioButton rb1 = (RadioButton) rootView.findViewById(R.id.radioButton1);
RadioButton rb2 = (RadioButton) rootView.findViewById(R.id.radioButton2);
View.OnClickListener button1Listener = new View.OnClickListener() {
public void onClick(View v) {
// Toast message etc.
}
};
View.OnClickListener button2Listener = new View.OnClickListener() {
public void onClick(View v) {
// I want to show a spinner if they click the second radio button
}
};
rb1.setOnClickListener(button1Listener);
rb2.setOnClickListener(button2Listener);
return rootView;
First initialize the spinner like:
Spinner mSpinner = (Spinner) rootView.findViewById(R.id.mSpinner);
Of course, before that, add a spinner in your layout somewhere, and set it's android:visibility="invisible" if the first selected radio button is 1, else set it to visible. Then add listeners:
View.OnClickListener button2Listener = new View.OnClickListener() {
public void onClick(View v) {
// I want to show a spinner if they click the second radio button
if (v.getId() == R.id.radioButton1) mSpinner.setVisibility(View.INVISIBLE);
if (v.getId() == R.id.radioButton2) mSpinner.setVisibility(View.VISIBLE);
}
};
If you don't want it to occupy any space once it's not on the screen, use View.GONEinstead of View.INVISIBLE. Refer here for the difference.
Put ((Spinner) findViewById(R.id.mySpinner)).performClick(); in second radiobutton click
View.OnClickListener button2Listener = new View.OnClickListener() {
public void onClick(View v) {
((Spinner) findViewById(R.id.mySpinner)).performClick();
}
};
I have problems with my list . I had an Activity I get some Data from.
The data must accessed in variables in my class :
Mylist.java class
public String Job,Ship,Location,Shift,Date;
public String workingHour;
Mylist(String job,String loc,String shp,String shft,String dat,String wh){
Job=job;
Location=loc;
Ship=shp;
Shift=shft;
Date=dat;
workingHour=wh;
}
and by pressing Save Button The list must add an item.My problem is when I add another items the list have only one item How to fix this ?
Adding Class :
AddOredit.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_oredit);
final ArrayList<Mylist>list =new ArrayList<>();
final ArrayList<String> Job=new ArrayList<>();
String selecteditem1, selecteditem2,getlocation,getship,getdate,gethours;
Spinner type=(Spinner)findViewById(R.id.s1);
Spinner shift=(Spinner)findViewById(R.id.s2);
EditText location=(EditText)findViewById(R.id.loc);
EditText ship=(EditText)findViewById(R.id.ship);
EditText date=(EditText)findViewById(R.id.date);
EditText workinghours=(EditText)findViewById(R.id.hours);
Button Save = (Button) findViewById(R.id.editbtn);
Button cancel = (Button) findViewById(R.id.cancelbtn);
selecteditem1 = type.getSelectedItem().toString(); //for first spinner
selecteditem2 = shift.getSelectedItem().toString();//for second spinner
getlocation=location.getText().toString();
getship=ship.getText().toString();
getdate=date.getText().toString();
gethours=workinghours.getText().toString();
list.add(new Mylist(selecteditem1,getlocation,getship,selecteditem2,getdate,gethours));
Log.e(TAG, String.valueOf(list.size()));
for(int i=0;i<list.size();i++){
Job.add("Job "+(i+1));
}
//When pressing save Button
Save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//list.add(new Mylist(selecteditem1, getlocation, getship, selecteditem2, getdate, gethours));
Intent intent = new Intent(AddOredit.this, MainActivity.class);
intent.putStringArrayListExtra("MyList", Job);
startActivity(intent);
}
});
}
MainActivity.java this class
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView lv= (ListView) findViewById(R.id.listView);
Button ADD=(Button)findViewById(R.id.addbtn);
Button DELETE=(Button)findViewById(R.id.deletebtn);
Button PROFILE=(Button)findViewById(R.id.profilebtn);
Intent intent=getIntent();
ArrayList<String> Job ;
Job=intent.getStringArrayListExtra("MyList");
if(Job!=null){
ListAdapter adapter= new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, Job);
lv.setAdapter(adapter);
//when user click on add button
}
ADD.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//go to AddOreditpage
Intent i = new Intent(MainActivity.this, AddOredit.class);
startActivity(i);
}
});
**Note :- ** Add Button is for Adding items in the list and Save Button is for saving data entered at AddOredit class.
**Note :- ** By clicking Add Button , getting to the AddOredit Activity .
By Clicking Save Button, getting back to the main activity with the item added
You are assigning a new List for list object on your second activity created. Try to assign the list with an existing object and add your new object.
EDIT:
Try to Declare this globally as,
private static ArrayList list =new ArrayList<>();
and with in onCreate() remove it. Let me know if it still do not work.
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.
What I'm trying to do is simple, I have a spinner with a few items, edittext and a button. I want to be able to select a certain item with a spinner and then type a certain value to edittext and then click a button. According to which spinner item I have selected earlier a textview will then change in the activity.
public void submitButtonClick (View submit){
Spinner s1 = (Spinner)findViewById(R.id.spinner1);
Button b1 = (Button)findViewById(R.id.button2);
if (b1.performClick())
{
switch (){
}
}
}
This is what I came up with so far, if I click button b1, the following switch statement should start (in case item 1 is selected, do a certain thing, etc.) but I don't know how to achieve this. If someone could help I would appreciate it. Thank you
This is what I have so far:
public void submit (View v){
Button b1 = (Button)findViewById(R.id.button2);
final Spinner s1 = (Spinner)findViewById(R.id.spinner1);
final Context context = this;
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = s1.getSelectedItemPosition();
switch (position){
case 0:
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setTitle("Warning");
alertDialogBuilder.setMessage("Please choose an item from the list");
alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
Bifrost.this.finish();
}
});
AlertDialog spinnerError = alertDialogBuilder.create();
spinnerError.show();
break;
case 1:
break;
}
}
});
}
The code gives no errors and app starts normally but when I select the first item and then click the button nothing happens. Did I do something wrong creating the dialog?
You first need to set an onClickListener to your button, and in this you need to get the selected item of the spinner.
b1.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
int position = s1.getSelectedItemPosition();
switch(position){
case 0: //first item
break;
case 1: //second item
break;
}
}
});
You can use one of the following methods to get the spinner's selected item.
spinner.getSelectedItem()
spinner.getSelectedItemPosition()
Which one you use, has to do with how you load items into your spinner.
Follow this link for more info on those methods.
You can do something like this. you need to set a onClickListener to the button. when the button is clicked then the onClick method will be called. At that method check the selected item of the spinner.. Forexmple
Spinner s1 = (Spinner)findViewById(R.id.spinner1);
Button b1 = (Button)findViewById(R.id.button2);
b1.setOnclickListener(new onClickListener(){
public void onCLick(View v){
switch(s1.getSelectedItemPosition()){
case 0:
// do something
`enter code here`break
..........
}
}
}
);
I just tried to give a conceptual idea the code is not exact , but this is how you should do it. So my suggestion is before implementing this leanr the basic features of buttons, spinners, onCLickListeners.
You can assign a listener to your spinner.
s1.setOnItemSelectedListener(new OnItemSelectedListener() {
// will run every time the user select an item from your spinner
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// change your textView here, base on position (index of item selected in spinner)
if (position == 0) {
// user selected the first item in spinner
}
else if (position == 1) {
// user selected the second item in spinner
}
// and so on...
}
});
After that, you can assign another listener (similar way as the code above - anonymous inner class, anonymous declaration and initialization) for your button. It will also have to override onClick etc etc. There are lots of resources online regarding all of this.
Hope this helps!