简体   繁体   English

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

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

// This is the Mainactivity java class, here i am getting the edittext value from username //这是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");
            }

    }

//This is Home Fragment that i want to get that string from Mainactivity, but my app is crashed. //这是我想从Mainactivity获取该字符串的Home Fragment,但是我的应用程序崩溃了。 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 能否请您检查我在哪里遇到问题,请帮助我以正确获取价值

You are setting an intent to start the class Userhome.class, does this exist? 您正在设置启动Userhome.class类的意图,这是否存在?

When you are setting text in the textView.setText() method you are setting it to the string "username" not the username that you are requiring from the bundle, to do this you can use: 在textView.setText()方法中设置文本时,可以将其设置为字符串“ username”,而不是捆绑软件中所需的用户名,为此,您可以使用:

bundle.getString(“Username“)

To pass strings such as names/emails etc it's quite easy to use a custom sharedPreferences class. 要传递诸如名称/电子邮件等字符串,使用自定义sharedPreferences类非常容易。 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. 假设您要将字符串名称从片段A传递到活动B,并且还要访问片段B和C中的名称 ,则可以使用本地sharedPreferences类来完成所有这些操作。 I'll post example code for you below. 我将在下面为您发布示例代码。

The custom SharedPreferences class (call it UserDetails or something): 自定义的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, "");
}


}

To set the credentials you would use: 要设置凭据,请使用:

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

Then to retrieve the stored data, and set a textView (lets call it 'userNameTextView') we do this: 然后,要检索存储的数据并设置一个textView(将其称为“ userNameTextView”),我们可以这样做:

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

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

userNameTextView.setText(userStoredName);

EDIT: You can do this without creating a new class for the SharedPreferences. 编辑:您可以执行此操作而无需为SharedPreferences创建新类。 The code below is the same as yours, just corrected with the SharedPreferences implemented. 下面的代码与您的代码相同,只是使用实现的SharedPreferences进行了更正。

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();

This puts your value for 'name' that you got through your EditText (using getText().toString()). 这会将您通过EditText(使用getText()。toString())获得的“名称”值放入其中。 Now to access 'name' from your fragment, you can do this: 现在要从片段​​中访问“名称”,您可以执行以下操作:

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

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 (eg name, age, email, DoB, country etc.) AND access them anywhere within the app. 这样,您可以保存任意数量的键值对(例如名称,年龄,电子邮件,DoB,国家/地区等),并在应用程序中的任何位置访问它们。 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");
        }

}

Now for the 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);

        // ####### 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. 如果它不起作用,请发表评论,但尝试提供错误代码并提供一些帮助我的东西。

暂无
暂无

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

相关问题 我想从片段中隐藏片段容器视图(在 MainActivity 布局内),但是当我单击任务按钮然后重新打开应用程序时它不起作用 - i want to hide fragment container view (Inside MainActivity Layout) from fragment but its not working when i click task button and then reopen app 从MainActivity更新片段内的textview - Update textview inside fragment from MainActivity 如何从 Mainactivity 中编辑 Fragment 中的 TextView - How to edit TextView in Fragment from Mainactivity 我想在 MainActivity 内部的一个片段中获取 EditText(来自 MainActivity),我得到一个 Nullpointer 错误 - I want to get the EditText (from the MainActivity) in a fragment inside off the MainActivity and i get a Nullpointer error 片段未显示在Mainactivity中,在我的活动片段内容仅在我单击工具栏时显示 - Fragment doesn't show in Mainactivity, In my activity fragment content only show when I click on toolbar 如何在我的主要活动中使用片段中的 ImageViews - How to use ImageViews from fragment in my mainactivity 当我在其他Activity中使用MainActivity中的方法时,Android应用程序崩溃 - My Android app crashes when I use method from MainActivity in an other Activity 我的MainActivity上的textView中的setText - setText in a textView on my MainActivity 我如何将我的 Retrofit 数据从 MainActivity 发送到我的 Fragment? - How i can send my Retrofit data from MainActivity to my Fragment? 如何从 MainActivity 获取价值? - How to get value from MainActivity?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM