How to get the spinner value not in integer but in character - java

public class MainActivity extends AppCompatActivity {
Spinner spinner;
ArrayAdapter<CharSequence> adapter;
int noc = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner =(Spinner)findViewById(R.id.spinner);
String text= spinner.getSelectedItem().toString();
adapter= ArrayAdapter.createFromResource(this,R.array.Coffee_names,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getBaseContext(),parent.getItemIdAtPosition(position) + " is selected",Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
My app stops when i add " String text= spinner.getSelectedItem().toString(); " to my code but it works fine when i remove this line from the program. But when i select a item from dropdown list it says 4 is selected.
I want it to say the name of the item i selected and not the index value.
Please help.

I think it should be:
Toast.makeText(getBaseContext(), parent.getSelectedItem() + " is selected", Toast.LENGTH_SHORT).show();

Alternative way
final String[] coffeeNames = getResources().getStringArray(R.array.Coffee_names);
spinner.setAdapter(new ArrayAdapter<>(activity, android.R.layout.simple_list_item_1, coffeeNames));
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selectedCoffeeName = coffeeNames[position];
Toast.makeText(getBaseContext(), selectedCoffeeName + " is selected", Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});

Related

App crashes on spinner item click

I have this code for my simple spinner:
private Spinner spnr_gender;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_complete_profile);
//GUI
spnr_gender = (Spinner)findViewById(R.id.spnr_finish_gender);
ArrayAdapter<CharSequence> gender_adapter = ArrayAdapter.createFromResource(this, R.array.strs_gender, android.R.layout.simple_spinner_item);
gender_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnr_gender.setAdapter(gender_adapter);
spnr_gender.setOnItemClickListener((AdapterView.OnItemClickListener) this);
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String selectChoice = adapterView.getItemAtPosition(i).toString();
Toast.makeText(adapterView.getContext(), selectChoice, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
What I want is to toast what the user has selected on the spinner. My string array in the strings.xml:
<string-array name="strs_gender">
<item>Male</item>
<item>Female</item>
</string-array>
When running the app it just crashed.
I can't find anything on the logcat but my suspect is this line spnr_gender.setOnItemClickListener((AdapterView.OnItemClickListener) this);.
How can I fix this?
Use this
spnr_gender.setOnItemSelectedListener(this);
Instead of
spnr_gender.setOnItemClickListener((AdapterView.OnItemClickListener) this);
setOnItemSelectedListener
void setOnItemSelectedListener (AdapterView.OnItemSelectedListener listener)
Register a callback to be invoked when an item in this AdapterView has been selected.
EDIT
Use this
ArrayAdapter<CharSequence> gender_adapter = ArrayAdapter.createFromResource(this, android.R.layout.simple_spinner_item,getResources().getStringArray(R.array.strs_gender));
Instead of this
ArrayAdapter<CharSequence> gender_adapter = ArrayAdapter.createFromResource(this, R.array.strs_gender, android.R.layout.simple_spinner_item);
Spinner example
Use Only (this) context while declaring item click listener
Do not cast with (AdapterView.OnItemClickListener) with it.
Use only
spnr_gender.setOnItemSelectedListener(this);
make it in this fashion
sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
here is the solution
private Spinner spnr_gender;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_complete_profile);
//GUI
spnr_gender = (Spinner) findViewById(R.id.spnr_finish_gender);
ArrayAdapter<CharSequence> gender_adapter = ArrayAdapter.createFromResource(this, R.array.strs_gender, android.R.layout.simple_spinner_item);
gender_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnr_gender.setAdapter(gender_adapter);
spnr_gender.setOnItemSelectedListener((AdapterView.OnItemSelectedListener) this);
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String selectChoice = adapterView.getItemAtPosition(i).toString();
Toast.makeText(adapterView.getContext(), selectChoice, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}

Passing spinner selection between activities

I have 4 activity with spinner inside every activity and this spinner include 3
string data (drop-down selection), when I pass from activity to another one I must pass this selected data inside spinner like if I have chosen data x from the list in the spinner and click in button the selected data must be in second activity spinner as x too.
I read several solutions without any solving. I hope to solve it here and this is my code for spinner and where to put the intent code
public class Page1 extends AppCompatActivity {
Spinner spinner;
ArrayAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page1);
spinner = (Spinner)findViewById(R.id.spinner);
adapter = ArrayAdapter.createFromResource(this,R.array.film_type,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getBaseContext(), parent.getItemAtPosition(position) + " selected", Toast.LENGTH_LONG).show();
switch (position)
{case 0:
btn[0] = (FloatingTextButton) findViewById(R.id.btn);
btn[0].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
double thick = Double.valueOf(editText1.getText().toString());
double width = Double.valueOf(editText2.getText().toString());
}
});
break;
case 1:
btn[0] = (FloatingTextButton) findViewById(R.id.btn);
btn[0].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
} catch (NumberFormatException e) {
//not a double
}
}
});
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
First save the position of selected data from spinner in a String variable,
int positionOfSelectedDataFromSpinner;
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
positionOfSelectedDataFromSpinner= position;
}
Then on button click send intent to Another activity with putExtra
Intent i = new Intent (this, activity2.class);
i.putExtra("position", positionOfSelectedDataFromSpinner);
startActivity(i);
get int from getIntent in another activity
Intent intent = getIntent();
int positionToShowToSpinner = intent.getStringExtra("position");
then set the position to spinner
spinner.setSelection(positionToShowToSpinner);
I think this my solve your problem.
this is the most painless way i can think of:
make a new class or a static member of an existing class but the second solution makes the code less understandable.
public class SpinnerPosHolder{
public static int poition;
}
then in all 4 of them:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
SpinnerPosHolder.position = spinner.getSelectedItemPosition();
For using it:
spinner.setSelection(SpinnerPosHolder.position)
You can do it in this way
String selectedItem=spinner1.getSelectedItem().toString();
And that String you can pass using Intent

Delete item from listview when the item is clicked

I currently have this code to display chosen items in a listview:
public class DisplayOrder extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_order);
bar();
Button btn = (Button) findViewById(R.id.btnHome);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(DisplayOrder.this, Options.class);
startActivity(myIntent);
}
});
}
private void bar() {
ListView lv = (ListView) findViewById(R.id.listViewDisplay);
List<String> itemsOrdered = new ArrayList<String>();
for (Map.Entry<Item, Integer> entry : Datastore.currentTable.getOrder().getItems().entrySet()) {
itemsOrdered.add((entry.getKey().name) + " x " + String.valueOf(entry.getValue()) + " £" + (entry.getKey().price * entry.getValue()));
}
// This is the array adapter, it takes the context of the activity as a
// first parameter, the type of list view as a second parameter and your
// array as a third parameter.
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getBaseContext(), R.layout.activity_display_order, R.id.textView8, itemsOrdered);
lv.setAdapter(arrayAdapter);
}
}
What i want to do is, when I click one of the items, for it to be deleted but Im not sure how to do that. Any guidance would be much appreciated.
You should detect when you click in each item of ListView by setOnItemClickListener.
Then inside this method, just delete the list datasource and notifyDataSetChanged
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView < ? > parent, View view,int position, long id) {
itemsOrdered.remove(position); // remove item at index in list datasource
arrayAdapter.notifyDataSetChanged(); // call it for refresh ListView
Toast.makeText(getApplicationContext(), "remove item at " + position, Toast.LENGTH_LONG).show();
}
});
You have to override the listener “setOnItemClickListener” like this:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
itemsOrdered.remove(item);
arrayAdapter.notifyDataSetChanged();
}
});
This code removes the ítem from the list, but you have to notify the change to the adapter. When the adapter is notified the listview is updated.

Passing a string to another activity in android

I am working on an app and I need to pass the contents of some textviews to a new activity, but I want to save the content I pass while the app is open so that the user can select more items from other activities and send them to the final checkout activity.
right now I have spinners which save the selection to a Textview
public class Americano extends AppCompatActivity {
// MyDBHandler dbHandler;
String result;
TextView tvSize;
Spinner spinner;
int mPos;
String mSelection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_americano);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Spinner spinnerSize = (Spinner) findViewById(R.id.spinner_size);
AdapterView.OnItemSelectedListener listener = new myOnItemSelectedListener();
spinnerSize.setOnItemSelectedListener(listener);
Spinner spinnerSyrups = (Spinner) findViewById(R.id.spinner_syrups);
AdapterView.OnItemSelectedListener listenerSyrups = new myOnItemSelectedListener2();
spinnerSyrups.setOnItemSelectedListener(listenerSyrups);
Spinner spinnerTopping = (Spinner) findViewById(R.id.spinner_toppings);
AdapterView.OnItemSelectedListener listenerTopping = new myOnItemSelectedListener3();
spinnerTopping.setOnItemSelectedListener(listenerTopping);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DBAdapter dbAdapter = new DBAdapter(view.getContext());
}
});
}
public class myOnItemSelectedListener implements AdapterView.OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> parent, View v, int pos, long id) {
Americano.this.mPos = pos;
Americano.this.mSelection = parent.getItemAtPosition(pos).toString();
TextView resultText = (TextView) findViewById(R.id.tvSize);
resultText.setText(Americano.this.mSelection);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
public class myOnItemSelectedListener2 implements AdapterView.OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> parent, View v, int pos, long id) {
Americano.this.mPos = pos;
Americano.this.mSelection = parent.getItemAtPosition(pos).toString();
TextView resultText = (TextView) findViewById(R.id.tvSyrup);
resultText.setText(Americano.this.mSelection);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
public class myOnItemSelectedListener3 implements AdapterView.OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> parent, View v, int pos, long id) {
Americano.this.mPos = pos;
Americano.this.mSelection = parent.getItemAtPosition(pos).toString();
TextView resultText = (TextView) findViewById(R.id.tvTopping);
resultText.setText(Americano.this.mSelection);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
I have more menu item classes exactly like this one
I want to pass the textview data to the checkout page. But save that data in that page until the user closes the app.
thanks
You can do it sending the information through an Intent.
In your listener you would go to another actvity like this:
Intent intent = new Intent(getActivity(), NewActivity.class);
intent.putExtra("RESULT_TEXT", resultText);
startActivity(intent);
And on the NewActivity you can get the information like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
Bundle bundle = getIntent().getExtras();
String resultText = bundle.getString("RESULT_TEXT", "");
}
Hope it helps.

How to Pass an Int from non-activity class to Activity class

Android is similar to Java in terms of convention but why does my setter and getter methods won't work.
I have a spinner(which is a non-activity class) with code like this:
int finalposition;
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
for(int i=0; i<40; i++) {
if (i==pos){
setPosition(pos);
}
}
}
public void setPosition(int position){
finalposition= position;
}
public int getPosition(){
return finalposition;
}
and in onCreate(), here is my MainActivity(which extends Activity):
//spinner
spinner2 = (Spinner)findViewById(R.id.spinner2);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, paths);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(adapter2);
spinner2.setOnItemSelectedListener(new CustomOnItemSelectedListener2());
//button
gPath = (Button) findViewById(R.id.getPath);
gPath.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CustomOnItemSelectedListener2 coisl2= new CustomOnItemSelectedListener2();
if(coisl2.getPosition()==1)
Toast.makeText(getApplicationContext(), "It Works!", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "position:"+coisl2.getPosition(), Toast.LENGTH_SHORT).show();
}
});
What I need to do is that if I select the item at position 1 in my spinner and clicked gPath button, a toast saying "It Works!" should be displayed. However, it does not work. I put a toast(displaying the position that was taken from calling getPosition()) on the button. When I selected the item at position 1 and click the button, it returned position:0. So that's why it won't enter the if-condition that I implemented and I'm wondering why. I do this in Java but why am I having troubles in Android. What is wrong/missing in my code?
Any help is appreciated
Try this.
You are creating a new instance of the listener on each onClick, and that listener would obviously not know which item was selected in the spinner, since it isn't effectively listening over anything.
//declare this as a class object
CustomOnItemSelectedListener2 coisl2= new CustomOnItemSelectedListener2();
//This follows in your onCreate
//spinner
spinner2 = (Spinner)findViewById(R.id.spinner2);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, paths);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(adapter2);
spinner2.setOnItemSelectedListener(coisl2);
//button
gPath = (Button) findViewById(R.id.getPath);
gPath.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(coisl2.getPosition()==1)
Toast.makeText(getApplicationContext(), "It Works!", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "position:"+coisl2.getPosition(), Toast.LENGTH_SHORT).show();
}
});
You Can try this:
Under MainActivity.java
spinner2 = (Spinner)findViewById(R.id.spinner2);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, paths);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(adapter2);
coisl2= new CustomOnItemSelectedListener2(MainActivity.this,spinner2);
//button
gPath = (Button) findViewById(R.id.getPath);
gPath.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(coisl2.getPosition()==1)
Toast.makeText(getApplicationContext(), "It Works!", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "position:"+coisl2.getPosition(), Toast.LENGTH_SHORT).show();
}
});
Under CustomOnItemSelectedListener2.java( You can create this class like below)
public class CustomOnItemSelectedListener2
{
int finalposition;
public CustomOnItemSelectedListener2(Context context,Spinner spinner)
{
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int pos, long arg3) {
// TODO Auto-generated method stub
setPosition(pos);
}
#Override
public void onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
});
}
public void setPosition(int position){
finalposition= position;
}
public int getPosition(){
return finalposition;
}
}
Hope this is what you want...

Categories

Resources