I want to transfer a line from Activity to Fragment , help to correct the error.

Auth.java

 public class Auth extends AppCompatActivity { private final String TAG = "log_tag"; private EditText etUser; private EditText etPassword; private Button btnLogin; private Button btnSignUp; private Realm realm; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.auth); etUser = (EditText) findViewById(R.id.editTextUserName); etPassword = (EditText) findViewById(R.id.editTextPassword); btnLogin = (Button) findViewById(R.id.btnLogin); btnSignUp = (Button) findViewById(R.id.btnSignUp); btnLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { authorization(view); } }); btnSignUp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getApplicationContext(), SignUp.class); startActivity(intent); } }); } private void authorization(View view) { Realm.init(getApplicationContext()); RealmConfiguration realmConfiguration = new RealmConfiguration .Builder() .deleteRealmIfMigrationNeeded() .build(); realm = Realm.getInstance(realmConfiguration); RealmResults<User> user = realm.where(User.class).findAll(); for (int i = 0; i < user.size(); i++) { if (user.get(i).getUserName().equals(etUser.getText().toString())&& user.get(i).getPassword().equals(etPassword.getText().toString())) { Log.d(TAG, "authorization: user size = " + user.size()); Log.d(TAG, "authorization: userName = " + user.get(i).getUserName()); Log.d(TAG, "authorization: password = " + user.get(i).getPassword()); Profile.newInstance(user.get(i).getUserName()); Intent intent = new Intent(getApplicationContext(), MainActivity.class); startActivity(intent); } else Snackbar.make(view, "Error! Check your entries.", Snackbar.LENGTH_LONG).show(); } } } 

Profile.java

 public class Profile extends Fragment { private final String TAG = "log_tag"; private CircleImageView imageView; private TextView tvName; private TextView tvEmail; private TextView tvPhone; private Realm realm; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.profile, container, false); imageView = (CircleImageView) view.findViewById(R.id.imageViewAvatar); tvName = (TextView) view.findViewById(R.id.tvFirstAndLastName); tvEmail = (TextView) view.findViewById(R.id.tvEmail); tvPhone = (TextView) view.findViewById(R.id.tvPhone); writeProfile(); return view; } public static Profile newInstance(final String userName) { final Profile profile = new Profile(); final Bundle bundle = new Bundle(); bundle.putString("userName", userName); profile.setArguments(bundle); return profile; } private void writeProfile() { Realm.init(getActivity()); RealmConfiguration realmConfiguration = new RealmConfiguration .Builder() .deleteRealmIfMigrationNeeded() .build(); realm = Realm.getInstance(realmConfiguration); String userName = this.getArguments().getString("userName");//здесь падает ошибка Log.d(TAG, "writeProfile: userName = " + userName); RealmResults<User> user = realm.where(User.class).findAll(); User userData = user.where().equalTo("userName", userName).findFirst(); tvName.setText(userData.getFirstName() + " " + userData.getLastName()); tvEmail.setText(userData.getEmail()); tvPhone.setText(userData.getPhone()); } } 

MainActivity.java

 public class MainActivity extends AppCompatActivity { private Fragment fragment; private FragmentManager fragmentManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); fragmentManager = getSupportFragmentManager(); fragment = new Feed(); final FragmentTransaction transaction = fragmentManager.beginTransaction(); transaction.add(R.id.main_container, fragment).commit(); BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation); bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.action_feed: fragment = new Feed(); break; case R.id.action_my_feed: fragment = new MyFeed(); break; case R.id.action_profile: fragment = new Profile(); break; } final FragmentTransaction transaction = fragmentManager.beginTransaction(); transaction.replace(R.id.main_container, fragment).commit(); return true; } }); } } 

well, the mistake itself

 E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.nikolai.engadgetnews, PID: 8073 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference at com.example.nikolai.engadgetnews.Profile.Profile.writeProfile(Profile.java:61) at com.example.nikolai.engadgetnews.Profile.Profile.onCreateView(Profile.java:40) at android.support.v4.app.Fragment.performCreateView(Fragment.java:2184) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1298) at android.support.v4.app.FragmentManagerImpl.moveFragmentsToInvisible(FragmentManager.java:2323) at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2136) at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2092) at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1998) at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:709) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

    3 answers 3

    You need dvuhhodovka.

    1 - pass the user name to the called MainActivity. For example, adding this parameter to the intent:

     intent = new Intent(....); intent.putExtra("userName", userName); startActivity(intent); 

    2 - in the invoked activation, get this parameter and transfer it to the fragment, for example, like this:

      case R.id.action_profile: userName = getIntent().getStringExtra("userName"); fragment = Profile.newInstance(userName); break; 

      The problem is that you use fragments incorrectly.

      In line:

       Profile.newInstance(user.get(i).getUserName()); 

      You create a fragment and do nothing with it. Moreover, you create an untitled object, which, on occasion, will be cleaned with a GC.

      Try this:

       FragmentManager fm = getSupportFragmentManager(); Fragment fragment = fm.findFragmentById(R.id.fragment_container); if (fragment == null) { fragment = Profile.newInstance(user.get(i).getUserName()); fm.beginTransaction() .add(R.id.fragment_container, fragment) .commit(); } 

      where R.id.fragment_container is a container for fragments.

      In the above code, it is first checked whether a fragment is in the specified container, if it is, then everything is OK - nothing needs to be done, otherwise a fragment instance is created and added to the FragmentManager .

      UPD: In the updated code you create a fragment instance without any arguments:

       fragment = new Profile(); 

      So when you call getArguments() get null .

      If in one situation you need to set and use arguments, and in the other - not, then just write in the fragment:

       if (getArguments() != null) { //some actions } 

      In this case, when the arguments are specified, some actions will be executed, otherwise, no actions will be performed.

          Profile.newInstance(user.get(i).getUserName()); Intent intent = new Intent(getApplicationContext(), MainActivity.class); startActivity(intent); 
        1. You get a fragment with the user name passed to it. It would be passed to the FragmentManager to show on the screen. You don’t lose him anywhere, and he (the fragment) gets to the garbage collector.
        2. You run the MainActivity. First, nothing is known about this MainActivity, and it is unclear how this activity relates to the Profile fragment. But it is clear that MainActivity does not get a user name.
        • added a question - nikolay