编辑问题以包括所需的行为、特定的问题或错误,以及重现问题所需的最短代码。这将帮助其他人回答这个问题。
嗨,我知道这个问题有答案。我已经尝试了所有它们,但在我的应用程序中不起作用。我有两个片段(登录和密码),我想将电子邮件和手机号码从登录片段传递到密码片段。我尝试了很多,但我无法得到解决方案。
请任何人帮助我。
登录片段:
public class LoginFragment extends Fragment {
private SlidingTabLayout mSlidingTabLayout;
private ViewPager mViewPager;
SharedPreferences pref = null;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_login, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// BEGIN_INCLUDE (setup_viewpager)
// Get the ViewPager and set it's PagerAdapter so that it can display items
mViewPager = (ViewPager) view.findViewById(R.id.loginpager);
mViewPager.setAdapter(new TabsAdapter());
// END_INCLUDE (setup_viewpager)
// BEGIN_INCLUDE (setup_slidingtablayout)
// Give the SlidingTabLayout the ViewPager, this must be done AFTER the ViewPager has had
// it's PagerAdapter set.
mSlidingTabLayout = (SlidingTabLayout) view.findViewById(R.id.sliding_tabs);
mSlidingTabLayout.setViewPager(mViewPager);
// END_INCLUDE (setup_slidingtablayout)
}
public class TabsAdapter extends PagerAdapter {
@Override
public boolean isViewFromObject(View view, Object o) {
return o == view;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0: return "SIGN IN";
case 1: return "SIGN UP";
}
return "";
}
// END_INCLUDE (pageradapter_getpagetitle)
@Override
public int getCount() {
// get item count - equal to number of tabs
return 2;
}
/**
* Instantiate the {@link View} which should be displayed at {@code position}. Here we
* inflate a layout from the apps resources and then change the text view to signify the position.
*/
@Override
public Object instantiateItem(ViewGroup container, int position) {
// Inflate a new layout from our resources
View view = null;
switch (position) {
case 0: view = getActivity().getLayoutInflater().inflate(R.layout.fragment_signin,
container, false);
signinListener(view);
break;
case 1: view = getActivity().getLayoutInflater().inflate(R.layout.fragment_signup,
container, false);
signupListener(view);
break;
}
container.addView(view);
return view;
}
EditText Name;
EditText EmailId;
EditText Phone;
Button Signup;
// Progress Dialog Object
ProgressDialog prgDialog;
// Error Msg TextView Object
TextView errorMsg;
TextView signUperrorMsg;
EditText username;
EditText password;
Button Signin;
public void signinListener(View signinView) {
username = (EditText) signinView.findViewById(R.id.signin_mobile);
password = (EditText) signinView.findViewById(R.id.signin_password);
Signin = (Button) signinView.findViewById(R.id.signButton);
// Find Error Msg Text View control by ID
errorMsg = (TextView)signinView.findViewById(R.id.login_error);
prgDialog = new ProgressDialog(getActivity());
// Set Progress Dialog Text
prgDialog.setMessage("Please wait...");
// Set Cancelable as False
prgDialog.setCancelable(false);
//Validation for signin field while clicking signin button
Signin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String usrname = username.getText().toString();
String usrpassword = password.getText().toString();
// Instantiate Http Request Param Object
RequestParams params = new RequestParams();
if (Utility.isNotNull(usrname) && Utility.isNotNull(usrpassword)) {
// When Email entered is Valid
if (Utility.validate(usrname)) {
// Put Http parameter username with value of Email Edit View control
params.put("mobile", usrname);
// Put Http parameter password with value of Password Edit Value control
params.put("pwd",usrpassword);
// Invoke RESTful Web Service with Http parameters
signinWS(params);
}
// When Email is invalid
else {
Toast.makeText(getActivity().getApplicationContext(), "Please enter valid mobile", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getActivity().getApplicationContext(), "Please fill the form, don't leave any field blank", Toast.LENGTH_LONG).show();
}
}
});
}
/*
Function to set the onclick listener for signup tab
*/
public void signupListener(View signUpView) {
Name = (EditText) signUpView.findViewById(R.id.signup_name);
EmailId= (EditText) signUpView.findViewById(R.id.signup_email);
Phone= (EditText) signUpView.findViewById(R.id.signup_phone);
Signup = (Button) signUpView.findViewById(R.id.signupButton);
// Find Error Msg Text View control by ID
signUperrorMsg = (TextView)signUpView.findViewById(R.id.signup_error);
prgDialog = new ProgressDialog(getActivity());
// Set Progress Dialog Text
prgDialog.setMessage("Please wait...");
// Set Cancelable as False
prgDialog.setCancelable(false);
//Allow only characters and space in name field
Name.setFilters(new InputFilter[]{
new InputFilter() {
@Override
public CharSequence filter(CharSequence cs, int start,
int end, Spanned spanned, int dStart, int dEnd) {
// TODO Auto-generated method stub
if (cs.equals("")) { // for backspace
return cs;
}
if (cs.toString().matches("[a-zA-Z ]+")) {
return cs;
}
return "";
}
}
});
//Validation for signup field while clicking signup button
Signup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String sName = Name.getText().toString();
String sPhoneNo = Phone.getText().toString();
String sEmailId = EmailId.getText().toString();
// Instantiate Http Request Param Object
RequestParams params = new RequestParams();
if (Utility.isNotNull(sName) && Utility.isNotNull(sPhoneNo) && Utility.isNotNull(sEmailId) ) {
if (Utility.line2_validate(sName)) {
if (Utility.validate(sPhoneNo)) {
if (Utility.email_validate(sEmailId)) {
// Put Http parameter username with value of Name Edit View control
params.put("name", sName);
// Put Http parameter email with value of Email Edit Value control
params.put("email", sEmailId);
// Put Http parameter mobile with value of Mobile Edit Value control
params.put("mobile", sPhoneNo);
// Invoke Signup RESTful Web Service with Http parameters
signUpWS(params);
}
else {
EmailId.setError("Enter valid Email");
}
}
else {
Phone.setError("Enter valid Mobile");
}
}
else {
Name.setError("Enter valid Name");
}
}
else {
Toast.makeText(getActivity().getApplicationContext(), "Please fill the form, don't leave any field blank", Toast.LENGTH_SHORT).show();
}
}
});
}
/*
Function to invoke the WS for signin activity
*/
public void signinWS(RequestParams params){
// Show Progress Dialog
prgDialog.show();
// Make RESTful webservice call using AsyncHttpClient object
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://example.com/signin", params, new AsyncHttpResponseHandler() {
// When the response returned by REST has Http response code '200'
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
// Hide Progress Dialog
prgDialog.hide();
try {
// JSON Object
JSONObject obj = new JSONObject(new String(response));
// When the JSON response has status boolean value assigned with true
if (obj.getBoolean("status")) {
Toast.makeText(getActivity().getApplicationContext(), "You are successfully logged in!", Toast.LENGTH_LONG).show();
// Navigate to Home screen
pref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putInt(getString(R.string.signedupflag), 1);
editor.putString("name", username.getText().toString());
editor.commit();
((MainActivity) getActivity()).navigatetoSearchActivity();
}
// Else display error message
else {
errorMsg.setText(obj.getString("error_msg"));
Toast.makeText(getActivity().getApplicationContext(), obj.getString("error_msg"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
Toast.makeText(getActivity().getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
// When the response returned by REST has Http response code other than '200'
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responsebody, Throwable error) {
// Hide Progress Dialog
prgDialog.hide();
// When Http response code is '404'
if (statusCode == 404) {
Toast.makeText(getActivity().getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
}
// When Http response code is '500'
else if (statusCode == 500) {
Toast.makeText(getActivity().getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
}
// When Http response code other than 404, 500
else {
Toast.makeText(getActivity().getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]", Toast.LENGTH_LONG).show();
}
}
});
}
/**
* Destroy the item from the {@link ViewPager}. In our case this is simply removing the
* {@link View}.
*/
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
/*
Function to invoke the WS for signin activity
*/
public void signUpWS(RequestParams params){
// Show Progress Dialog
prgDialog.show();
// Make RESTful webservice call using AsyncHttpClient object
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://example.com/signup", params, new AsyncHttpResponseHandler() {
// When the response returned by REST has Http response code '200'
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
// Hide Progress Dialog
prgDialog.hide();
try {
// JSON Object
JSONObject obj = new JSONObject(new String(response));
// When the JSON response has status boolean value assigned with true
if (obj.getBoolean("status")) {
Toast.makeText(getActivity().getApplicationContext(), "You are successfully Signed Up!", Toast.LENGTH_LONG).show();
//Pass value from this fragment
PasswordFragment pf = new PasswordFragment();
Bundle args = new Bundle();
args.putString("email",EmailId.getText().toString());
pf.setArguments(args);
getFragmentManager().beginTransaction().add(R.id.content_frame,pf).commit();
((MainActivity) getActivity()).navigatetoPasswordActivity();
}
// Else display error message
else {
signUperrorMsg.setText(obj.getString("msg"));
Toast.makeText(getActivity().getApplicationContext(), obj.getString("msg"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
Toast.makeText(getActivity().getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
// When the response returned by REST has Http response code other than '200'
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responsebody, Throwable error) {
// Hide Progress Dialog
prgDialog.hide();
// When Http response code is '404'
if (statusCode == 404) {
Toast.makeText(getActivity().getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
}
// When Http response code is '500'
else if (statusCode == 500) {
Toast.makeText(getActivity().getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
}
// When Http response code other than 404, 500
else {
Toast.makeText(getActivity().getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]", Toast.LENGTH_LONG).show();
}
}
});
}
}
}
密码碎片:
public class PasswordFragment extends Fragment {
EditText verifyCode;
EditText new_pwd;
EditText confirm_pwd;
TextView pwd_error_msg;
Button pwd_ok;
// Progress Dialog Object
ProgressDialog prgDialog;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.password, container,false);
//Retrive value from login fragment
final String email = getArguments().getString("email");
verifyCode = (EditText)view.findViewById(R.id.mobie_verification);
new_pwd = (EditText)view.findViewById(R.id.new_password);
confirm_pwd = (EditText)view.findViewById(R.id.confirm_password);
pwd_error_msg = (TextView)view.findViewById(R.id.pwd_error_msg);
pwd_ok = (Button)view.findViewById(R.id.password_button);
prgDialog = new ProgressDialog(getActivity());
// Set Progress Dialog Text
prgDialog.setMessage("Please wait...");
// Set Cancelable as False
prgDialog.setCancelable(false);
pwd_ok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String strPwd = new_pwd.getText().toString();
String strConfPwd = confirm_pwd.getText().toString();
String strVerifyCode = verifyCode.getText().toString();
// Instantiate Http Request Param Object
RequestParams params = new RequestParams();
if (Utility.isNotNull(strPwd)) {
if (Utility.isNotNull(strConfPwd)) {
if ((strPwd.length() > 3 ) && (strPwd.length() < 8 ) ) {
pwd_error_msg.setText(null);
if (strPwd.equals(strConfPwd)) {
//password and confirm passwords equal.go to next step
pwd_error_msg.setText(null);
//Toast.makeText(getActivity().getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();
params.put("email", email);
// Put Http parameter verificationCode with value of Verificationcode Edit View control
params.put("key", strVerifyCode);
// Put Http parameter password with value of Password Edit Value control
params.put("code", strPwd);
params.put("mobile", "9966338856");
pwdWS(params);
} else {
//passwords not matching.please try again
pwd_error_msg.setText("Password does not Match!");
}
}
else {
pwd_error_msg.setText("Password should be from 4 to 8 characters.");
}
}
else {
confirm_pwd.setError("Confirm Password must be filled out");
}
}
else {
new_pwd.setError("New Password must be filled out");
}
}
});
return view;
}
/*
Function to invoke the WS for signin activity
*/
public void pwdWS(RequestParams params){
// Show Progress Dialog
prgDialog.show();
// Make RESTful webservice call using AsyncHttpClient object
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.example.com/mverify", params, new AsyncHttpResponseHandler() {
// When the response returned by REST has Http response code '200'
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
// Hide Progress Dialog
prgDialog.hide();
try {
// JSON Object
JSONObject obj = new JSONObject(new String(response));
// When the JSON response has status boolean value assigned with true
if (obj.getBoolean("status")) {
Toast.makeText(getActivity().getApplicationContext(), "Password Successfully Created!", Toast.LENGTH_LONG).show();
// Navigate to Home screen
/*pref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putInt(getString(R.string.signedupflag), 1);
editor.putString("name", username.getText().toString());
editor.commit();*/
((MainActivity) getActivity()).navigatetoSearchActivity();
}
// Else display error message
else {
pwd_error_msg.setText(obj.getString("msg"));
Toast.makeText(getActivity().getApplicationContext(), obj.getString("msg"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
Toast.makeText(getActivity().getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
// When the response returned by REST has Http response code other than '200'
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responsebody, Throwable error) {
// Hide Progress Dialog
prgDialog.hide();
// When Http response code is '404'
if (statusCode == 404) {
Toast.makeText(getActivity().getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
}
// When Http response code is '500'
else if (statusCode == 500) {
Toast.makeText(getActivity().getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
}
// When Http response code other than 404, 500
else {
Toast.makeText(getActivity().getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]", Toast.LENGTH_LONG).show();
}
}
});
}
}
1) 在片段2中创建接口
2)在活动中实现此接口<3)将活动的对象转换为片段中的接口,并使用要传递的数据调用其方法
4)在活动的接口方法中使用“getFragmentManager()。findFragmentbyId(…)”获取第二个片段的对象,并使用此对象将数据传递给fragment2。
请参阅此链接:http://developer.android.com/training/basics/fragments/communicating.html
示例:http://simpledeveloper.com/how-to-communicate-between-fragments-and-activities/
使用Bundle发送字符串:
//Put the value
YourNewFragment ldf = new YourNewFragment ();
Bundle args = new Bundle();
args.putString("YourKey", "YourValue");
ldf.setArguments(args);
//Inflate the fragment
getFragmentManager().beginTransaction().add(R.id.container, ldf).commit();
在新片段的onCreateView(onCreateView)中:
//Retrieve the value
String value = getArguments().getString("YourKey");
我找到了这段代码来将数据从一个片段传递到另一个片段: 片段1: 片段2: 但我不想改变片段。所以我拆了一部分。但这不起作用。这里是我的代码: 片段1: 片段2: 我必须使用我在网上找到的代码还是我的版本也能工作?当我打开第二个片段时会出现这个错误: E/AndroidRuntime:致命异常:主进程:com.example.rexan_snerficonquiz.fragment_score.on
这是我完整的logcat: 在Android.support.v4.app.backStackRecord.doaddop(backStackRecord.java:414)在Android.support.v4.app.backStackRecord.replace(backStackRecord.java:449)在Android.support.v4.app.backStackRecord.
在FragmentOne.class扩展android.support.v4.app.
我有两个活动,在活动1中有碎片,在活动2中有碎片 fragment1和fragment2扩展自FragmentActivity1,activity2扩展自AppCompatActivity 我想将字符串值从fragment1发送到fragment2,而不获取空值。我希望你能理解这个问题。谢谢
我在一个片段中有一个复选框列表(我们称之为FragmentA),我有一个包含两个片段(FragmentB和C)的活动。如果选中一个复选框,我想在片段C中显示一条消息,说明选中了特定的复选框。我需要帮助,因为我不知道如何将(isChecked)从片段A传递到片段C。 FragmentA.java 分数不影响碎片C。 包含片段 B 和 C 的活动 片段C 活动
我知道的一种方法是通过活动。我们可以将数据从一个片段发送到另一个活动,再从一个活动发送到另一个片段。还有其他方法吗?