当我尝试从mainactivity中获取Fragment中的textview值时,我的应用无法正常工作 [英] when i tried to get the textview value in Fragment from mainactivity, my app is not working

查看:157
本文介绍了当我尝试从mainactivity中获取Fragment中的textview值时,我的应用无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

//这是Mainactivity java类,在这里我正在从用户名中获取edittext值

// This is the Mainactivity java class, here i am getting the edittext value from username

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中获取该字符串,但是我的应用程序崩溃了.它没有从主要活动中获取价值

//This is Home Fragment that i want to get that string from Mainactivity, but my app is crashed. it is not getting the value from that main activity

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

    }

请问我在哪里遇到问题,请帮助我以正确获取价值

can you please check where i am getting issue and please helpme to get the value properly

推荐答案

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

To pass strings such as names/emails etc it's quite easy to use a custom sharedPreferences class. Say you want to pass a string name from Fragment A to Activity B, and also access name in fragments B and C, you could do all this using a local sharedPreferences class. I'll post example code for you below.

自定义的SharedPreferences类(称为UserDetails之类):

The custom SharedPreferences class (call it UserDetails or something):

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"),我们这样做:

Then to retrieve the stored data, and set a textView (lets call it 'userNameTextView') we do this:

Textview usernameTextView = (TextView) findViewById(R.id.yourTextViewId);

String userStoredName = UserDetails.getLoggedInUserName(getActivity());

userNameTextView.setText(userStoredName);

您可以执行此操作而无需为SharedPreferences创建新的类.下面的代码与您的代码相同,只是使用实现的SharedPreferences进行了纠正.

You can do this without creating a new class for the SharedPreferences. The code below is the same as yours, just corrected with the SharedPreferences implemented.

要使用您的String将字符串插入共享首选项.

To insert a string into shared prefs, using your String.

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

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

This puts your value for 'name' that you got through your EditText (using getText().toString()). Now to access 'name' from your fragment, you can do this:

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

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

Note how "Name" is used here just as with the first bit of code, this is called a 'key', which is part of a 'key-value pair'. You need a key to access the string that is stored in the preferences. This way you can have any number of key-value pairs saved (e.g. name, age, email, DoB, country etc.) AND access them anywhere within the app. Make sure not to save passwords in shared prefs though.

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

To make this easier for you to understand, I'll rewrite the code you posted to include this, and highlight it with comments.

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

Your Main Activity (the first one):

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

}

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

I haven't tested this and have just written it in the browser, but it's very similar to what I use in my current project so I'm confident that it'll work for you. Just comment if it doesn't work, but try to provide error codes and give something for me to work with.

这篇关于当我尝试从mainactivity中获取Fragment中的textview值时,我的应用无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆