java 在不创建新 Intent Android 的情况下将数据从一个 Activity 发送到另一个
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26820900/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sending Data From One Activity to Another Without Creating a new Intent Android
提问by Kebab Programmer
i have an impending question that is mind buggling me at the moment in regards to android app development.
我有一个迫在眉睫的问题,目前正在困扰我关于 android 应用程序开发的问题。
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 intentbut i am now sure on how to go about that
在我的代码中,用户输入他的姓名、质量和身高,当用户单击 Button 计算时,它将新意图中的所有值带到第二个活动中,在那里,它计算用户的 BMI。现在,我想将这个新计算的 BMI 发送回第一个活动而不创建新的意图,但我现在确定如何去做
Here are the relevant part of my Code
这是我的代码的相关部分
Main Activity.java
主要活动.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
和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?
我知道没有传递值,因为当用户在第一个 Activity 中单击 Display 时,它将值带到 textView 应该显示的第三个 Activity 例如“BMI: 20.66”但我得到的是“BMI: null”,怎么会我修复了这个错误?
回答by eminem
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
您不必总是使用 Intent 在活动之间发送数据。您可以使用其他 android 存储选项,例如 Sqlite db、SharedPreferences。您还可以将数据存储在 SD 卡上。在此处查看 Android 存储选项
回答by Deminem
To solve the above problem properly, android provides startActivityForResultthat basically launch an activity for which you would like a result when it finished.
为了正确解决上述问题,android 提供了startActivityForResult,它基本上启动一个活动,当它完成时你想要一个结果。
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:
当用户完成后续活动并返回时,系统会调用您的活动的onActivityResult()
方法。该方法包括三个参数:
- 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 orRESULT_CANCELED
if the user backed out or the operation failed for some reason. - An
Intent
that carries the result data.
- 您传递给 的请求代码
startActivityForResult()
。 - 第二个活动指定的结果代码。这要么
RESULT_OK
是操作成功,要么RESULT_CANCELED
是用户因某种原因退出或操作失败。 - 一个
Intent
携带的结果数据。
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.
您可以startActivityForResult
在此处查看本文中的完整示例。
回答by DevOps85
For send data between Activity without using Intent you can use SharedPreferences or SQlite db.
要在不使用 Intent 的情况下在 Activity 之间发送数据,您可以使用 SharedPreferences 或 SQlite db。
Example for SharedPreferences:
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.
使用 putString(),putBoolean(),putInt(),putFloat(),putLong() 你可以保存你想要的数据类型。
and to fetch data:
并获取数据:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
String userName = sharedPref.getString("userName", "Not Available");