简体   繁体   中英

How to pass a variable from one class to another in Android development

i am new to java and i need some help. I need to transfer the bmivalue variable from the MainActivity to the goal class. I have researched other posts on how to do this but i cant figure out how to do it in this situation.

package com.example.bmiworking;

import android.os.Bundle;
import android.app.Activity;
import android.content.DialogInterface;
import android.view.View.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class goal extends Activity {
    Button btn;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.goal);
        btn = (Button) findViewById(R.id.bmiButton);
        btn.setText(bmiValue);
}
}


package com.example.bmiworking;

import android.app.Activity;
import android.content.DialogInterface;
import android.view.View.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
Button btn;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn = (Button) findViewById(R.id.homeClickHandler);
    btn.setOnClickListener(this);
}

    @Override
public void onClick(View v) {
    if (v.getId() == R.id.homeClickHandler) {
        startActivity(new Intent(this, MainMenu.class));
    }
}

public void calculateClickHandler(View view) {
    // make sure we handle the click of the calculator button

    if (view.getId() == R.id.calculateButton) {

        // get the references to the widgets
        EditText weightText = (EditText) findViewById(R.id.weightText);
        EditText heightText = (EditText) findViewById(R.id.heightText);
        TextView resultText = (TextView) findViewById(R.id.resultLabel);

        // get the users values from the widget references

        float weight = Float.parseFloat(weightText.getText().toString());
        float height = Float.parseFloat(heightText.getText().toString());

        // calculate the bmi value

        float bmiValue = calculateBMI(weight, height);

        // interpret the meaning of the bmi value
        String bmiInterpretation = interpretBMI(bmiValue);

        // now set the value in the result text

        resultText.setText(bmiValue + "-" + bmiInterpretation);
    }
}

// the formula to calculate the BMI index

// check for http://en.wikipedia.org/wiki/Body_mass_index
private float calculateBMI(float weight, float height) {

    return (float) (weight * 4.88 / (height * height));
}

// interpret what BMI means
private String interpretBMI(float bmiValue) {

    if (bmiValue < 16) {
        return "Severely Underweight - See Weight Gain";
    } else if (bmiValue < 18.5) {

        return "Underweight - See Weight Gain";
    } else if (bmiValue < 25) {

        return "Normal - No Recomendations";
    } else if (bmiValue < 30) {

        return "Overweight - See Weight Loss";
    } else {
        return "Obese - See Weight Loss";
    }

}

}

We can pass the variables and values from one class to another through the use of intent . The sample code I have used in my hotels project is as below. hope it will help you

Intent in = new Intent(getApplicationContext(), goal.class);
in.putExtra("h_id", h_id);
in.putExtra("lat1", lat1);
in.putExtra("lon1", lon1);
startActivity(in);

here in this way you can start next class execution with intent and passing values from present class to goal class with use of in.putExtras("varible_name in new class, value ")

and in the new class goal use

Intent in = getIntent();
        h_id = in.getStringExtra("h_id");
        lat1 = in.getDoubleExtra("lat1", 0);
        lon1 = in.getDoubleExtra("lon1", 0);

You can start your goal activity with an intent, that has a Bundle-type object of extra values in it, like this:

Intent intent = new Intent(this, MainActivity.class);
Bundle extras = new Bundle();
extras.putInt("int-key", int_value);
extras.putString("string-key", string_value);
extras.putFloat("float-key", float_value);
intent.putExtras(extras);
startActivity(intent);

Then inside your goal class you can put this code into your onCreate() method to retrieve the values:

Intent receivedIntent = getIntent();
Bundle extras = intent.getExtras();
int int_value = extras.getInt("int-key", 0);
String string_value = extras.getString("string-key", "");
float float_value = extras.getFloat("float-key", 0.0);

If this is Still open and being looked at you really should be using shared preferences for this. http://developer.android.com/guide/topics/data/data-storage.html#pref

simpler and more efficient than intents and with shared prefs you can pass data to fragments as well as activities and vice versa

There are a few ways.

I think a useful way to make your data available 'globally' is to create the data structures in a sub class of Application. There is one Application object that is always available in any activity. When you extend the Application class, you must note that in the manifest.

You can retrieve your application object,

  MyApplication myApp = (MyApplication) getApplication();

and then your data structure,

  ArrayList<Thing> myThings = myApp.getMyData();

You can retrieve and modify the data structure in any activity. I'd be interested to know if this is how others are doing this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM