繁体   English   中英

当我尝试从mainactivity获取Fragment中的textview值时,我的应用无法正常工作

[英]when i tried to get the textview value in Fragment from mainactivity, my app is not working

//这是Mainactivity java类,在这里我正在从用户名获取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");
            }

    }

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

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;
        }

    }

能否请您检查我在哪里遇到问题,请帮助我以正确获取价值

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

在textView.setText()方法中设置文本时,可以将其设置为字符串“ username”,而不是捆绑软件中所需的用户名,为此,您可以使用:

bundle.getString(“Username“)

要传递诸如名称/电子邮件等字符串,使用自定义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进行了更正。

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

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

这会将您通过EditText(使用getText()。toString())获得的“名称”值放入其中。 现在要从片段​​中访问“名称”,您可以执行以下操作:

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

请注意,此处的“名称”用法与代码的第一位一样,即“键”,它是“键-值对”的一部分。 您需要一个密钥来访问存储在首选项中的字符串。 这样,您可以保存任意数量的键值对(例如名称,年龄,电子邮件,DoB,国家/地区等),并在应用程序中的任何位置访问它们。 但是请确保不要将密码保存在共享首选项中。

为了使您更容易理解,我将重写您发布的代码以包括此代码,并在其中加上注释以突出显示。

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

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;
    }

}

我没有测试过它,只是在浏览器中编写了它,但是它与我在当前项目中使用的非常相似,因此我相信它会为您工作。 如果它不起作用,请发表评论,但尝试提供错误代码并提供一些帮助我的东西。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM