简体   繁体   English

无法设置 TextView 的文本

[英]Can't set Text of TextView

I wanted to have the Text of a TextView changed to whatever the username of the active user is, but the method updateUI() always returns this error:我想将TextView的文本更改为活动用户的任何用户名,但方法updateUI()始终返回此错误:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.cocko.industries.einkaufshelfer.shopper, PID: 18704
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.cocko.industries.einkaufshelfer.shopper/com.cocko.industries.einkaufshelfer.shopper.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    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)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
    at com.cocko.industries.einkaufshelfer.shopper.MainActivity.updateUI(MainActivity.java:203)
    at com.cocko.industries.einkaufshelfer.shopper.MainActivity.onCreate(MainActivity.java:76)
    at android.app.Activity.performCreate(Activity.java:6237)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
    at android.app.ActivityThread.-wrap11(ActivityThread.java) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    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)

So what's the problem?所以有什么问题? It seems to me as if the TextView can't be found and is therefore null.在我看来好像找不到TextView ,因此为空。 But why?但为什么? And how can I fix that?我该如何解决? Below you can find the MainActivity class with the onCreate and updateUI method and the fragment that I used.您可以在下面找到带有onCreateupdateUI方法的MainActivity类以及我使用的片段。

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

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        mAuth = FirebaseAuth.getInstance();

        nav_view = findViewById(R.id.nav_view);
        nav_view.setNavigationItemSelectedListener(this);

        drawer = findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.nav_drawer_open, R.string.nav_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        try {
            Intent intent = getIntent();
            if (intent.getStringExtra("activity").equals("register")) {
                getSupportFragmentManager().beginTransaction().replace(R.id.framgment_container, new UserprofileFragment()).commit();
            }
        } catch (NullPointerException noIntentExtra) {
            getSupportFragmentManager().beginTransaction().replace(R.id.framgment_container, new AssignmentsFragment()).commit();
        }

        if (mAuth.getCurrentUser() != null){
            updateUI();
        }
    }

And the updateUI function is as follows.updateUI函数如下。

public void updateUI() {
    TextView textView = findViewById(R.id.textview_assignemntsheader);
    textView.setText("Test");
}

Here's the layout for my fragment, that is fragment_assignments.xml :这是我的片段的布局,即fragment_assignments.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textview_assignemntsheader"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:text="@string/textview_assigmentsHeader"
        android:textAlignment="center"
        android:textAppearance="@style/TextAppearance.AppCompat.Display1"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textview_assignemntsheader">

        <LinearLayout
            android:id="@+id/linearlayout_assignments"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

        </LinearLayout>
    </ScrollView>


</androidx.constraintlayout.widget.ConstraintLayout>

And the layout for my activity is activity_main.xml :我的活动的布局是activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".MainActivity"
    tools:openDrawer="start">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/colorPrimary"
            android:elevation="4dp"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

        <FrameLayout
            android:id="@+id/framgment_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </LinearLayout>

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:headerLayout="@layout/nav_header"
        app:menu="@menu/menu" />
</androidx.drawerlayout.widget.DrawerLayout>

you can't find your textView in MainActivity because it is not in the main_activity.xml, so updateUI should be in UserProfile Fragment.你在 MainActivity 中找不到你的 textView 因为它不在 main_activity.xml 中,所以 updateUI 应该在 UserProfile Fragment 中。

in OnCreateViewOnCreateView

try this :尝试这个 :

View view = inflater.inflate(R.layout.fragment_assignments, container,false);

TextView text=view.findViewById(R.id.textview_assignemntsheader);

Where do you inflate fragment_assignments.xml?你在哪里膨胀 fragment_assignments.xml? in this line, you inflate main_activity.xml在这一行中,您膨胀 main_activity.xml

setContentView(R.layout.activity_main);

But, textview_assignemntsheader is in another XML file and can`t find it and returns null.但是,textview_assignemntsheader 位于另一个 XML 文件中,无法找到它并返回 null。 findViewById will search for ID only in the inflated view. findViewById 将仅在膨胀视图中搜索 ID。 Move UpdateUI function to UserProfile (where fragment_assignments.xml is inflated)将 UpdateUI 函数移动到 UserProfile(其中 fragment_assignments.xml 被膨胀)

In your MainActivity you are inflating the activity_main layout which does not have the TextView .在您的MainActivity您正在膨胀没有TextViewactivity_main布局。 Hence you are getting the NullPointerException while trying to find the TextView and assign some text to it.因此,您在尝试查找TextView并为其分配一些文本时遇到NullPointerException

In the onCreate method of your MainActivity class tries to set a text to a TextView which is not there or not inflated.MainActivity类的onCreate方法中,尝试将文本设置为不存在或未膨胀的TextView The fragment_assignments.xml layout might be inflated in your fragment, and hence you will find the layout reference there in your fragment. fragment_assignments.xml布局可能会在您的片段中膨胀,因此您会在片段中找到布局引用。

Looks like you want to pass the auth information to your fragment and set some value there.看起来您想将身份验证信息传递给您的片段并在那里设置一些值。 In that case, you can just pass the information using a bundle while doing the fragment transaction.在这种情况下,您可以在执行片段事务时使用包传递信息。

Hence, you might have the following function for your fragment transaction in your activity.因此,您的活动中的片段交易可能具有以下功能。

public void launchAssignmentFragment() {

    AssignmentFragment frag = new AssignmentFragment();
    Bundle bundle = new Bundle();

    if (mAuth.getCurrentUser() != null) {
        bundle.putBoolean("auth", true);
    } else {
        bundle.putBoolean("auth", false);
    }

    // set Arguments to be passed to the fragment 
    frag.setArguments(bundle);

    // Now load the fragment 
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

    transaction.replace(R.id.fragment_container, frag);
    transaction.addToBackStack(null);

    transaction.commit();
}

Now from the onCreateView of your fragment, you can do something like this.现在从你的片段的onCreateView ,你可以做这样的事情。

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout. fragment_assignments, parent, false);
    TextView tv = rootView.findViewById(R.id.textview_assignemntsheader);

    // Get the passed-in value here
    boolean auth = getArguments().getBoolean("auth");

    if (auth) tv.setText("Success");
    else tv.setText("Fail");

    return rootView;
}

And finally, update your onCreate in the MainActivity as follows.最后,按如下方式更新MainActivityonCreate

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    mAuth = FirebaseAuth.getInstance();

    nav_view = findViewById(R.id.nav_view);
    nav_view.setNavigationItemSelectedListener(this);

    drawer = findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.nav_drawer_open, R.string.nav_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    try {
        Intent intent = getIntent();
        if (intent.getStringExtra("activity").equals("register")) {
            getSupportFragmentManager().beginTransaction().replace(R.id.framgment_container, new UserprofileFragment()).commit();
        }
    } catch (NullPointerException noIntentExtra) {
        getSupportFragmentManager().beginTransaction().replace(R.id.framgment_container, new AssignmentsFragment()).commit();
    }

    if (mAuth.getCurrentUser() != null){
        launchAssignmentFragment(); // launch the fragment maybe?
    }
}

I hope that helps!我希望这有帮助!

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

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