I am currently coding an android app but I encountered some difficulty.
I am able to receive some checkbox values from another activity using the getIntent().getExtras().getBoolean()function.
But my question is, how can i make sure that checkboxes with the characters 'wb' or 'ab' or 'alb' together with(or not) 'cs' appearing, a count is performed and the one with the greatest value between 'wb', 'ab' and 'alb' is chosen and a summary is displayed via a texfield.
e.g. if there appearances of 'wb' are greater than those of 'alb' and ab, then the result is displayed "you have a widened bronchus".
package com.example.vic.cdmes_;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class results extends AppCompatActivity {
private Button displayResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_results);
viewResults();
}
private void viewResults() {
final Boolean wb1 = getIntent().getExtras().getBoolean("wb1");
final Boolean wb2 = getIntent().getExtras().getBoolean("wb2");
final Boolean wb3 = getIntent().getExtras().getBoolean("wb3");
final Boolean wb4 = getIntent().getExtras().getBoolean("wb4");
final Boolean wb5 = getIntent().getExtras().getBoolean("wb5");
final Boolean wb6 = getIntent().getExtras().getBoolean("wb6");
final Boolean wb7 = getIntent().getExtras().getBoolean("wb7");
final Boolean cs1 = getIntent().getExtras().getBoolean("cs1");
final Boolean cs2 = getIntent().getExtras().getBoolean("cs2");
final Boolean vb1 = getIntent().getExtras().getBoolean("vb1");
final Boolean vb2 = getIntent().getExtras().getBoolean("vb2");
final Boolean vb3 = getIntent().getExtras().getBoolean("vb3");
final Boolean vb4 = getIntent().getExtras().getBoolean("vb4");
final Boolean vb5 = getIntent().getExtras().getBoolean("vb5");
final Boolean alb1 = getIntent().getExtras().getBoolean("alb1");
final Boolean alb2 = getIntent().getExtras().getBoolean("alb2");
final Boolean alb3 = getIntent().getExtras().getBoolean("alb3");
final Boolean ab1 = getIntent().getExtras().getBoolean("ab1");
final Boolean ab2 = getIntent().getExtras().getBoolean("ab2");
final Boolean ab3 = getIntent().getExtras().getBoolean("ab3");
final Boolean ab4 = getIntent().getExtras().getBoolean("ab4");
displayResult = (Button)findViewById(R.id.displayResults);
displayResult.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(results.this,.toString(),
// Toast.LENGTH_SHORT).show();
if(wb1&&wb2&&wb3&&wb4&&wb5&&wb6&&wb7&&cs1&&cs2)
{
//if the number of checkboxes exceeds
}
else
if (vb1&&vb2&&vb3&&vb4&&vb5&&cs1&&cs2)
{
//display the person might be having a widened bronchus
}
else
if (alb1&&alb2&&alb3&&cs1&&cs2)
{
//display the person might be having a alb disease
}
else
if (ab1&&ab2&&ab3&&ab4&&cs1&&cs2)
{
//display the person might be having a airborne disease
}
}
});
}
}
thanks for the help in advance.
Set Default Boolean value. Like This
final Boolean wb1 = getIntent().getExtras().getBoolean("wb1",true);
You can get the count of wb, ab and alb below, using that you can write the if statement.
int wbCount = 0, abCount = 0, albCount = 0;
boolean cs = (cs1 && cs2);
for(int i=1; i <= 7; i++) {
if(getIntent().getExtras().getBoolean("wb"+i) && cs) {
wbCount++;
}
}
for(int i=1; i <= 3; i++) {
if(getIntent().getExtras().getBoolean("alb"+i) && cs) {
albCount++;
}
}
for(int i=1; i <= 4; i++) {
if(getIntent().getExtras().getBoolean("ab"+i) && cs) {
abCount++;
}
}
I'm having an issue with saving the instance of an ArrayList of custom objects in an Activity and then retreiving it after doing some stuff in another Activity. Inside the first Activity (which has the ArrayList), there is a button to start a second activity. Inside this second Activity the user is asked to create a new object that will be added afterwards in the ArrayList of the first Activity, so that when the second Activity finishes the first Activity is shown again with a ListView of all the objects (including the last one created). The problem I'm facing is that only the last object created is being shown in the ListView.
Here is the code of the first Activity:
public class CargasMin extends AppCompatActivity implements View.OnClickListener {
RelativeLayout rl_CargasMin;
ImageButton bt_AdDep;
Button bt_CalcCargas;
ListView listView_Dep;
ArrayList<Dependencia> listaDeDependencias = new ArrayList<Dependencia>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.min_cargas);
rl_CargasMin = (RelativeLayout) findViewById(R.id.cargasMinLayout);
bt_AdDep = (ImageButton) findViewById(R.id.bt_AdDep_CargasMin);
bt_CalcCargas = (Button) findViewById(R.id.bt_CalcCargas_CargasMin);
bt_AdDep.setOnClickListener(this);
bt_CalcCargas.setOnClickListener(this);
// This seems not to be working!
if(savedInstanceState == null) { }
else {
listaDeDependencias = savedInstanceState.getParcelableArrayList("key");
}
// Get last object created
Intent intent_de_AdDep = getIntent();
Dependencia dependenciaAAdicionar = (Dependencia) intent_de_AdDep.getParcelableExtra("novaDependencia");
if(dependenciaAAdicionar == null) { }
else {
listaDeDependencias.add(dependenciaAAdicionar);
}
//Cria Adapter pra mostrar dependencias na ListView
DependenciaAdapter adapterDeDependencias = new DependenciaAdapter(this, R.layout.adapter_dependencia, listaDeDependencias);
//Seta Adapter
listView_Dep = (ListView) findViewById(R.id.listView_Dep_CargasMin);
listView_Dep.setAdapter(adapterDeDependencias);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.bt_AdDep_CargasMin:
Intent intent_AdDep = new Intent(CargasMin.this, AdDep.class);
startActivity(intent_AdDep);
break;
case R.id.bt_CalcCargas_CargasMin:
//
break;
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// Aqui se salva a listaDeDependencias quando a Atividade eh momentaneamente fechada.
outState.putParcelableArrayList("key", listaDeDependencias);
super.onSaveInstanceState(outState);
}
}
This is the code of my custom class Dependencia:
public class Dependencia implements Parcelable {
String nome;
int tipo;
float largura = 0;
float comprimento = 0;
float area = 0;
float perimetro = 0;
// Constructor da classe Dependencia.
public Dependencia(String nomeDep, int tipoDep) {
nome = nomeDep;
tipo = tipoDep;
}
private Dependencia(Parcel in) {
nome = in.readString();
tipo = in.readInt();
largura = in.readFloat();
comprimento = in.readFloat();
area = in.readFloat();
perimetro = in.readFloat();
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeString(nome);
out.writeInt(tipo);
out.writeFloat(largura);
out.writeFloat(comprimento);
out.writeFloat(area);
out.writeFloat(perimetro);
}
public static final Parcelable.Creator<Dependencia> CREATOR = new Parcelable.Creator<Dependencia>() {
public Dependencia createFromParcel(Parcel in) {
return new Dependencia(in);
}
public Dependencia[] newArray(int size) {
return new Dependencia[size];
}
};
}
And this is the code of the second Activity:
public class AdDep extends AppCompatActivity implements View.OnClickListener {
RelativeLayout rl_AdDep;
EditText et_Nome;
EditText et_Largura;
EditText et_Comprimento;
EditText et_Area;
EditText et_Perimetro;
Spinner spinner_Tipo;
String vetorTipo[];
int tipoEscolhido;
Button bt_AdDep1;
Button bt_AdDep2;
Dependencia novaDependencia;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dep_ad);
rl_AdDep = (RelativeLayout)findViewById(R.id.adDepLayout);
et_Nome = (EditText) findViewById(R.id.et_Nome_AdDep);
et_Largura = (EditText) findViewById(R.id.et_Largura_AdDep);
et_Comprimento = (EditText) findViewById(R.id.et_Comprimento_AdDep);
et_Area = (EditText) findViewById(R.id.et_Area_AdDep);
et_Perimetro = (EditText) findViewById(R.id.et_Perimetro_AdDep);
spinner_Tipo = (Spinner) findViewById(R.id.spinner_Tipo_AdDep);
bt_AdDep1 = (Button) findViewById(R.id.bt_AdDep1);
bt_AdDep2 = (Button) findViewById(R.id.bt_AdDep2);
// Adicionando opcoes no spinner
vetorTipo = new String[5];
vetorTipo[0] = "Banheiro";
vetorTipo[1] = "Varanda";
vetorTipo[2] = "Cozinha/Copa/Serviço/etc.";
vetorTipo[3] = "Sala/Dormitório";
vetorTipo[4] = "Outro";
// Criando ArrayAdapter de strings pro spinner
ArrayAdapter<String> adapterTipo = new ArrayAdapter<String>(AdDep.this, android.R.layout.simple_spinner_item, vetorTipo);
// Setando o Adapter
spinner_Tipo.setAdapter(adapterTipo);
// Valor default do spinner (hint)
spinner_Tipo.setSelection(0);
bt_AdDep1.setOnClickListener(this);
bt_AdDep2.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(String.valueOf(spinner_Tipo.getSelectedItem()).equals("Banheiro"))
tipoEscolhido = 1;
else if(String.valueOf(spinner_Tipo.getSelectedItem()).equals("Varanda"))
tipoEscolhido = 2;
else if(String.valueOf(spinner_Tipo.getSelectedItem()).equals("Cozinha/Copa/Serviço/etc."))
tipoEscolhido = 3;
else if(String.valueOf(spinner_Tipo.getSelectedItem()).equals("Sala/Dormitório"))
tipoEscolhido = 4;
else if(String.valueOf(spinner_Tipo.getSelectedItem()).equals("Outro"))
tipoEscolhido = 5;
novaDependencia = new Dependencia(et_Nome.getText().toString(), tipoEscolhido);
switch(v.getId()) {
case R.id.bt_AdDep1:
novaDependencia.largura = Float.valueOf(et_Largura.getText().toString());
novaDependencia.comprimento = Float.valueOf(et_Comprimento.getText().toString());
break;
case R.id.bt_AdDep2:
novaDependencia.area = Float.valueOf(et_Area.getText().toString());
novaDependencia.perimetro = Float.valueOf(et_Perimetro.getText().toString());
break;
}
AlertDialog.Builder builder2 = new AlertDialog.Builder(v.getContext());
builder2.setMessage("Deseja adicionar T.U.E. nesta dependência?").setPositiveButton("Sim", dialogClickListener).setNegativeButton("Não", dialogClickListener).show();
}
// Objeto tipo dialog criado para perguntar se usario deseja inserir TUEs
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
break;
case DialogInterface.BUTTON_NEGATIVE:
Intent intent_NovaDep_CargasMin = new Intent(AdDep.this, CargasMin.class);
intent_NovaDep_CargasMin.putExtra("novaDependencia", novaDependencia);
startActivity(intent_NovaDep_CargasMin);
break;
}
}
};
}
If anyone knows how to solve this, please share. Thanks.
The problem is that you're starting a new instance of the CargasMin activity from AdDep activity. Your AdDep activity should just finish and return a result back to the existing instance of CargasMin activity on the back stack for you to see all the previous list data as well.
To retrieve the new list item from AdDep as a result, use startActivityForResult()
case R.id.bt_AdDep_CargasMin:
Intent intent_AdDep = new Intent(CargasMin.this, AdDep.class);
startActivityForResult(intent_AdDep, ADD_DEP_REQUEST);
break;
where ADD_DEP_REQUEST is just a request code constant
public static final int ADD_DEP_REQUEST = 1;
Now, when AdDep is done collecting data, it returns the new data item as a result.
case DialogInterface.BUTTON_NEGATIVE:
Intent result = new Intent();
result.putExtra("novaDependencia", novaDependencia);
setResult(Activity.RESULT_OK, result);
finish();
break;
Your main CargasMin activity will then receive the new data item as
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ADD_DEP_REQUEST) {
if (resultCode == RESULT_OK) {
// Get last object created
Dependencia dependenciaAAdicionar =
(Dependencia) data.getParcelableExtra("novaDependencia");
if(dependenciaAAdicionar != null){
listaDeDependencias.add(dependenciaAAdicionar);
// Refresh Adapter pra mostrar dependenciaAAdicionar na ListView
adapterDeDependencias.notifyDataSetChanged();
}
}
}
}
Note that listaDeDependencias and adapterDeDependencias have been changed to instance members of the activity.
Your current approach would have worked if you were persisting the data to some storage (like in a file or database) but creating a new instance of CargasMin is still not recommended because the one existing on the back stack would suffice.
I can't figure out how to fix this problem in my code: I am making a small app which randomly asks you for 20 words from Dutch (nederlands) to English (engels). I have saved the words in arrays and the words are randomly picked now. There are 2 buttons: One for picking a random word and one for checking if the answer is correct. The variable iwoord is given a random value when pressing button Newword and i want the same value to be used in the next OnClickListener, so I can compare the arrays and see if the answer is correct. But the variable cannot be resolved in the second OnClickListener. Can anybody help me solving my problem?
public class MainActivity extends Activity {
EditText NederlandsEdit;
EditText EngelsEdit;
Button ControleerButton;
Button NieuwwoordButton;
Random woord = new Random();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final String[] nederlands = new String[20];
nederlands[0] = "bij";
nederlands[1] = "paraplu";
nederlands[2] = "hond";
nederlands[3] = "kaas";
nederlands[4] = "eekhoorn";
nederlands[5] = "fiets";
nederlands[6] = "auto";
nederlands[7] = "vis";
nederlands[8] = "maan";
nederlands[9] = "aarde";
nederlands[10] = "vuur";
nederlands[11] = "boom";
nederlands[12] = "blaadje";
nederlands[13] = "soep";
nederlands[14] = "sok";
nederlands[15] = "potlood";
nederlands[16] = "kat";
nederlands[17] = "muis";
nederlands[18] = "zeep";
nederlands[19] = "ring";
final String[] engels = new String[20];
engels[0] = "bee";
engels[1] = "umbrella";
engels[2] = "dog";
engels[3] = "cheese";
engels[4] = "squirrel";
engels[5] = "bicycle";
engels[6] = "car";
engels[7] = "fish";
engels[8] = "moon";
engels[9] = "earth";
engels[10] = "fire";
engels[11] = "tree";
engels[12] = "leaf";
engels[13] = "soup";
engels[14] = "sock";
engels[15] = "pencil";
engels[16] = "cat";
engels[17] = "mouse";
engels[18] = "soap";
engels[19] = "ring";
NederlandsEdit = (EditText) findViewById(R.id.editnederlands);
EngelsEdit = (EditText) findViewById(R.id.editengels);
ControleerButton = (Button) findViewById(R.id.butcontroleer);
NieuwwoordButton = (Button) findViewById(R.id.butnieuwwoord);
NieuwwoordButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NieuwwoordButton.setEnabled(false);
ControleerButton.setEnabled(true);
int iwoord = woord.nextInt(20 - 0) + 0;
NederlandsEdit.setText(nederlands[iwoord]);
}
});
ControleerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(EngelsEdit.getText().toString().equals(engels[iwoord])){
Toast.makeText(getBaseContext(), "correct!", Toast.LENGTH_SHORT).show();
}
else
{
i = i + 1;
}
}
});
}
The int "iwoord" should be declared globally just like the edittexts. I have posted the code just in case.
package com.example.stack_test;
import java.util.Random;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText NederlandsEdit;
EditText EngelsEdit;
Button ControleerButton;
Button NieuwwoordButton;
Random woord = new Random();
int i,iwoord;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final String[] nederlands = new String[20];
nederlands[0] = "bij";
nederlands[1] = "paraplu";
nederlands[2] = "hond";
nederlands[3] = "kaas";
nederlands[4] = "eekhoorn";
nederlands[5] = "fiets";
nederlands[6] = "auto";
nederlands[7] = "vis";
nederlands[8] = "maan";
nederlands[9] = "aarde";
nederlands[10] = "vuur";
nederlands[11] = "boom";
nederlands[12] = "blaadje";
nederlands[13] = "soep";
nederlands[14] = "sok";
nederlands[15] = "potlood";
nederlands[16] = "kat";
nederlands[17] = "muis";
nederlands[18] = "zeep";
nederlands[19] = "ring";
final String[] engels = new String[20];
engels[0] = "bee";
engels[1] = "umbrella";
engels[2] = "dog";
engels[3] = "cheese";
engels[4] = "squirrel";
engels[5] = "bicycle";
engels[6] = "car";
engels[7] = "fish";
engels[8] = "moon";
engels[9] = "earth";
engels[10] = "fire";
engels[11] = "tree";
engels[12] = "leaf";
engels[13] = "soup";
engels[14] = "sock";
engels[15] = "pencil";
engels[16] = "cat";
engels[17] = "mouse";
engels[18] = "soap";
engels[19] = "ring";
NederlandsEdit = (EditText) findViewById(R.id.editnederlands);
EngelsEdit = (EditText) findViewById(R.id.editengels);
ControleerButton = (Button) findViewById(R.id.butcontroleer);
NieuwwoordButton = (Button) findViewById(R.id.butnieuwwoord);
NieuwwoordButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NieuwwoordButton.setEnabled(false);
ControleerButton.setEnabled(true);
iwoord = woord.nextInt(20 - 0) + 0;
NederlandsEdit.setText(nederlands[iwoord]);
}
});
ControleerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(EngelsEdit.getText().toString().equals(engels[iwoord])){
Toast.makeText(getBaseContext(), "correct!", Toast.LENGTH_SHORT).show();
}
else
{
i = i + 1;
}
}
});
}
}
Declare your variable globally and you can able assign value from first onclicklistener and use it frm the second onclicklistener
In case you are facing problems that listeners ask you to make your variable final, use a setter and a getter method for your variable. You cant change the value of an integer variable once you have initialized it for the first time. Don't use it directly in the Listener code, and you wont have to make it final.
Read this article if you need to be familiar with getters and setters.
First of I'm a novice. I've been through the example of how to create a spinner, and I've searched this site and the Internet for how to create multiple spinners with the list in the 2nd spinner being dependant upon the first spinner and the 3rd spinner list being dependent upon the selection in the 2nd. However I cannot find a tutorial or solution anywhere.
Could someone provide some help to as to how this would be done (a tutorial would be great :))
Basically A list in Spinner1 could be 'Manufacturer', on selection Produces a list of 'Models' in Spinner2 and from the selection of Model in spinner2 produces a list of 'Issues' in Spinner3.
Any help would be great,
Thanks in advanced.
See here this demo have Two Spinner and works
so onItemSelected method you can check your fisrt,second,third spinner value and set as per your requires.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Spinner spinner1,spinner2,spinner3;
public static final String AP_DISTRICTS = "Andhra Pradesh";
public static final String TN_DISTRICTS = "Tamil Nadu";
public static final String TG_DISTRICTS = "Telangana";
public static final String VC_DISTRICTS = "Victoria";
public static final String TS_DISTRICTS = "Tasmania";
public static final String QL_DISTRICTS = "Queens Land";
public static final String KR_DISTRICTS = "Karachi";
public static final String LH_DISTRICTS = "Lahore";
public static final String SI_DISTRICTS = "Sindh";
public static final String SELECT_COUNTRY = "--Select Country--";
public static final String SELECT_STATE = "--Select State--";
public static final String SELECT_DISTRICT = "--Select District--";
String[] country = {SELECT_COUNTRY, "India", "Australia", "Pakistan"};
String[] indiaStates = {SELECT_STATE, AP_DISTRICTS, TN_DISTRICTS, TG_DISTRICTS};
String[] australiaStates = {"SELECT_STATE", VC_DISTRICTS, TS_DISTRICTS, QL_DISTRICTS};
String[] pakistanStates = {"SELECT_STATE", KR_DISTRICTS, LH_DISTRICTS, SI_DISTRICTS};
String[] apDistricts = {SELECT_DISTRICT, "Nellore", "Chittoor", "Prakasam"};
String[] tnDistricts = {SELECT_DISTRICT, "Chennai", "Thiruvallur", "Kanchipuram"};
String[] tgDistricts = {SELECT_DISTRICT, "Hyderabad", "Secunderabad", "Ranga Reddy"};
String[] vicDistricts = {SELECT_DISTRICT, "Ballarat South", "Ballarat North", "Ballarat East"};
String[] tsDistricts = {SELECT_DISTRICT, "Tasmania East", "Tasmania West", "Tasmania South"};
String[] qsDistricts = {SELECT_DISTRICT, "Queens Land East", "Queens Land West", "Queens Land North"};
String[] krDistricts = {SELECT_DISTRICT, "Karachi East", "Karachi North", "Karachi South"};
String[] lhDistricts = {SELECT_DISTRICT, "Lahore South", "Lahore East", "Lahore North"};
String[] siDistricts = {SELECT_DISTRICT, "Sindh West", "Sindh North", "Sindh East"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner1 = (Spinner) findViewById(R.id.spinner_item1);
spinner2 = (Spinner) findViewById(R.id.spinner_item2);
spinner3 = (Spinner) findViewById(R.id.spinner_item3);
spinner1.setSelection(0);
spinner2.setSelection(0);
spinner3.setSelection(0);
setSpinner(spinner1, country);
setSpinner(spinner2, indiaStates);
setSpinner(spinner3, apDistricts);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, country);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter);
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
switch (i){
case 0:
Toast.makeText(MainActivity.this, "please Select Country", Toast.LENGTH_SHORT).show();
spinner1.setSelection(0);
spinner2.setSelection(0);
spinner3.setSelection(0);
break;
case 1:
setSpinner(spinner2, indiaStates);
break;
case 2:
setSpinner(spinner2, australiaStates);
break;
case 3:
setSpinner(spinner2, pakistanStates);
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String selectedItem = adapterView.getSelectedItem().toString();
if (spinner1.getSelectedItemPosition() == 0) {
Toast.makeText(MainActivity.this, "please Select Country", Toast.LENGTH_SHORT).show();
spinner2.setSelection(0);
spinner3.setSelection(0);
return;
}
if (i == 0){
spinner3.setSelection(0);
return;
}
switch (selectedItem){
case AP_DISTRICTS:
setSpinner(spinner3, apDistricts);
break;
case TN_DISTRICTS :
setSpinner(spinner3, tnDistricts);
break;
case TG_DISTRICTS:
setSpinner(spinner3, tgDistricts);
break;
case VC_DISTRICTS:
setSpinner(spinner3, vicDistricts);
break;
case TS_DISTRICTS:
setSpinner(spinner3, tsDistricts);
break;
case QL_DISTRICTS:
setSpinner(spinner3, qsDistricts);
break;
case KR_DISTRICTS:
setSpinner(spinner3, krDistricts);
break;
case LH_DISTRICTS:
setSpinner(spinner3, lhDistricts);
break;
case SI_DISTRICTS :
setSpinner(spinner3, siDistricts);
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
spinner3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if (spinner2.getSelectedItemPosition() == 0 || spinner1.getSelectedItemPosition() == 0) {
Toast.makeText(MainActivity.this, "please Select State", Toast.LENGTH_SHORT).show();
spinner2.setSelection(0);
spinner3.setSelection(0);
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
private void setSpinner(Spinner spinner2, String[] states) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, states);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Specify the layout to use when the list of choices appears
spinner2.setAdapter(adapter);
}
}
You can do this by handling onItemSelected event.
you can store your data in database or in arrays and on selection you can populate particular array in particular spinner.
this is straight from one of my app's (actually the first app i ever wrote) so its not pretty but it works
package com.skyesmechanical.OilProductionLogApp;
import android.app.Activity;
import android.app.AlertDialog;
import android.database.Cursor;
import android.database.SQLException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;
import java.io.IOException;
public class test extends Activity {
/** Called when the activity is first created. */
public String spinnerPipeLengthText = "";
public String spinnerNaturalGasText = "";
public String spinnerPropaneGasText = "";
public Spinner spinnerPipeLength;
public Spinner spinnerTypeGas;
public Spinner spinnerSupplyPressure;
public static Integer spinnerPipeLengthInt = 0;
public static Integer spinnerTypeGasInt = 0;
public static Integer spinnerPropaneGasInt = 0;
public static Integer spinnerSupplyPressureInt = 0;
public static Integer finalRow = 0;
public boolean supplyPressureVisible = false;
public boolean pipeLengthVisible = false;
static TextView textViewSize15;
static TextView textViewSize19;
static TextView textViewSize25;
static TextView textViewSize31;
static TextView textViewSize37;
static TextView textViewSize46;
static TextView textViewSize62;
static TextView textViewSupplyPressure;
static TextView textViewSelectPipeLength;
public static Integer baseTableRowNumber = 0;
public static Cursor cursorResult;
// these to int's keep a false Toast message from appearing
private int intSpinnerCountGas = 0;
private int intSpinnerCountSupply = 0;
private int intSpinnerCountLength = 0;
private static final int NO_OF_EVENTS_GAS = 1;
private static final int NO_OF_EVENTS_SUPPLY = 1;
private static final int NO_OF_EVENTS_LENGTH = 1;
#Override
public void onCreate (Bundle state) {
super.onCreate(state);
setContentView(R.layout.main);
//check if app just started or is being restored from memory
if (state != null ) {
//app is being restored from memory, not executed from scratch
//initialize the fields to the last used;
supplyPressureVisible = state.getBoolean("supplyPressureVisible");
pipeLengthVisible = state.getBoolean("pipeLengthVisible");
spinnerTypeGasInt = state.getInt("spinnerTypeGasInt");
spinnerSupplyPressureInt = state.getInt("spinnerSupplyPressureInt");
spinnerPipeLengthInt = state.getInt("spinnerPipeLengthInt");
finalRow = state.getInt("finalRow");
Toast.makeText(getApplicationContext(), "savedInstanceState != null", Toast.LENGTH_LONG).show();
} //end if
// call doInBackground
new LoadDataBaseTask().doInBackground();
mainProgram ();
} // end onCreate
// performs database query outside GUI thread
private class LoadDataBaseTask extends AsyncTask<Object, Object, Cursor> {
DataBaseHelper myDbHelper = new DataBaseHelper(CSSTPipeSizingActivity.this);
// perform the database access
#Override
protected Cursor doInBackground (Object... params) {
try {
myDbHelper.createDataBase();
}
catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}
catch(SQLException sqle) {
throw sqle;
}
return myDbHelper.getData();
} // end method doInBackground
// use the Cursor returned from the doInBackground method
#Override
protected void onPostExecute(Cursor result) {
//myDbHelper.changeCursor(result); // set the adapter's Cursor
myDbHelper.close();
} // end method onPostExecute
} // end class LoadDataBaseTask
public void mainProgram () {
spinnerTypeGas = (Spinner) findViewById(R.id.spinnerTypeGas);
spinnerSupplyPressure = (Spinner) findViewById(R.id.spinnerSupplyPressure);
spinnerPipeLength = (Spinner) findViewById(R.id.spinnerPipeLength);
spinnerSupplyPressure.setVisibility(View.INVISIBLE);
textViewSelectPipeLength.setVisibility(View.INVISIBLE);
spinnerPipeLength.setVisibility(View.INVISIBLE);
if (supplyPressureVisible == true) spinnerSupplyPressure.setVisibility(View.VISIBLE);
else spinnerSupplyPressure.setVisibility(View.INVISIBLE);
if (pipeLengthVisible == true) spinnerPipeLength.setVisibility(View.VISIBLE);
else spinnerPipeLength.setVisibility(View.INVISIBLE);
//Sets up the spinnerTypeGas spinner
ArrayAdapter<CharSequence> adapterTypeGas = ArrayAdapter.createFromResource(
this, R.array.TypeGas, android.R.layout.simple_spinner_item);
adapterTypeGas.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerTypeGas.setAdapter(adapterTypeGas);
//Sets up the spinnerPipeLength spinner
ArrayAdapter<CharSequence> adapterPipeLength = ArrayAdapter.createFromResource(
this, R.array.PipeLength, android.R.layout.simple_spinner_item);
adapterPipeLength.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerPipeLength.setAdapter(adapterPipeLength);
// Listens for changes in the selected item in each spinner
spinnerTypeGas.setOnItemSelectedListener(new GASOnItemSelectedListener());
spinnerSupplyPressure.setOnItemSelectedListener(new SupplyOnItemSelectedListener());
spinnerPipeLength.setOnItemSelectedListener(new MyOnItemSelectedListener());
} // end mainProgram
public void SpinnerNatGas() {
ArrayAdapter<CharSequence> adapterSupplyPressure = ArrayAdapter.createFromResource(
this, R.array.NaturalGas, android.R.layout.simple_spinner_item);
adapterSupplyPressure.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerSupplyPressure.setAdapter(adapterSupplyPressure);
adapterSupplyPressure.notifyDataSetChanged();
} // end SpinnerNatGAs ()
public void SpinnerProGas () {
ArrayAdapter<CharSequence> adapterSupplyPressure = ArrayAdapter.createFromResource(
this, R.array.PropaneGas, android.R.layout.simple_spinner_item);
adapterSupplyPressure.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerSupplyPressure.setAdapter(adapterSupplyPressure);
adapterSupplyPressure.notifyDataSetChanged();
} // end SpinnerProGAs ()
public class GASOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// this prevents false firing of Toast messages
if (intSpinnerCountGas < NO_OF_EVENTS_GAS) {
intSpinnerCountGas++;
} // end if
else {
spinnerTypeGasInt = spinnerTypeGas.getSelectedItemPosition();
if(spinnerTypeGasInt == 1) {
//populate spinnerSupplyPressure accordingly
SpinnerNatGas();
} // end if
else if(spinnerTypeGasInt == 2) {
//populate spinnerSupplyPressure accordingly
SpinnerProGas();
} // end else if
if (spinnerTypeGasInt != 0) {
spinnerSupplyPressure.setVisibility(View.VISIBLE);
textViewSupplyPressure.setVisibility(View.VISIBLE);
spinnerSupplyPressure.setSelection(0);
spinnerPipeLength.setSelection(0);
supplyPressureVisible = true;
} // end else if
else {
spinnerSupplyPressure.setVisibility(View.INVISIBLE);
textViewSupplyPressure.setVisibility(View.INVISIBLE);
textViewSelectPipeLength.setVisibility(View.INVISIBLE);
spinnerPipeLength.setVisibility(View.INVISIBLE);
supplyPressureVisible = false;
pipeLengthVisible = false;
}// end else
}// end if for false Toast message at app launch
} // end onItemSelected
public void onNothingSelected(AdapterView<?> arg0) {
// nothing to do
} // end onNothingSelected
} // end class GASOnItemSelectedListener
public class SupplyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// this prevents false firing of Toast messages
if (intSpinnerCountSupply < NO_OF_EVENTS_SUPPLY) {
intSpinnerCountSupply++;
} // end if
else {
spinnerSupplyPressureInt = spinnerSupplyPressure.getSelectedItemPosition();
if (spinnerSupplyPressureInt != 0) {
textViewSelectPipeLength.setVisibility(View.VISIBLE);
spinnerPipeLength.setVisibility(View.VISIBLE);
pipeLengthVisible = true;
spinnerPipeLength.setSelection(0);
} // end if
else {
textViewSelectPipeLength.setVisibility(View.INVISIBLE);
spinnerPipeLength.setVisibility(View.INVISIBLE);
pipeLengthVisible = false;
} // end else
}// end if for false Toast message at app launch
} // end onItemSelected
public void onNothingSelected(AdapterView<?> arg0) {
// nothing to do
} // end onNothingSelected
} // end class SupplyOnItemSelectedListener
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
if (intSpinnerCountLength < NO_OF_EVENTS_LENGTH) {
intSpinnerCountLength++;
} // end if
else {
// This also gives the Row to look in the database for the CFH
baseTableRowNumber = 0;
spinnerPipeLengthInt = spinnerPipeLength.getSelectedItemPosition();
//spinnerPipeLengthText = spinnerPipeLength.getSelectedItem().toString();
// calculates the base table row number and stores it in variable baseTableRowNumber
if (spinnerTypeGasInt == 1) {// Natural Gas is selected
baseTableRowNumber = (spinnerSupplyPressureInt - 1) * 18;
}
else if (spinnerTypeGasInt == 2) { // Propane is selected
baseTableRowNumber = 198 + (spinnerSupplyPressureInt - 1) * 18;
} // end else if
showResults();
} // end else for check if firing at inializing
} // end onItemSelected
public void onNothingSelected(AdapterView<?> arg0) {
// nothing to do
} // end onNothingSelected
} // end class MyOnItemSelectedListener
public void showResults () {
if (CSSTPipeSizingActivity.cursorResult != null) {
finalRow = (baseTableRowNumber + spinnerPipeLengthInt);
if (finalRow < 0) {
finalRow = 0;
}
if (finalRow == 0) {
textViewSize15.setText(String.valueOf("0"));
textViewSize19.setText(String.valueOf("0"));
textViewSize25.setText(String.valueOf("0"));
textViewSize31.setText(String.valueOf("0"));
textViewSize37.setText(String.valueOf("0"));
textViewSize46.setText(String.valueOf("0"));
textViewSize62.setText(String.valueOf("0"));
} // end if
else {
cursorResult.moveToPosition(finalRow);
textViewSize15.setText(String.valueOf(cursorResult.getInt(1)));
textViewSize19.setText(String.valueOf(cursorResult.getInt(2)));
textViewSize25.setText(String.valueOf(cursorResult.getInt(3)));
textViewSize31.setText(String.valueOf(cursorResult.getInt(4)));
textViewSize37.setText(String.valueOf(cursorResult.getInt(5)));
textViewSize46.setText(String.valueOf(cursorResult.getInt(6)));
textViewSize62.setText(String.valueOf(cursorResult.getInt(7)));
} // end else
} // end if
} //end showResults
} // end class CSSTPipeSizingActivity
In the first three lines of the mainProgram() method I declare my three spinners and then begin to populate them. when the user selects a choice from spinnerTypeGas then the next spinner (spinnerSupplyPressure) becomes visible. then when the user selects an item from that spinnerSupplyPressure the third spinner (spinnerPipeLenght) becomes visible. Data is then displayed that is retrieved from a database. Each spinner gets its array list from the string.xml file
I have a problem where I want to make the comparison the data in button
package lynn.calculate.KaunterKalori;
import lynn.calculate.KaunterKalori.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.EditText;
public class CalculateAll extends Activity implements OnClickListener {
protected int totalKalori1;
protected int totalKalori2;
protected int totalKalori3;
EditText EstimateCalorie;
TextView TotalKaloriSehari;
TextView totalsarapan;
TextView totallunch;
TextView totaldinner;
TextView calorieneeds;
TextView resultDiff;
public CalculateAll() {
}
#Override
public void onCreate(Bundle savedInstancesState) {
super.onCreate(savedInstancesState);
setContentView(R.layout.calculate_all);
View kiraButton = findViewById(R.id.buttonKiraAll);
kiraButton.setOnClickListener(this);
View bezaButton = findViewById(R.id.caloriediff);
bezaButton.setOnClickListener(this);
TotalKaloriSehari = (TextView) findViewById(R.id.JumlahKalori);
totalsarapan = (TextView) findViewById(R.id.sarapantext);
totallunch = (TextView) findViewById(R.id.lunchtext);
totaldinner = (TextView) findViewById(R.id.dinnertext);
EstimateCalorie = (EditText) findViewById(R.id.BMR);
// calorieneeds = (TextView) findViewById(R.id.BMR);
resultDiff = (TextView) findViewById(R.id.result);
Bundle extras = getIntent().getExtras();
if (extras != null) {
totalKalori1 = extras.getInt("totalBreakfast");
totalKalori2 = extras.getInt("totalLunch");
totalKalori3 = extras.getInt("totalDinner");
}
totalsarapan.setText(totalKalori1 + "");
totallunch.setText(totalKalori2 + "");
totaldinner.setText(totalKalori3 + "");
}
public void onClick(View v) {
if (v.getId() == R.id.buttonKiraAll) {
int TotalKalori = calculateTotalKalori(totalKalori1, totalKalori2,
totalKalori3);
TotalKaloriSehari.setText(TotalKalori + "");
}
else if (v.getId()== R.id.caloriediff) {
int nilaikalori = Integer.parseInt(EstimateCalorie.getText()
.toString());
int bmr = calculatebmr(nilaikalori);
String deskripsiKalori = describekalori(bmr);
resultDiff.setText("kalori makanan" + TotalKalori + " calori diperlukan " + bmr + "=" + deskripsiKalori);
// --> this TotalKalori also can't be used
Intent n = new Intent(this, MainActivity.class);
startActivity(n);
}
}
public int calculateTotalKalori(int totalKalori1, int totalKalori2,
int totalKalori3) {
return (int) (totalKalori1 + totalKalori2 + totalKalori3);
}
public int calculatebmr(int nilaikalori) {
return (int) (nilaikalori);
}
private String describekalori(int bmr) {
if (bmr < TotalKalori ) { //<-- this TotalKalori can't be read/used
return "bykkan makan";
} else if (bmr == TotalKalori) {
return "kekalkan jumlah kalori ini";
} else if (bmr > TotalKalori) {
return "kurangkan pengambilan kalori";
} else
return "oiii";
}
}
The first button, buttonKiraAll read int totalKalori, then i want to use the totalKalori data to be compare with 2nd data button calorieDiff, how i want to make the totalKalori can be read by the second button? so i can make the comparison
It's a scoping problem, you are declaring int TotalKalori locally in the onClick event.
Declare it like you have done with totalKalori1 and it should work
Or you can use getTag(); setTag(); to store the variables on the buttons...
Use setTag to the data you want
myButton.setTag("fun Stuff");
Then on the listener just get the tag (you will need to do a type cast):
OnClickListener myListner = new OnClickListener() {
public void onClick(View view) {
doSomethingAwesome(view, (String) view.getTag());
}
};
Declare int TotalKalori only once globally (in the section you declared protected int totalKalori1; protected int totalKalori2;... ) and simply use it for both buttons like: in button1 TotalKalori = calculateTotalKalori(totalKalori1, totalKalori2,totalKalori3); this value is global so button2 already can acess it by simply using TotalKalori where you need and also the comparison portion.