how to use an if else statement with a spinner? - java

this is my code I don't know how to use if else statement with two spinner
//(spinner1.equals"THB" && spinner2.equals"USD") <--something like that
https://drive.google.com/file/d/1e_TbY6e-KAE7Iq6GLq2CFy9WA1VBy1qx/view?fbclid=IwAR1s7C9SVm2S202uAmURjwTilHu2ppwkHclvN7gDT3cEFFwZkqyktZv6MRE

If you are talking about the values of the spinner that the user has chosen:
Spinner spinner1 = findViewById(R.id.your_spinner1);
Spinner spinner2 = findViewById(R.id.your_spinner2);
if(spinner1.getSelectedItem().toString().equals("THB") && spinner2.getSelectedItem().toString().equals("USD"){
//do stuff here
}
Like the user f1sh in the comment said, post your code in the question.

Extend an interface AdapterView.OnItemSelectedListener
package com.example.acer.spinner;
import android.accessibilityservice.GestureDescription;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import java.lang.ref.SoftReference;
public class MainActivity extends AppCompatActivity {
Spinner spn,spn1;
EditText inmoney;
TextView answer;
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inmoney=findViewById(R.id.text);
answer=findViewById(R.id.textView);
btn=findViewById(R.id.button);
// first spinner
spn=findViewById(R.id.spinner);
spn1=findViewById(R.id.spinner2);
String [] legion ={"THB","USD","EUR","JPY","SGD","MYN","CNY"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,legion);
spn.setAdapter(adapter);
spn1.setAdapter(adapter);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
exrate();
}
});
}
public void exrate(){
double num=Double.parseDouble(inmoney.getText().toString());
if (spn1.getSelectedItem().toString().equals("THB") && spn.getSelectedItem().toString().equals("USD")){
double ans=num*5;
answer.setText(String.valueOf(ans));
}
else{
//do other currency conversions
}
}
}
You can also use else if(condition) instead of just else, to do other comparison and conversions
It is called as Ladder-if in Java jargon

Related

Trying to add to an arraylist on a different activity each time a button is pressed

So just to practice I've created a Pythagorean theorem calculator app. I want each answer that I obtain to be stored in another activity(a "history" page). I'm trying to use intents to send/receive the arraylist and items. I get the most recent one, but it is overwritten after each press of the button.
package com.example.hypnotenusecalculatorrebuild;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
//ToDo history button is broken. doesn't display listview when pressed.
public void toHistory(View view) {
// Intent intent = new Intent(getApplicationContext(), HistoryActivity.class);
//
// startActivity(intent);
}
public void findHypno(View view) {
Log.i("Info", "button pressed");
EditText editTextNumberA = (EditText) findViewById(R.id.editTextNumberA);
EditText editTextNumberB = (EditText) findViewById(R.id.editTextNumberB);
TextView textViewAnswer = (TextView) findViewById(R.id.textViewAnswer);
String message;
String cSquared;
if (editTextNumberA.getText().toString().isEmpty() || editTextNumberB.getText().toString().isEmpty()) {
message = "Please enter a number for each dimension";
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
} else {
Number numberA = new Number();
Number numberB = new Number();
Number numberC = new Number();
numberA.number = Double.parseDouble(editTextNumberA.getText().toString());
numberB.number = Double.parseDouble(editTextNumberB.getText().toString());
numberA.squareNumber();
numberB.squareNumber();
numberC.number = numberA.number + numberB.number;
numberC.squareRoot();
Log.i("test numberA", String.valueOf(numberA.number));
Log.i("test numberB", String.valueOf(numberB.number));
Log.i("test numberC", String.valueOf(numberC.number));
cSquared = Double.toString(numberC.number);
textViewAnswer.setText(cSquared);
ArrayList<String> historyList = new ArrayList<String>();
historyList.add("test");
Intent intent = new Intent(getApplicationContext(), HistoryActivity.class);
intent.putExtra("answer", cSquared);
intent.putStringArrayListExtra("arrayList", historyList);
startActivity(intent);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
package com.example.hypnotenusecalculatorrebuild;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
import java.util.function.ToDoubleBiFunction;
public class HistoryActivity extends AppCompatActivity {
public void back(View view) {
finish();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
Intent getList = getIntent();
ArrayList<String> historyList = getList.getStringArrayListExtra("arrayList");
historyList.add(getList.getStringExtra("answer"));
ListView listViewHistory = (ListView) findViewById(R.id.listViewHistory);
ArrayAdapter historyListArrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, historyList);
listViewHistory.setAdapter(historyListArrayAdapter);
// ToDo - intent isn't working as attended, only saves one item and gets overwritten each time
//Intent historyIntent = getIntent();
// get extra needs a name from put extra
// String testGetIntent = historyIntent.getStringExtra("answer");
// Log.i("testIntentString", testGetIntent);
// historyList.add(historyIntent.getStringExtra("answer"));
}
}
here is a different approach. make a public interface in a separate file named "extensions" or whatever and initialize your arraylist there like so:
public interface ext {
ArrayList<String> myArray = new ArrayList<String>();
}
this interface is created when the app runs and lives for as long as the app lives meaning you can always access and manipulate it anywhere in your app without worrying whether the activity is being killed or not. so you can add or remove elements to or from it wherever you want.
Access the array this way:
ext.myArray.add("new item")

Further guidance with a Spinner

after testing out examples given here and here, I thought I would be able to add a score-point if the user selected the correct drop-down item. (I'm making a simple quiz app that toasts the final score).
Obviously this is too advanced for me, but I really don't want to give up and wondered if anyone might have any idea as to what I'm doing wrong please?
Here is how I have it set out in the MainActivity.java, with my failed attempts of implementing a way of checking the selected item stripped out:
First I set out the questions:
package com.example.android.arabic;
import android.content.Intent;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.os.Bundle;
import android.util.Log;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.view.View.OnClickListener;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import com.example.android.arabic.Nature.Nature;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements OnItemSelectedListener{
int arabicScore = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// add emoji Q1
TextView q1 = findViewById(R.id.Q1_question);
q1.setText(Nature.HONEY_BEE);
// add emoji A2_option1
TextView qa2Option1 = findViewById(R.id.A2_option1);
qa2Option1.setText(Nature.GOAT);
// add emoji A2_option2
TextView qa2Option2 = findViewById(R.id.A2_option2);
qa2Option2.setText(Nature.BIRD);
// add emoji A2_option3
TextView qa2Option3 = findViewById(R.id.A2_option3);
qa2Option3.setText(Nature.HORSE);
//Q3 audio
Button q3Sound = this.findViewById(R.id.Q3_sound);
final MediaPlayer q3 = MediaPlayer.create(this, R.raw.camel);
q3Sound.setOnClickListener(new OnClickListener() {
public void onClick(View v) { q3.start();
}
});
// add emoji Q4_question
TextView q4 = findViewById(R.id.Q4_question);
q4.setText(Nature.ANT);
// Start of spinner Q4
Spinner a4 = findViewById(R.id.A4);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence>adapter = ArrayAdapter.createFromResource(this,
R.array.a4_array, 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);
// Apply the adapter to the spinner
a4.setAdapter(adapter);
a4.setOnItemSelectedListener(this);
//Q5 audio
Button q5Sound = this.findViewById(R.id.Q5_sound);
final MediaPlayer q5 = MediaPlayer.create(this, R.raw.cow_bird);
q5Sound.setOnClickListener(new OnClickListener() {
public void onClick(View v) { q5.start();
}
});
//A5
// add emoji A5_option1
TextView qa5Option1 = findViewById(R.id.A5_option1);
qa5Option1.setText(Nature.COW);
// add emoji A5_option2
TextView qa5Option2 = findViewById(R.id.A5_option2);
qa5Option2.setText(Nature.PIG);
// add emoji A5_option3
TextView qa5Option3 = findViewById(R.id.A5_option3);
qa5Option3.setText(Nature.SNAKE);
// add emoji A5_option4
TextView qa5Option4 = findViewById(R.id.A5_option4);
qa5Option4.setText(Nature.BIRD);
}
//Display Result
public void results(View view){
// Check point for Q1
EditText a1EditText = findViewById(R.id.A1);
String a1Entry = a1EditText.getText().toString();
if (a1Entry.contains("نحلة")) {
arabicScore = arabicScore + 1;
}
// Check point for Q2
RadioButton a2Radio = findViewById(R.id.A2_option2);
boolean isa2RadioChecked = a2Radio.isChecked();
if (isa2RadioChecked){
arabicScore = arabicScore + 1;
}
// Check point for Q3
EditText a3EditText = findViewById(R.id.A3);
String a3Entry = a3EditText.getText().toString();
if (a3Entry.contains("جمل")) {
arabicScore = arabicScore + 1;
}
// Check point for Q4
Toast resultToast = Toast.makeText(this, "You got " + arabicScore + " of 7 questions right.", Toast.LENGTH_LONG);
resultToast.show();
}
Preview of layout
}
Thank you very much for your advice in advance! I've been stuck on this for months! :'D

I can't get my scan results to display in android

When I run my app on a rooted device the ListView is blank and I am not sure why?
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.content.Context;
import android.content.BroadcastReceiver;
import android.content.Intent;
import java.util.List;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.widget.Toast;
This is my main class:
public class Network_List extends AppCompatActivity {
WifiManager wifiM;
WifiScanReciever wifiR;
ListView networklist;
String wifis[];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_network__list);
Search box for searching networks (not yet implemented so don't worry about it)
EditText searchNet = (EditText) findViewById(R.id.networkEditText);
This is the main list to display the network information
networklist = (ListView) findViewById(R.id.networkList);
Search button for the EditText (This is for future development)
Button networkButton = (Button) findViewById(R.id.searchButton);
scanButton is a button that starts the scan
Button scanButton = (Button) findViewById(R.id.buttonScan);
Declares wifiM as wifi manager and gets service
wifiM = (WifiManager) getSystemService(Context.WIFI_SERVICE);
Declares wifiR as WifiScanReciever
wifiR = new WifiScanReciever();
Button for starting the scan
scanButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
wifiM.startScan();
}
});
}
protected void onPause(){
unregisterReceiver(wifiR);
super.onPause();
}
protected void onResume(){
registerReceiver(wifiR, new IntentFilter(wifiM.SCAN_RESULTS_AVAILABLE_ACTION));
super.onResume();
}
This receives the scan results and puts it an array called wifis. onReceive captures scan results and sets the size of the array wifis.
private class WifiScanReciever extends BroadcastReceiver{
public void onReceive(Context c, Intent intent){
List<ScanResult> wifiSList = wifiM.getScanResults();
wifis = new String[wifiSList.size()];
for (int x = 0; x<wifiSList.size(); x++){
wifis[x] = ((wifiSList.get(x)).toString());
}
networklist.setAdapter(new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,wifis));
}
}
}

Android Programming with Java, how to use R.id

studio to create an android app that adds a string from an editText with an id of input and displays it into textView with an id of output. But
EditText input = EditText(findViewById(R.id.input));
and
TextView output = TextView(findViewById(R.id.output));
doesnt work as it says Method call expected. Any kind of help would be great, thankyou.
package com.example.toshb.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity
{
private Model model;
public MainActivity() {model = new Model();}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void processInput(View view)
{
EditText input = EditText(findViewById(R.id.input));
TextView output = TextView(findViewById(R.id.output));
model.addString(editText.getText().toString());
output.setText(model.getList());
input.setText("");
}
}
You need to add proper declaration of EditText And TextView . Before write a code please have a look here:
https://developer.android.com/index.html
EditText input = (EditText)findViewById(R.id.input);
TextView output =(TextView)findViewById(R.id.output);
model.addString(input.getText().toString());

My app will only output "false", not the code I want

I used samples from similar code to make this, unfortunately I'm not to sure what I did wrong.
The purpose of this app is to output text entered in a field to a TextView, where I changed the color, when a button is pressed.
package edu.wmich.project3
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.view.View.OnClickListener;
public class Main extends Activity {
String txtResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button text =(Button) findViewById(R.id.btnColor0);
final TextView result = ((TextView) findViewById(R.id.txtResult));
text.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
txtResult= getText(R.id.txtField0).toString();
result.setText(txtResult);
}
});
}
}
txtResult = (findViewById(R.id.txtField0)).toString();
will solve...
the problem is that you're using the method getText() from the Activity which has nothing to do with the TextField you're dealing with.
...what is the type of view of R.id.txtField0? I guess with this you can take it from here.

Categories