Kebab Programmer
Kebab Programmer

Reputation: 1219

Sending Data From One Activity to Another Without Creating a new Intent Android

i have an impending question that is mind buggling me at the moment in regards to android app development.

In my app, which works exactly the way i want it to, except for one part i have problem figuring out is how will i send a piece of data from one activity to another without making a new Intent.

In my Code, the user inputs his Name, Mass, and Height, and when the user clicks on Button calculate, it takes all the values in a new intent to a second activity, there, it calculates the BMI of the user. Now, i want to send this freshly calculated BMI back to the First activity without creating a new intent but i am now sure on how to go about that

Here are the relevant part of my Code

Main Activity.java

package mobileapp.melvin.bmicalculator;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.*;
import android.content.*;
import android.widget.*;

public class MainActivity extends Activity {

public String name,mass,height,bmi;
public EditText nameField, massField, heightField;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    bmi = getIntent().getStringExtra("BMI");

    //Create "TextFields" By getting ID of Editviews from Main XML
    nameField = (EditText) findViewById(R.id.mText_box1);
    massField = (EditText) findViewById(R.id.mText_box2);
    heightField = (EditText) findViewById(R.id.mText_box3);

    //Button To calculate and display BMI as TextViews
    Button launchBtn = (Button) findViewById(R.id.mButton_calculate);
    launchBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            //Check is The "Textfields" have values
            if(!verifyData()){
                return;
            }
            /*Create a new Intent to Launch another activity 
             * To display all the Values gotten from
             * The TextFields as Normal Text Values
             */
            Intent launcher = new Intent(v.getContext(),BMI1.class);
            //This intent then passes these values over to the next Intent
            launcher.putExtra("Name", name);
            launcher.putExtra("Mass", mass);
            launcher.putExtra("Height", height);
            //We then start this new activity with the new Intent
            startActivity(launcher);
        }
    });
}

and BMI1.java

package mobileapp.melvin.bmicalculator;

import android.app.*;
import android.content.*;
import android.os.*;
import android.view.*;
import android.widget.*;

public class BMI1 extends Activity {

String name,mass,height,bmi;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bmi1);

    //Get data from the first activity through intent
     name = getIntent().getStringExtra("Name");
     mass = getIntent().getStringExtra("Mass");
     height = getIntent().getStringExtra("Height");

     //convert mass and height to double and calculate BMI
     double m = Double.parseDouble(mass);
     double h = Double.parseDouble(height);
     bmi = Double.toString(calculateBMI(m, h));

    ((TextView) findViewById(R.id.b1_Label2)).setText(name);
    ((TextView) findViewById(R.id.b1_Label4)).setText(mass);
    ((TextView) findViewById(R.id.b1_Label6)).setText(height);
    ((TextView) findViewById(R.id.b1_Label8)).setText(bmi);


    Button backBtn = (Button) findViewById(R.id.b1Button_back);
    backBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent launcher = getIntent();
            launcher.putExtra("BMI", bmi);
            finish();
        }
    });
}

  private double calculateBMI(double toMass, double toHeight){
      double value;

      value = toMass/(toHeight * toHeight);
      return value;
  }

}

I know there is no value passed because when a user clicks Display in the first Activity, it takes the values to a third Activity where a textView Should display For example "BMI: 20.66" but instead i get "BMI: null", how will i fix this error?

Upvotes: 1

Views: 15217

Answers (3)

Deminem
Deminem

Reputation: 672

To solve the above problem properly, android provides startActivityForResult that basically launch an activity for which you would like a result when it finished.

For example, here's how to start an activity that allows the user to pick a contact:

static final int PICK_CONTACT_REQUEST = 1;  // The request code
...
private void pickContact() {
    Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
    pickContactIntent.setType(Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers
    startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);
}

Receive the Result

When the user is done with the subsequent activity and returns, the system calls your activity's onActivityResult() method. This method includes three arguments:

  • The request code you passed to startActivityForResult().
  • A result code specified by the second activity. This is either RESULT_OK if the operation was successful or RESULT_CANCELED if the user backed out or the operation failed for some reason.
  • An Intent that carries the result data.

For example, here's how you can handle the result for the "pick a contact" intent:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Check which request we're responding to
    if (requestCode == PICK_CONTACT_REQUEST) {
        // Make sure the request was successful
        if (resultCode == RESULT_OK) {
            // The user picked a contact.
            // The Intent's data Uri identifies which contact was selected.

            // Do something with the contact here (bigger example below)
        }
    }
}

You can see the complete example of startActivityForResult in this article here.

Upvotes: 1

eminem
eminem

Reputation: 41

You don't have to always use Intent to send data between activities. You use other android storage options like Sqlite db, SharedPreferences. You can also store data on SDcard. Have a look at Android storage options here

Upvotes: 2

DevOps85
DevOps85

Reputation: 6523

For send data between Activity without using Intent you can use SharedPreferences or SQlite db.

Example for SharedPreferences:

// Create object of SharedPreferences.
 SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
 //now get Editor
 SharedPreferences.Editor editor = sharedPref.edit();
 //put your value
 editor.putString("userName", "stackoverlow");

 //commits your edits
 editor.commit();

Using putString(),putBoolean(),putInt(),putFloat(),putLong() you can save your desired dtatype.

and to fetch data:

SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
String userName = sharedPref.getString("userName", "Not Available");

Upvotes: 1

Related Questions