简体   繁体   中英

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

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. 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?

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:

bundle.getString(“Username“)

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.

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, "");
}


}

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) 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. The code below is the same as yours, just corrected with the SharedPreferences implemented.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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