当我试图从mainactivity获取Fragment中的textview值时,我的应用程序无效

//这是Mainactivity java类,这里我从username获取edittext值

public class Home_Foodcourt extends AppCompatActivity implements View.OnClickListener { EditText username,userpassword; Button user_login; TextView user_register; FoodCourt_UserLoginDatabase foodCourt_userDatabase; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home__foodcourt); foodCourt_userDatabase=new FoodCourt_UserLoginDatabase(this); username=(EditText)findViewById(R.id.username); userpassword= (EditText) findViewById(R.id.loginpassword); user_login=(Button)findViewById(R.id.login_submit); user_register= (TextView) findViewById(R.id.user_newregister); user_register.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i=new Intent(Home_Foodcourt.this,FoodCourt_Register.class); startActivity(i); } }); user_login.setOnClickListener(this); } @Override public void onClick(View view) { String name=username.getText().toString(); String password=userpassword.getText().toString(); String Admin="aDminSN"; String Pass= foodCourt_userDatabase.Login(name); if(password.equals(Pass)) // { Message.message(this,"Log in Successfully"); Intent i=new Intent(Home_Foodcourt.this,Userhome.class); i.putExtra("Username",name); startActivity(i); }else { Message.message(this,"Login Failed"); } } 

//这是Home Fragment,我想从Mainactivity获取该字符串,但我的应用程序崩溃了。 它没有从主要活动中获得价值

 public class HomeFragment extends Fragment { private TextView textView; public HomeFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment Bundle bundle=getArguments(); View rootView=inflater.inflate(R.layout.fragment_home,container,false); textView.setText("Welcome to FoodCourt"+"username"); return rootView; } } 

你可以检查我在哪里遇到问题,请帮助我们正确地获得价值

要传递名称/电子邮件等字符串,使用自定义sharedPreferences类非常容易。 假设您要将字符串名称从片段A传递到活动B,并且还要访问片段B和C中的名称 ,您可以使用本地sharedPreferences类完成所有这些操作。 我将在下面为您发布示例代码。

自定义SharedPreferences类(称为UserDetails或其他):

 public class UserDetails{ static final String SharedPrefUserName = ""; //default value can go in between " ". static final String SharedPrefUserOtherData = ""; //the bit below gets the shared preferences public static SharedPreferences getSharedPreferences(Context ctx) { return PreferenceManager.getDefaultSharedPreferences(ctx); } //This sets a string value public static void setLoggedInUserName(Context ctx, String name) { SharedPreferences.Editor editor = getSharedPreferences(ctx).edit(); editor.putString(SharedPrefUserName, name); editor.commit(); } //this retrieves a string value public static String getLoggedInUserName(Context ctx) { return getSharedPreferences(ctx).getString(SharedPrefUserName, ""); } } 

要设置您将使用的凭据:

 username = (EditText) findViewById(R.id.username); String name = username.getText().toString(); // If you called your shared prefs 'UserDetails', storing the name would look like this: UserDetails.setLoggedInUserName(getApplicationContext(), name); 

然后检索存储的数据,并设置textView(让我们称之为’userNameTextView’),我们这样做:

 Textview usernameTextView = (TextView) findViewById(R.id.yourTextViewId); String userStoredName = UserDetails.getLoggedInUserName(getActivity()); userNameTextView.setText(userStoredName); 

编辑:您可以在不为SharedPreferences创建新类的情况下执行此操作。 下面的代码与您的代码相同,只是通过实现的SharedPreferences进行了更正。

要使用String将字符串插入共享首选项。

 SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences.Editor editor = preferences.edit(); editor.putString("Name",name); editor.apply(); 

这将您通过EditText获得的’name’的值(使用getText()。toString())。 现在要从您的片段中访问“名称”,您可以这样做:

 SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); String name = preferences.getString("Name", ""); 

注意这里如何使用“Name”和第一位代码一样,这被称为’key’,它是’key-value pair’的一部分。 您需要一个键来访问存储在首选项中的字符串。 这样,您可以保存任意数量的键值对(例如姓名,年龄,电子邮件,DoB,国家/地区等)并在应用内的任何位置访问它们。 但请确保不要在共享prefs中保存密码。

为了使您更容易理解,我将重写您发布的代码以包含此内容,并使用注释突出显示它。

您的主要活动(第一个):

 public class Home_Foodcourt extends AppCompatActivity implements View.OnClickListener { EditText username,userpassword; Button user_login; TextView user_register; FoodCourt_UserLoginDatabase foodCourt_userDatabase; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home__foodcourt); foodCourt_userDatabase=new FoodCourt_UserLoginDatabase(this); username=(EditText)findViewById(R.id.username); userpassword= (EditText) findViewById(R.id.loginpassword); user_login=(Button)findViewById(R.id.login_submit); user_register= (TextView) findViewById(R.id.user_newregister); user_register.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i=new Intent(Home_Foodcourt.this,FoodCourt_Register.class); startActivity(i); } }); user_login.setOnClickListener(this); } @Override public void onClick(View view) { String name=username.getText().toString(); //############ I've added the section below. ########### SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences.Editor editor = preferences.edit(); editor.putString("Name",name); editor.apply(); //############ SharedPref section complete. ############ String password=userpassword.getText().toString(); String Admin="aDminSN"; String Pass= foodCourt_userDatabase.Login(name); if(password.equals(Pass)) // { Message.message(this,"Log in Successfully"); Intent i=new Intent(Home_Foodcourt.this,Userhome.class); i.putExtra("Username",name); startActivity(i); }else { Message.message(this,"Login Failed"); } } 

现在为片段:

 public class HomeFragment extends Fragment { private TextView textView; public HomeFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment Bundle bundle=getArguments(); View rootView=inflater.inflate(R.layout.fragment_home,container,false); // ####### ALWAYS initialise your view components like below ## TextView welcomeMessage = (TextView) findViewById(R.id.PUT_TEXTVIEW_ID_HERE); // ###### The section below fetches the 'name' value from the first activity ### SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); String username = preferences.getString("Name", "DEFAULT_STRING"); /*You can change DEFAULT_STRING to be any string you want. If there isn't any data to pull from SharedPrefs, it will show this string instead!*/ // ################### textView.welcomeMessage("Welcome to FoodCourt " + username); return rootView; } } 

我没有对它进行测试,只是在浏览器中编写了它,但它与我在当前项目中使用的非常相似,所以我相信它对你有用。 只是评论它是否不起作用,但尝试提供错误代码并给我一些工作。

您正在设置启动Userhome.class类的意图,这是否存在?

当您在textView.setText()方法中设置文本时,您将其设置为字符串“username”而不是您要求从该包中使用的用户名,为此,您可以使用:

 bundle.getString(“Username“)