how to pass value data between classes/activity in Android? - android

For example i have activity1, activity2, activity3 and lastly valueAllActivity?
how do I pass the data from activity1, activity2, activity3 to --> valueAllActivity?
to pass INT value in each activity to valueAllActivity.
I am very new in developing Android program, so if anyone could guide, it would be an honor :)
Thank you
//Activity1
package lynn.calculate.KaunterKalori;
import lynn.calculate.KaunterKalori.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.content.Intent;
public class Breakfast extends Activity {
public static int TotalKalori;
ArrayAdapter<String> FoodType1Adapter;
ArrayAdapter<String> DrinkType1Adapter;
String FoodTypeArray[] = { "","white bread"}
int[] valueFoodTypeArray = { 0,20};
String[] DrinkTypeArray = { "","tea"};
int[] valueDrinkTypeArray = { 0,201};
Spinner FoodTypeSpinner;
Spinner DrinkTypeSpinner;
TextView SarapanTotalKalori;
public void onCreate(Bundle savedInstancesState) {
super.onCreate(savedInstancesState);
setContentView(R.layout.breakfast);
FoodTypeSpinner = (Spinner) findViewById(R.id.spinner1);
DrinkTypeSpinner = (Spinner) findViewById(R.id.spinner2);
SarapanTotalKalori = (TextView) findViewById(R.id.JumlahKalori);
initializeSpinnerAdapters();
// load the default values for the spinners
loadFoodValue1Range();
loadDrinkValue1Range();
}
// nk handle button --> refer calculate button
public void calculateClickHandler(View view) {
if (view.getId() == R.id.button1) {
// nk bace dkat spinner
int food1 = getSelectedFood();
int drink1 = getSelectedDrink();
// kira kalori sarapan
// view kalori sarapan
int totalKalori1 = calculateSarapan(food1, drink1);
SarapanTotalKalori.setText(totalKalori1 + "");
//setttlBreakfast(totalKalori1);
Intent b= new Intent(Breakfast.this, Lunch.class);
b.putExtra("totalBreakfast",totalKalori1);
Breakfast.this.startActivity(b);
}
}
public int getSelectedFood() {
String selectedFoodValue = (String) FoodTypeSpinner.getSelectedItem();
int index = 0;
for (int i = 0; i < FoodTypeArray.length; i++) {
if (selectedFoodValue.equals(FoodTypeArray[i])) {
index = i;
break;
}
}
return valueFoodTypeArray[index];
}
public int getSelectedDrink() {
String selectedDrinkValue = (String) DrinkTypeSpinner.getSelectedItem();
int index = 0;
for (int i = 0; i < DrinkTypeArray.length; i++) {
if (selectedDrinkValue.equals(DrinkTypeArray[i])) {
index = i;
break;
}
}
return valueDrinkTypeArray[index];
}
public int calculateSarapan(int food1, int drink1) {
return (int) (food1 + drink1);
}
public void loadFoodValue1Range() {
FoodTypeSpinner.setAdapter(FoodType1Adapter);
// set makanan b4 pilih
FoodTypeSpinner.setSelection(FoodType1Adapter.getPosition("400"));
}
public void loadDrinkValue1Range() {
DrinkTypeSpinner.setAdapter(DrinkType1Adapter);
DrinkTypeSpinner.setSelection(DrinkType1Adapter.getPosition("77"));
}
public void initializeSpinnerAdapters() {
FoodType1Adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, FoodTypeArray);
DrinkType1Adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, DrinkTypeArray);
}
}
//Acitivity 2
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.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class Lunch extends Activity {
public static int TotalKalori;
private int totalKalori1;
/* private int ttlLunch;
public void setttlLunch(int ttlLunch){
this.ttlLunch=ttlLunch;
}
public int getttlLunch(){
return ttlLunch;
} */
ArrayAdapter<String> FoodType2Adapter;
ArrayAdapter<String> DrinkType2Adapter;
ArrayAdapter<String> LaukType2Adapter;
String FoodType2Array[] = { "","Burger"};
int[] valueFoodType2Array = { 0, 150 };
String DrinkType2Array[] = { "","Pepsi" };
int[] valueDrinkType2Array = { 0,100 };
String LaukType2Array[] = { "","Wings" };
int[] valueLaukType2Array = { 0,200 };
Spinner FoodType2Spinner;
Spinner DrinkType2Spinner;
Spinner LaukType2Spinner;
TextView LunchTotalKalori;
protected void onCreate(Bundle savedInstancesState) {
super.onCreate(savedInstancesState);
setContentView(R.layout.lunch);
FoodType2Spinner = (Spinner) findViewById(R.id.spinner1);
LaukType2Spinner = (Spinner) findViewById(R.id.spinner2);
DrinkType2Spinner = (Spinner) findViewById(R.id.spinner3);
LunchTotalKalori = (TextView) findViewById(R.id.JumlahKalori);
initializeSpinnerAdapters();
loadFoodValue2Range();
loadDrinkValue2Range();
loadLaukValue2Range();
}
public void calculateClickHandler(View view) {
if (view.getId() == R.id.button1) {
int food2 = getSelectedFood2();
int drink2 = getSelectedDrink2();
int lauk2 = getSelectedLauk2();
int totalKalori2 = calculateLunch(food2, drink2, lauk2);
LunchTotalKalori.setText(totalKalori2 + "");
Bundle extras = getIntent().getExtras();
if (extras != null){
totalKalori1 = extras.getInt("totalBreakfast");
totalKalori2 = extras.getInt("totalLunch");
}
//setttlLunch(totalKalori2);
Intent n= new Intent(Lunch.this, Dinner.class);
n.putExtra("totalBreakfast", totalKalori1);
n.putExtra("totalLunch", totalKalori2);
Lunch.this.startActivity(n);
}
}
public int getSelectedFood2() {
String selectedFoodValue2 = (String) FoodType2Spinner.getSelectedItem();
int index = 0;
for (int i = 0; i < FoodType2Array.length; i++) {
if (selectedFoodValue2.equals(FoodType2Array[i])) {
index = i;
break;
}
}
return valueFoodType2Array[index];
}
public int getSelectedDrink2() {
String selectedDrinkValue2 = (String) DrinkType2Spinner
.getSelectedItem();
int index = 0;
for (int i = 0; i < DrinkType2Array.length; i++) {
if (selectedDrinkValue2.equals(DrinkType2Array[i])) {
index = i;
break;
}
}
return valueDrinkType2Array[index];
}
public int getSelectedLauk2() {
String selectedLaukValue2 = (String) LaukType2Spinner.getSelectedItem();
int index = 0;
for (int i = 0; i < LaukType2Array.length; i++) {
if (selectedLaukValue2.equals(LaukType2Array[i])) {
index = i;
break;
}
}
return valueLaukType2Array[index];
}
public int calculateLunch(double food2, double drink2, double lauk2) {
return (int) (food2 + drink2 + lauk2);
}
public void loadFoodValue2Range(){
FoodType2Spinner.setAdapter(FoodType2Adapter);
FoodType2Spinner.setSelection(FoodType2Adapter.getPosition("200"));
}
public void loadDrinkValue2Range(){
DrinkType2Spinner.setAdapter(DrinkType2Adapter);
DrinkType2Spinner.setSelection(DrinkType2Adapter.getPosition("77"));
}
public void loadLaukValue2Range(){
LaukType2Spinner.setAdapter(LaukType2Adapter);
LaukType2Spinner.setSelection(LaukType2Adapter.getPosition("2"));
}
public void initializeSpinnerAdapters(){
FoodType2Adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, FoodType2Array);
DrinkType2Adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, DrinkType2Array);
LaukType2Adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, LaukType2Array);
}
}
//Activity 3
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.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class Dinner extends Activity {
public static int TotalKalori;
private int totalKalori1;
private int totalKalori2;
/*private int ttlDinner;
public void setttlDinner(int ttlDinner){
this.ttlDinner=ttlDinner;
}
public int getttlDinner(){
return ttlDinner;
} */
ArrayAdapter<String> FoodType3Adapter;
ArrayAdapter<String> ProteinType3Adapter;
ArrayAdapter<String> DrinkType3Adapter;
String FoodType3Array[] = { "","chicken chop" };
int[] valueFoodType3Array = { 0, 204};
String ProteinType3Array[] = { "","chicken breast", };
int[] valueProteinType3Array = { 0, 40 };
String DrinkType3Array[] = { "","mineral water" };
int[] valueDrinkType3Array = { 0, 0};
Spinner FoodType3Spinner;
Spinner ProteinType3Spinner;
Spinner DrinkType3Spinner;
TextView DinnerTotalKalori;
protected void onCreate(Bundle savedInstancesState) {
super.onCreate(savedInstancesState);
setContentView(R.layout.dinner);
FoodType3Spinner = (Spinner) findViewById(R.id.spinner1);
ProteinType3Spinner = (Spinner) findViewById(R.id.spinner2);
DrinkType3Spinner = (Spinner) findViewById(R.id.spinner3);
DinnerTotalKalori = (TextView) findViewById(R.id.JumlahKalori);
initializeSpinnerAdapters();
loadFoodValue3Range();
loadProteinValue3Range();
loadDrinkValue3Range();
}
public void calculateClickHandler(View view) {
if (view.getId() == R.id.button1) {
int food3 = getSelectedFood3();
int protein3 = getSelectedProtein3();
int drink3 = getSelectedDrink3();
int totalKalori3 = calculateDinner(food3, protein3, drink3);
DinnerTotalKalori.setText(totalKalori3 + "");
Bundle extras = getIntent().getExtras();
if (extras != null){
totalKalori1 = extras.getInt("totalBreakfast");
totalKalori2 = extras.getInt("totalLunch");
totalKalori3 = extras.getInt("totalDinner");
}
//setttlDinner(totalKalori3);
Intent d= new Intent(Dinner.this, CalculateAll.class);
d.putExtra("totalBreakfast", totalKalori1);
d.putExtra("totalLunch", totalKalori2);
d.putExtra("totalDinner", totalKalori3);
startActivity(d);
}
}
public int getSelectedFood3() {
String selectedFoodValue3 = (String) FoodType3Spinner.getSelectedItem();
int index = 0;
for (int i = 0; i < FoodType3Array.length; i++) {
if (selectedFoodValue3.equals(FoodType3Array[i])) {
index = i;
break;
}
}
return valueFoodType3Array[index];
}
public int getSelectedProtein3() {
String selectedProteinValue3 = (String) ProteinType3Spinner
.getSelectedItem();
int index = 0;
for (int i = 0; i < ProteinType3Array.length; i++) {
if (selectedProteinValue3.equals(ProteinType3Array[i])) {
index = i;
break;
}
}
return valueProteinType3Array[index];
}
public int getSelectedDrink3() {
String selectedDrinkValue3 = (String) DrinkType3Spinner
.getSelectedItem();
int index = 0;
for (int i = 0; i < DrinkType3Array.length; i++) {
if (selectedDrinkValue3.equals(DrinkType3Array[i])) {
index = i;
break;
}
}
return valueDrinkType3Array[index];
}
public int calculateDinner(int food3, int protein3, int drink3) {
return (int) (food3 + protein3 + drink3);
}
public void loadFoodValue3Range() {
FoodType3Spinner.setAdapter(FoodType3Adapter);
FoodType3Spinner.setSelection(FoodType3Adapter.getPosition("10"));
}
public void loadProteinValue3Range() {
ProteinType3Spinner.setAdapter(ProteinType3Adapter);
ProteinType3Spinner.setSelection(ProteinType3Adapter.getPosition("99"));
}
public void loadDrinkValue3Range(){
DrinkType3Spinner.setAdapter(DrinkType3Adapter);
DrinkType3Spinner.setSelection(DrinkType3Adapter.getPosition("10"));
}
public void initializeSpinnerAdapters(){
FoodType3Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, FoodType3Array);
ProteinType3Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, ProteinType3Array);
DrinkType3Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, DrinkType3Array);
}
}
// CalulateAllActivity - where I want to add up all the value (int)
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.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class CalculateAll extends Activity {
public static int TotalKalori;
private int totalKalori1;
private int totalKalori2;
private int totalKalori3;
ArrayAdapter<String> SexTypeAdapter;
String SexTypeArray[] = { "Lelaki", "Perempuan" };
Spinner SexTypeSpinner;
TextView TotalKaloriSehari;
TextView totalsarapan;
public CalculateAll() {
}
#Override
public void onCreate(Bundle savedInstancesState) {
super.onCreate(savedInstancesState);
setContentView(R.layout.calculate_all);
SexTypeSpinner = (Spinner) findViewById(R.id.spinnerSex);
TotalKaloriSehari = (TextView) findViewById(R.id.JumlahKalori);
}
public void calculateClickHandler(View view) {
if (view.getId() == R.id.buttonKiraAll) {
// public final int TotalKalori;
Bundle extras = getIntent().getExtras();
if (extras != null){
totalKalori1 = extras.getInt("totalBreakfast");
totalKalori2 = extras.getInt("totalLunch");
totalKalori3 = extras.getInt("totalDinner");
}
//setttlLunch(totalKalori2);
Intent n= new Intent(this, CalculateAll.class);
n.putExtra("totalBreakfast", totalKalori1);
n.putExtra("totalLunch", totalKalori2);
n.putExtra("totalDinner", totalKalori3);
startActivity(n);
int TotalKalori = calculateTotalKalori(totalKalori1, totalKalori2, totalKalori3);
TotalKaloriSehari.setText(TotalKalori+ "");
// int ttlCAl =getttlBreakfast()+getttlLunch()+getttlDinner();
//String finalString = Integer.toString(calcAll());
//TextView tv1 = (TextView) findViewById(R.id.JumlahKalori);
//tv1.setText(finalString);
}
}
public int calculateTotalKalori(int totalKalori1, int totalKalori2,
int totalKalori3) {
return (int) (totalKalori1 + totalKalori2 + totalKalori3);
}
}
thank you anyone who try to help me. much appreciated :) as you know, I on my early stage developing the program, so thank you very much everyone :)

You would do it via intents. Assume data1 and data 2 are Strings and data3 is an int.
In your first activity when you set the intent to call the next activity:
Intent myIntent = new Intent(Activity1.this, Activity2.class);
myIntent.putExtra("Data1", data1);
myIntent.putExtra("Data2", data2);
myIntent.putExtra("Data3", data3);
Activity1.this.startActivity(myIntent);
Then in Activity 2:
Private String data1;
Private String data2;
Private int data3;
Bundle extras = getIntent().getExtras();
if (extras != null) {
data1 = extras.getString("Data1");
data2 = extras.getString("Data2");
data3 = extras.getInt("Data3");
}
// other code
Intent myIntent = new Intent(Activity2.this, Activity3.class);
myIntent.putExtra("Data1", data1);
myIntent.putExtra("Data2", data2);
myIntent.putExtra("Data3", data3);
Activity2.this.startActivity(myIntent);
And so on, through as many activities as you want.
You can Use any identifier you want. Above I used Data1, Data2, Data3. They could have as well been called Make, Model and TopSpeed. As long as you use the same id to get the data as you use to put it, it'll be fine.
EDIT
Several things I see...
First, use the getExtra to get the data out of the bundle in your onCreate method for each activity. Put the intents to call the next activity wherever you need to.
Then, one of your issues is here in activity 2:
if (extras != null){
totalKalori1 = extras.getInt("totalBreakfast");
totalKalori2 = extras.getInt("totalLunch");
}
You haven't put totalLunch into the bundle yet, so you shouldn't be trying to get it yet. Delete that line.
Same thing in Activity 3:
if (extras != null){
totalKalori1 = extras.getInt("totalBreakfast");
totalKalori2 = extras.getInt("totalLunch");
totalKalori3 = extras.getInt("totalDinner");
}
You haven't put totalDinner into the bundle yet, so you shouldn't be trying to get it yet. Delete that line.
Then in Calculate All you set an unnecessary intent and restart the activity... which looks to me like it would result in an infintie loop:
Intent n= new Intent(this, CalculateAll.class);
n.putExtra("totalBreakfast", totalKalori1);
n.putExtra("totalLunch", totalKalori2);
n.putExtra("totalDinner", totalKalori3);
startActivity(n);
Delete this whole section from the 'CalculateAll` activity.
I think moving the getExtra parts and removing the bad data will fix your issue.

You have several options:
Use intents to pass data when you move between activities.
Use a global application state bean, which you create by extending the Application class, which you can then access in your activity by calling the getApplication() method.
Use the SharedPreferences api if the shared data is something that will be provided by the user.
Persist data to the SQLite database and retrieve it in each Activity, if you want the data to be available even when the application is shutdown and restarted.
Read the documentation for all available ways in which you can store and retrieve data in your application.

You have some possibilities.
One that I like more is using the application context...
Create a new class like:
public class DataApp extends Application{
private int myInt;
private MyCustomObject myObj;
public int getMyInt() { return myInt; }
public void setMyInt(int i) { this.myInt = i; }
public MyCustomObject getMyObj() { return myObj; }
public void setMyObj(MyCustomObject ob) { this.myObj = ob;}
}
Add this to you manifest:
<application
android:name=".DataApp"
...>
...
</application>
After, when you need to pass data you can do this in your activity:
DataApp dataInfo = (DataApp)getApplicationContext();
//set some data:
dataInfo.setMyObj(/*put the object*/);
In your other activity, you get you object like this:
DataApp dataInfo = (DataApp)getApplicationContext();
MyCustomObject obj = dataInfo.getMyObj();
With this option, you can pass every object type you want.

The recommended way to pass data from one activity to another is via intents.
Have a look at this tutorial.

I used a method in an activity to call another activity.
It starts a game with two variables (resume and number of players).
private void MethodToCallAnotherActivity(int resume, int players) {
Intent intent = new Intent(CurrentActivity.this, NextActivity.class);
intent.putExtra(NextActivity.RESUME, resume);
intent.putExtra(NextActivity.PLAYERS, players);
startActivity(intent);
}
in the 'onCreate' of the NextActivity, I used
int resume = getIntent().getIntExtra(Game.RESUME, 1);
to read the variable I wanted.
Good luck!

To pass using the intent just do like that:
private String fUserName;
private String fPassword;
private Boolean fUseProxy;
private String fProxyAddress;
private Integer fProxyPort;
/** Called when the activity is first created. */
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dashboard_activity);
fProjectsButton = (Button) findViewById(R.id.dashProjectsButton);
fUserName = "something";
fPassword = "xxx";
fUseProxy = false;
fProxyAddress = "";
fProxyPort = 80;
fProjectsButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(CodeBaseClientDashBoardActivity.this, CodeBaseClientProjectsActivity.class);
i.putExtra(CodeBaseClientSettingsActivity.PREFERENCE_API_USERNAME, fUserName);
i.putExtra(CodeBaseClientSettingsActivity.PREFERENCE_PASSWORD, fPassword);
i.putExtra(CodeBaseClientSettingsActivity.PREFERENCE_USE_PROXY, fUseProxy);
i.putExtra(CodeBaseClientSettingsActivity.PREFERENCE_PROXY_ADDRESS, fProxyAddress);
i.putExtra(CodeBaseClientSettingsActivity.PREFERENCE_PROXY_PORT, fProxyPort);
startActivity(i);
}
});
}

Related

Android checkboxes, how to implement if statement.

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++;
}
}

Save ArrayList of custom objects and add a new object to ArrayList

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.

How can I give a value to a variable in one Onclicklistener and use that value in another Onclicklistener in Android?

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.

Android 3 Spinners

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

How to compare data(int) in the first and data(int) in second button in Android?

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.

Categories

Resources