如何在Android中的类/活动之间传递值数据?

时间:2012-05-20 14:45:56

标签: android android-intent

例如,我有activity1,activity2,activity3,最后是valueAllActivity? 如何将数据从activity1,activity2,activity3传递到 - > valueAllActivity?

将每个活动中的INT值传递给valueAllActivity。

我是开发Android程序的新手,所以如果有人可以指导,那将是一种荣誉:) 谢谢

//活性1

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

}
}

//活动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);
}

}

//活动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 - 我想要添加所有值(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);

}


}

谢谢任何试图帮助我的人。非常感谢:)正如你所知,我在早期阶段开发程序,所以非常感谢大家:)

6 个答案:

答案 0 :(得分:5)

你会通过意图来做到这一点。假设data1和data2是字符串,data3是int。

在您设置调用下一个活动的意图时的第一个活动中:

Intent myIntent = new Intent(Activity1.this, Activity2.class);
myIntent.putExtra("Data1", data1);
myIntent.putExtra("Data2", data2);
myIntent.putExtra("Data3", data3);
Activity1.this.startActivity(myIntent);

然后在活动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);

依此类推,通过尽可能多的活动。

您可以使用您想要的任何标识符。上面我使用了Data1,Data2,Data3。它们也可以被称为Make,Model和TopSpeed。只要您使用相同的ID来获取数据就可以了,它就没问题了。

修改

我看到的一些事情......

首先,使用getExtra从onCreate方法中为每个活动从数据包中获取数据。将意图调用到您需要的任何地方。

然后,您的一个问题出现在活动2中:

    if (extras != null){ 
        totalKalori1 = extras.getInt("totalBreakfast"); 
        totalKalori2 = extras.getInt("totalLunch"); 
    } 

您尚未将totalLunch放入捆绑包中,因此您不应该尝试get它。删除该行。

活动3中的相同事项:

    if (extras != null){    
        totalKalori1 = extras.getInt("totalBreakfast");    
        totalKalori2 = extras.getInt("totalLunch");    
        totalKalori3 = extras.getInt("totalDinner");    
    }    

您尚未将totalDinner放入捆绑包中,因此您不应该尝试get它。删除该行。

然后在Calculate All中你设置了一个不必要的意图并重新开始活动...这对我来说就像是会导致一个infintie循环:

    Intent n= new Intent(this, CalculateAll.class);         
    n.putExtra("totalBreakfast", totalKalori1);         
    n.putExtra("totalLunch", totalKalori2);         
    n.putExtra("totalDinner", totalKalori3);         
    startActivity(n); 

从'CalculateAll`活动中删除整个部分。

我认为移动getExtra部分并删除不良数据将解决您的问题。

答案 1 :(得分:4)

您有几种选择:

  1. 在活动之间移动时,使用intents传递数据。
  2. 使用全局application状态bean,您可以通过扩展Application类来创建该类,然后您可以通过调用getApplication()方法在活动中访问该类。
  3. 如果共享数据是用户提供的内容,请使用SharedPreferences api。
  4. 如果您希望数据在关闭并重新启动时即使可用,也可以将数据保留到SQLite数据库并在每个活动中检索它。
  5. 阅读documentation,了解在应用程序中存储和检索数据的所有可用方法。

答案 2 :(得分:2)

你有一些可能性。

我更喜欢的是使用应用程序上下文......

创建一个新类,如:

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

}

将此添加到您的清单:

<application
        android:name=".DataApp"
...>
...

    </application>

之后,当您需要传递数据时,您可以在您的活动中执行此操作:

DataApp dataInfo = (DataApp)getApplicationContext();

//set some data:

dataInfo.setMyObj(/*put the object*/);

在你的其他活动中,你会得到这样的对象:

DataApp dataInfo = (DataApp)getApplicationContext();
MyCustomObject obj = dataInfo.getMyObj();

使用此选项,您可以传递所需的每种对象类型。

答案 3 :(得分:0)

将数据从一个活动传递到另一个活动的推荐方法是通过意图

查看this tutorial

答案 4 :(得分:0)

要使用意图,请执行以下操作:

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

答案 5 :(得分:0)

我在活动中使用了一种方法来调用另一个活动。 它以两个变量(简历和玩家数量)开始游戏。

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

在NextActivity的'onCreate'中,我使用了

int resume = getIntent().getIntExtra(Game.RESUME, 1);

读取我想要的变量。

祝你好运!