在安卓中将数据从活动传递到片段



我刚刚启动Android,我正在开发简单的登录页面,用户可以在登录时使用他们的电子邮件和密码登录,并在登录时在某些条件下登录。当用户以"商店所有者"身份登录时,他的姓名和电子邮件将显示在下一页(即在 Fragment 类上(,这工作正常,但每当用户以"公共用户"身份登录时,他的姓名和电子邮件都不会显示在下一页上。

注意:我正在使用网络服务和共享首选项来获取和保存数据。

提前致谢

这是我的代码

登录活动

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
EditText login_emailid, login_password;
String str_login_email, str_login_password;
Button login_button;

public static final String MY_PREFS_NAMEs = "MyPrefsFiles";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
login_button = (Button) findViewById(R.id.loginBtn);
login_emailid = (EditText) findViewById(R.id.login_emailid);
login_password = (EditText) findViewById(R.id.login_password);
login_button = (Button) findViewById(R.id.loginBtn);
login_button.setOnClickListener(this);

}
@Override
public void onClick(View v) {
if (v == login_button) {
str_login_email = login_emailid.getText().toString();
str_login_password = login_password.getText().toString();
if (str_login_email.isEmpty()) {
login_emailid.setError("Enter your email");
} else if (str_login_password.isEmpty()) {
login_password.setError("Password Please");
} else {
new AsyncTaskRunner().execute();
}
}
}
}
public static boolean isEmailValid(String email) {
return !(email == null || TextUtils.isEmpty(email)) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
public String connection(String action) {
String result = "";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://beta.gkninternational.life/webservice/user_login.php");// replace with your url
httpPost.addHeader("Content-type", "application/x-www-form-urlencoded");

List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
nameValuePairList.add(new BasicNameValuePair(
"action", action));
nameValuePairList.add(new BasicNameValuePair(
"Email", str_login_email));
nameValuePairList.add(new BasicNameValuePair(
"Password", str_login_password));
try {
Log.e("nameValuePairList", " " + nameValuePairList);
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(
nameValuePairList);
httpPost.setEntity(urlEncodedFormEntity);
try {
HttpResponse httpResponse = httpClient
.execute(httpPost);
InputStream inputStream = httpResponse.getEntity()
.getContent();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
stringBuilder.append(bufferedStrChunk);
}
result = stringBuilder.toString();
Log.e("result", stringBuilder.toString());
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
System.out
.println("First Exception coz of HttpResponese :"
+ cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out
.println("Second Exception coz of HttpResponse :"
+ ioe);
ioe.printStackTrace();
}
} catch (UnsupportedEncodingException uee) {
System.out.println("An Exception given because of UrlEncodedFormEntity argument :" + uee);
uee.printStackTrace();
}
return result;
}
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
ProgressDialog mProgressBar;
String resp;
int success;
String message;
String name, email, password, userrole, userpic, iddd;
String storeId,storeName;
SharedPreferences sharedPreferencesLogin;
SharedPreferences.Editor editor;
@Override
protected String doInBackground(String... params) {
String result = connection("Login_Activity");
try {
sharedPreferencesLogin = getSharedPreferences(MY_PREFS_NAMEs, Context.MODE_PRIVATE);
editor = sharedPreferencesLogin.edit();
JSONObject jsonObject = new JSONObject(result);
success = jsonObject.getInt("success");
message = jsonObject.getString("message");
iddd = jsonObject.getString("UserId");
name = jsonObject.getString("FirstName");
email = jsonObject.getString("Email");
userrole = jsonObject.getString("UserRole");
storeId = jsonObject.getString("StoreId");
storeName = jsonObject.getString("StoreName");
editor.putString("UserId", name);
editor.putString("FirstName", name);
editor.putString("Email", email);
editor.putString("userrole", userrole);
editor.putString("storeIdLogin", storeId);
editor.putString("StoreNameLogin", storeName);
editor.apply();

} catch (Exception e) {
e.printStackTrace();
}
return resp;
}

@Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
mProgressBar.dismiss();
if (success == 2) {
Toast.makeText(LoginActivity.this, message, Toast.LENGTH_LONG).show();
} else if (success == 1) {
Toast.makeText(LoginActivity.this, message, Toast.LENGTH_LONG).show();
if(userrole.equals("store_owner"))
{
if(storeName.equals("Dummy")){
startActivity(new Intent(LoginActivity.this, EditActivity.class));
finish();
}
else{
Intent intentt = new Intent(LoginActivity.this, HomeActivity.class);
startActivity(intentt);
finish();
}
}
else{
Intent intentuser = new Intent(LoginActivity.this, AfterSplash.class);
startActivity(intentuser);
finish();
}
}
}
@Override
protected void onPreExecute() {
mProgressBar = new ProgressDialog(LoginActivity.this);
mProgressBar.setMessage("Connecting to server");
mProgressBar.setCancelable(false);
mProgressBar.show();
}
}

弗拉门特类

公共类 MyFragment 扩展了 Fragment{

SharedPreferences sharedPreferencesLogin;
public static final String MY_PREFS_NAMEs = "MyPrefsFiles";
TextView names,emails;
String str_names,str_emails;
public MyFragment() {
// Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.fragment_my, container, false);

sharedPreferencesLogin=    getActivity().getSharedPreferences(MY_PREFS_NAMEs, Context.MODE_PRIVATE);
names=(TextView)layout.findViewById(R.id.names);
emails=(TextView)layout.findViewById(R.id.emails);
str_names=     sharedPreferencesLogin.getString("FirstName","");
str_emails=      sharedPreferencesLogin.getString("Email","");
names.setText(str_names);
emails.setText(str_emails);
}

}

尝试设置共享首选项

String userId=yourstring;
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(youractivity.this);
Editor edit = settings.edit();
edit.putString("name", userId);
settings.commit;

获取共享首选项

SharedPreferences settins = PreferenceManager
.getDefaultSharedPreferences(Youractivity.this);
name=settings.getString("name", "anon");

您必须使用捆绑包和可序列化对象才能传递:

  • 活动
Fragment fragment = new YourFragment();
Bundle bundle = new Bundle();
bundle.putSerializable(ARGUMENT_KEY, objectSerializable);
fragment.setArguments(bundle); showFragment(fragment)
  • 片段上:
Bundle bundle = this.getArguments();
if (bundle != null) {
Object neededObject = bundle.getSerializable(ser_key)
}

像这样覆盖片段中的newInstance()方法。

public static YourFragment newInstance(Bundle bundle) {
ActivityFeedListFragment fragment = new ActivityFeedListFragment();
fragment.setArguments(bundle);
return fragment;
}

并传递bundle对象。

相关内容

  • 没有找到相关文章