Spinner object reference problem? - java

How to use if else statement when using spinner objects?
I wish to make a page like this in Android.
I have done the coding for the button and the spinners and I have used an array to store the values in the spinner.
My Problem: When I select some values in both the spinners and click on "SHOW FARE" button the fare is not generated??
public class HelloSpinner extends Activity implements OnClickListener {
/** Called when the activity is first created.
* #return */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.source_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(
this, R.array.destination_array, android.R.layout.simple_spinner_item);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter);
View v= findViewById(R.id.button);
v.setOnClickListener(this);
if(spinner.getSelectedItem().toString()=="Adarsh Nagar"
&& spinner1.getSelectedItem().toString()=="Rajiv Chowk")
{
TextView t= (TextView) findViewById(R.id.text);
t.setText("Fare:Rs. 16");
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button:
Intent i = new Intent(this,Fare.class);
startActivity(i);
break;
}
}
}
If anyone can spot error(s) in the code, I would appreciate the feedback!

Create setOnItemSelectedListener for both spinner and inside that store the selected Value in a string Variable..
After that in Button click Check you if Conditions..
spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
selectedspinnervalue =s1.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
where the string variable selectedspinnervalue contains the value selected by the spinner..
Now in the Button Click check the condition like this :
yourbuttonobject.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(selectedvalueinspinner.equalsIgnoreCase("Adarsh Nagar")&& selectedvalueinspinner1.equalsIgnoreCase("Rajiv Chowk")){
// Your desired Code..
}
}
});

Related

comparing selecteditempostion from spinner to an arraylist with resources

This is probably a dumb question but I'm very new to coding so please bear with me.
I am trying to make audiofiles play when a button is pressed and a song is selected in the spinner. But the number doesnt seem to be updating and I only get the same song played.
private void Onclick() {
final int[] songlist ={
R.raw.salsa,
R.raw.fantasy,
};
mp = MediaPlayer.create(this, songlist[spinner.getSelectedItemPosition()]);
mp.setLooping(true);
play_btn.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.start();}
});}
Why doesnt this work?
EDIT: onCreate method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play_btn = (ImageButton) findViewById(R.id.play_btn);
spinner = (Spinner) findViewById(R.id.song_spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.songs_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
Onclick();
}
You can go with this:
add a class property like:
final int[] songlist ={
R.raw.salsa,
R.raw.fantasy,
};
int selectedSong; //default to 0
Then in your class, you can add a listener on spinner value change events with this:
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
selectedSong = position;
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {}
});
And now in the button onClick, you can go with this code:
play_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp = MediaPlayer.create(MainActivity.this, songlist[selectedSong]);
mp.setLooping(true);
mp.start();
}
});
To make this work all you have to do is initialise the media-player object every time when you click on the button pressed.
play_btn.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// in your code it is initialised with the first selected object
mp = MediaPlayer.create(this, songlist[spinner.getSelectedItemPosition()]);
mp.setLooping(true);
mp.start();}
})};

How to make the activity authentification appear just after the animation (splash screen) of the logo.please help me

$I made for the first time an application so my problem is to make the layout login appear in the same activity 'splashscreen' after the animation
this my code for splashscreen.java
Where could the problem be?
public class Splashscreen extends Activity implements AdapterView.OnItemSelectedListener {
Spinner spinner;
Button btnCnx;
LinearLayout ln;
public void onAttachedToWindow() {
super.onAttachedToWindow();
Window window = getWindow();
window.setFormat(PixelFormat.RGBA_8888);
}
/** Called when the activity is first created. */
Thread splashTread;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splashscreen);
// btnCnx = (Button) findViewById(R.id.btn_Connexion);
// btnCnx.setCursorVisible(false);
//**************************************************************
ln = (LinearLayout) findViewById(R.id.LinLaySpalScrenLogin);
ln.setVisibility(View.INVISIBLE);
StartAnimations();
Button Key_save = (Button) findViewById(R.id.btn_Connexion);
//Key_save.setVisibility(View.INVISIBLE);
Key_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e("DEMO TAG", "CLick on sign in button");
Intent intent = new Intent(Splashscreen.this, calendrier.class);
startActivity(intent);
}
});
// ********************************************************
// Spinner element
spinner = (Spinner) findViewById(R.id.fonction);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
// Spinner Drop down elements
List<String> fonction = new ArrayList<String>();
fonction.add("Administrateur");
fonction.add("Agent laboratoire");
fonction.add("Chef releve");
fonction.add("Releveur");
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, fonction);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
// Key_save.setVisibility(View.VISIBLE);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
String item = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
// Toast.makeText(parent.getContext(), "Vous avez choisit: " + item, Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
private void StartAnimations() {
Animation anim = AnimationUtils.loadAnimation(this, R.anim.alpha);
anim.reset();
LinearLayout l=(LinearLayout) findViewById(R.id.lin_lay);
l.clearAnimation();
l.startAnimation(anim);
anim = AnimationUtils.loadAnimation(this, R.anim.translate);
anim.reset();
ImageView iv = (ImageView) findViewById(R.id.splash);
iv.clearAnimation();
iv.startAnimation(anim);
ln.setVisibility(View.VISIBLE);
splashTread = new Thread() {
#Override
public void run() {
try {
int waited = 0;
// Splash screen pause time
while (waited < 3500) {
sleep(100);
waited += 100;
}
//Intent intent = new Intent(Splashscreen.this,
// saisieIndex.class);
//intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
//startActivity(intent);
//Splashscreen.this.finish();
} catch (InterruptedException e) {
// do nothing
}
// finally {
// //Splashscreen.this.finish();
// }
ln.setVisibility(View.VISIBLE);
}
};
splashTread.start();
}
}
You are going to have to create either an activity that loads right after the Splash Screen i.e. Intent i = new Intent(getApplicationContext, Authenticate.class); then startActivity(i). Once that loads you can use getSharedPreferences to get a list of users registered on the device, or you can pull the user list from an online source. From this point you can set a boolean success meaning the username and password match, which in that case you would start the Mainactivity using the same code above. If not you can let them know via toast, changing a textView, etc.

Can't get Double output in TextView

The main purpose of this Android app is to learn how to use spinners and parse data. I have tried a lot of things and it still is not working. I don't get the output of the resultFuel on the screen.
Here's the code in my MainActivity:
public class MainActivity extends Activity implements OnItemSelectedListener {
Spinner spinFrom,spinTo;
String[] paths ={"liters/100km","liters/100 miles","(US)gallons/100 miles","(US)gallons/100km","(UK)gallons/100miles",
"(UK)gallons/100km","kilometers/liter","miles/liter", "miles/gallon", "kilometers/gallon"
};
EditText etfrom;
TextView textview;
double fromFuel,resultFuel;
Button clik;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinFrom = (Spinner) findViewById(R.id.fromSpinner);
spinTo = (Spinner) findViewById(R.id.toSpinner);
etfrom = (EditText) findViewById(R.id.fromET);
textview = (TextView) findViewById(R.id.Results);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_spinner_item,paths);
spinFrom.setAdapter(adapter);
spinTo.setAdapter(adapter);
spinFrom.setOnItemSelectedListener(this);
spinTo.setOnItemSelectedListener(this);
if( etfrom.length() == 0 || etfrom.equals("") || etfrom == null){
}
clik = (Button) findViewById(R.id.button1);
clik.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(selectedFrom.equals(selectedTo)){
//Do nothing
}else if(selectedFrom.equals("liters/100km")&& selectedTo.equals("liters/100 miles")){
fromFuel= Double.parseDouble(etfrom.getText().toString());
resultFuel = fromFuel* 1.61;
// String result = String.valueOf(resultFuel);
textview.setText("" +resultFuel );
}else{
}
}
});
}
String selectedFrom;
String selectedTo;
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
selectedFrom = spinFrom.getItemAtPosition(arg2).toString();
selectedTo = spinTo.getItemAtPosition(arg2).toString();
Toast.makeText(getBaseContext(),"From: " + selectedTo, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
Please try :
textview.setText(Double.toString(resultFuel) );

how to assign different activities to each item of the spinner?

I have a page which consist of a spinner and a submit button. What I want to achieve is when user selects an item in the list and click on submit, it should take him to an other layout having a webview. Each item in the spinner should open different .html page in the layout.
What I have now is the item is being selected from the spinner, but I'm not sure how to perform onclick listener to it...
code for main activity is here
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.beef);
addListenerOnButton();
addListenerOnSpinnerItemSelection();
}
public void addListenerOnSpinnerItemSelection(){
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
//get the selected dropdown list value
public void addListenerOnButton() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
btnSubmit = (ImageButton) findViewById(R.id.imageButton1);
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/*Nothing as of now*/
//I need to call the ID of the selected item from the spinner here and start new activity
}
});
}
}
code of CustomOnItemSelectedListener is here
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
if (arg2 == 0) // First item selected
{
//Here I need to give an id for the .html file
}
else if (arg2 == 1) // Second
{
//Here I need to give an id for the .html file
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
String selItem = arg0.get(arg2); // String representation of the selected item
if (arg2 == 0) // First item selected
{
}
else if (arg2 == 1) // Second
{
}
// etc
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}

Android Dynamic Spinner Update

I'm working with Android and Spinners and I need some help. I have a class that creates two spinners and a button. The first spinner is for my category, my second is for my sub-category. What I am trying to do is dynamically update the second spinner (spinner2). I've been trying to use adapter2.clear() but that crashes android, with an error "unable to start activity componentinfo unsupported operation"
Here is my code:
public class MyClass extends MyBaseClass
{
int category;
int sub_category;
ArrayAdapter<String> adapter2;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.quizes);
//CATEGORY INFO
final String[] items1 = new String[] {"One", "Two", "Three"};
final Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, items1);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter1);
//SUBCATEGORY INFO
final String[] items2 = new String[] {"SOne", "STwo", "SThree"};
final Spinner spinner2 = (Spinner) findViewById(R.id.spinner2);
adapter2 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, items2);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(adapter2);
// Capture our button from layout
Button button = (Button)findViewById(R.id.button1);
// Register the onClick listener with the implementation above
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
startActivity(new Intent(MyClass.this, GoToOtherClass.class));
}
});
//SELECTOR CONTROL FOR SPINNER1 {CATEGORY}
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
MyClass.this.category = spinner1.getSelectedItemPosition();
//OTHER STUFF
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
//SELECTOR CONTROL FOR SPINNER2 {SUB-CATEGORY}
spinner2.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
MyClass.this.sub_category = spinner2.getSelectedItemPosition();
//OTHER STUFF
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
return true;
}
}
I understand about the .clear()/.add() methods, but anytime I try clear()/add() my program crashes, what do I need to do to fix things so I can change the spinner2 contents for my sub-category list? Any advice would help, as I have spent hours doing things such as:
Object t=adapter2.getitem(0);
spinner2.remove((String) t);
or adapter2.clear() and a few other tricks and I have no further ideas left. I am still learning android. I've tried looking at some other posts here on stackoverflow and google but was not sure how to get their ideas working.
After you change the contents of the second Spinner, you need to call adapter2.notifyDataSetChanged(). Without that call, the UI won't update with the new contents of the Spinner, and you could also have problems referencing things that don't exist anymore.
Try this Code..
public class MainActivity extends Activity {
Spinner sp1,sp2;
ArrayAdapter<String> adp1,adp2;
List<String> l1,l2;
int pos;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
l1=new ArrayList<String>();
l1.add("A");
l1.add("B");
sp1= (Spinner) findViewById(R.id.spinner1);
sp2= (Spinner) findViewById(R.id.spinner2);
adp1=new ArrayAdapter<String> (this,android.R.layout.simple_dropdown_item_1line,l1);
adp1.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
sp1.setAdapter(adp1);
sp1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
pos=arg2;
add();
}
private void add() {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), ""+pos, Toast.LENGTH_SHORT).show();
switch(pos)
{
case 0:
l2= new ArrayList<String>();
l2.add("A 1");
l2.add("A 2");
adp2=new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_dropdown_item_1line,l2);
adp2.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
sp2.setAdapter(adp2);
select();
break;
case 1:
l2= new ArrayList<String>();
l2.add("B 1");
l2.add("B 2");
adp2=new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_dropdown_item_1line,l2);
adp2.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
sp2.setAdapter(adp2);
select();
break;
}
}
private void select() {
// TODO Auto-generated method stub
sp2.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "Test "+arg2, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}

Categories