how to pass value data between classes/activity in

2020-02-29 22:40发布

问题:

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 :)

回答1:

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.



回答2:

You have several options:

  1. Use intents to pass data when you move between activities.
  2. 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.
  3. Use the SharedPreferences api if the shared data is something that will be provided by the user.
  4. 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.



回答3:

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.



回答4:

The recommended way to pass data from one activity to another is via intents.

Have a look at this tutorial.



回答5:

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!



回答6:

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