如何修复viewmodel.setText中的PP_9?



我正在尝试将用户信息从MainActivity传递到NavigationHeader中的一个片段,每次尝试在片段中设置文本时,我都会收到NullPointerException。

在尝试 ViewModel 之前,我尝试使用捆绑和接口方法。getActivity()也警告我它是空的。

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
    private DrawerLayout drawer;

    //NavHeader
    private TextView header_name, header_email;
    //SessionManager
    SessionManager sessionManager;
    //maps
    private static final String TAG = "MainActivity";
    private static final int ERROR_DIALOG_REQUEST = 9001;
    private static final String FINELOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
    private static final String COURSELOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
    private Boolean mLocationPermissionsGranted = false;
    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
    private static final float DEFAULT_ZOOM = 15f;
    private FusedLocationProviderClient mFusedLocationProviderClient;
    private GoogleMap mMap;

    String pontopartida, pontochegada;
    private EditText ponto_partidaInput, ponto_chegadaInput;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //GET USER DATA
        sessionManager = new SessionManager(this);
        sessionManager.checkLogin();
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        View headerView = navigationView.getHeaderView(0);
        header_name = (TextView) headerView.findViewById(R.id.header_name);
        header_email = (TextView) headerView.findViewById(R.id.header_email);

        HashMap<String, String> user = sessionManager.getUserDetail();
        String mName =  user.get(sessionManager.NAME);
        String mEmail = user.get(sessionManager.EMAIL);
        header_name.setText(mName);
        header_email.setText(mEmail);

        //Navigation Drawer
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        drawer = findViewById(R.id.drawer_layout);
        navigationView.setNavigationItemSelectedListener(this);

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
        switch (menuItem.getItemId()){
            case R.id.nav_myaccount:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new MyAccountFragment()).commit();
                break;
            case R.id.nav_settings:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new SettingsFragment()).commit();
                break;
            case R.id.nav_logout:
                sessionManager.logout();
                break;
            case R.id.nav_share:
                Toast.makeText(this, "Shared", Toast.LENGTH_SHORT).show();
                break;
        }
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
    @Override
    public void onBackPressed() {
        if(drawer.isDrawerOpen(GravityCompat.START)){
            drawer.closeDrawer(GravityCompat.START);
        }else{
            super.onBackPressed();
        }
    }
}

和我的帐户片段


public class MyAccountFragment extends Fragment {
    private SharedViewModel viewModel;
    private EditText account_name;
    private EditText account_email;
    protected FragmentActivity mActivity;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_myaccount, container, false);

        account_name = (EditText) view.findViewById(R.id.name_accountfrag);
        account_email = (EditText) view.findViewById(R.id.email_accountfrag);
        viewModel.setText(account_name.getText().toString());

        return view;
    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        viewModel = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
        viewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                account_name.setText(s);
            }
        });
    }
}

这也是我的错误日志


E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.tiago.teleperformance, PID: 9236
    java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.tiago.teleperformance.SharedViewModel.setText(java.lang.String)' on a null object reference
        at com.example.tiago.teleperformance.MyAccountFragment.onCreateView(MyAccountFragment.java:42)
        at android.support.v4.app.Fragment.performCreateView(Fragment.java:2439)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1460)
        at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1852)
        at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:802)
        at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625)
        at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411)
        at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
        at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273)
        at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:733)
        at android.os.Handler.handleCallback(Handler.java:789)
        at android.os.Handler.dispatchMessage(Handler.java:98)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6541)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

我希望它在打开片段后立即在主活动中使用相同的名称和电子邮件更新片段中的信息。相反,它崩溃了。谁能帮我?

片段中的

onCreateView 将在 onActivityCreate 之前调用,因此您的viewModel为空,请将您的 init viewModel' before移动到 setText' 方法

相关内容

  • 没有找到相关文章

最新更新