我试图将matrix_id的值从MainActivity(extends Activity)传递给HomeActivity(extends Activity)和ScheduleFragment(extends Fragment)。 当我运行应用程序时,它会崩溃。
我非常喜欢Java编程。
我该怎么办?
请帮帮我,谢谢。
这是MainActivity.java的一部分
public class MainActivity extends Activity {
public static final String PREFS_NAME="PreferencesValue";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_screen);
b = (Button)findViewById(R.id.btnLogin);
matrix_id = (EditText)findViewById(R.id.txtMatric);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("matrix", matrix_id.getText().toString());
editor.commit();
Intent i = new Intent(getApplicationContext(), HomeActivity.class);
startActivity(i);
finish();
}
});
}
这是HomeActivity.java的一部分
/**
* Displaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0: fragment = new ScheduleFragment();
break;
case 1: fragment = new ReminderFragment();
break;
case 2: fragment = new AboutFragment();
break;
case 3: fragment = new LogoutFragment();
break;
}
这是ScheduleFragment.java
public class ScheduleFragment extends Fragment {
private final Context context;
public static final String PREFS_NAME="PreferencesValue";
public ScheduleFragment(Context context){
this.context = context;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_schedule, container, false);
TextView tvmatrix = (TextView)rootView.findViewById(R.id.textViewMatrix);
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
tvmatrix.setText(settings.getString("matrix", "A324142"));
return rootView;
}
}
答案 0 :(得分:0)
你有
public ScheduleFragment(Context context){
this.context = context;
}
片段构造函数不能有任何args。您可以使用getActivity()
来获取托管片段的活动的活动上下文
SharedPreferences settings = getActivity().getSharedPreferences(PREFS_NAME, 0);