我正在使用mysql将代码检索到我的Main Activity中,该代码存储为字符串。这是有效的,但是当我尝试将它传递给另一个活动时,它就无法工作了。我可能错了,但我正在传递它,就像我对常规c#变量一样。
将变量(string,int)从一个活动传递到另一个活动的正确方法是什么?
答案 0 :(得分:3)
你这样做,同时传递:
var MyIntent = new Intent (this, typeof(MyActivity));
MyIntent.PutExtra("MyString", "This is a string");
MyIntent.PutExtra("MyInt", 20);
StartActivity (MyIntent);
检索时:
string MyText = Intent.GetStringExtra ("MyString");
//you get
//This is a string
int MyDefault = 0;
int MyNumber = Intent.GetIntExtra ("MyInt", MyDefault);
//you get
//20
答案 1 :(得分:2)
来自Xamarin docs:
var activity2 = new Intent (this, typeof(Activity2));
activity2.PutExtra ("MyData", "Data from Activity1");
StartActivity (activity2);
并从第二个活动中检索数据:
string text = Intent.GetStringExtra ("MyData")
答案 2 :(得分:1)
<强> FirstClass.java 强>
Intent intent = new Intent (FirstClass.this, SecondClass.class);
intent.putExtra("StringData", "Stringvalue");
intent.putExtra("intData", 10);
startActivity(intent);
finish(); // this line is optional. If you want to destroy FirstClass, add this line.
<强> SecondClass.java 强>
在onCreate方法中添加此行。
Intent i = getIntent();
if(i != null){
String StringData = i.getStringExtra("name");
int intData = i.getIntExtra("intData", 0); // second parameter is the default value. if unable to get the value of "intData", default value will parse.
}
清单文件
将这些行添加到您的清单文件中。
<activity android:name=".FirstClass">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondClass">
</activity>
答案 3 :(得分:0)
Bundle对象也是一个选项
public class NextActivity extends AppCompatActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
Bundle intentBundle = getIntent().getExtras();
String strResult = intentBundle.getString("strA");
}
}