java - 添加 fragment 时应用程序崩溃

标签 java android android-fragments nullpointerexception

我尝试创建一个简单的颜色更改应用程序。在我的应用程序中,我创建了一个具有线性布局的 fragment ,其中存在 TextView 。我试图定期更改应用程序中 TextView 的颜色。为了定期更改颜色,我使用 random() 函数创建 0 到 255 之间的随机数,并使用这些数字作为参数来创建随机颜色。我再次使用这些随机颜色来设置线性布局中存在的 TextView 的背景。

下面是我的代码:

MainActivity.java

package com.example.abcd.color_change;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        FragmentManager fragment = getSupportFragmentManager();
        Fragment existingFragment = fragment.findFragmentById(R.id.container);
        fragment.beginTransaction().replace(R.id.linear1, existingFragment).commit();


    }
}

ColorChangeFragment.java

package com.example.abcd.color_change;

import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by abcd on 10/7/17.
 */

public class ColorChangeFragment {
    private TextView mTextView;
    private Random rand = new Random();
    private int randNum = 0;

    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState){

        View v = inflater.inflate(R.layout.fragment,container, false);
        mTextView = (TextView) v.findViewById(R.id.textview);

        Timer timer = new Timer();

        //MyTimer mt = new MyTimer();
        /*timer.schedule(mt, 1000, 1000);*/
        timer.schedule(new TimerTask(){

            @Override
            public void run() {
                int r = rand.nextInt(255);
                int g = rand.nextInt(255);
                int b = rand.nextInt(255);
                int randomColor = Color.rgb(r,g,b);
                mTextView.setBackgroundColor(randomColor);
            }
        },5000,5000);
        return v;
    }

   /* class MyTimer extends TimerTask{

        @Override
        public void run() {
            runOnUiThread(new Runnable(){

                @Override
                public void run() {
                    Random rand = new Random();
                    mTextView.setBackgroundColor(Color.argb(255, rand.nextInt(256), rand.nextInt(256) ));
                }
            });
        }
    }*/


}

ActivityMain.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</FrameLayout>

fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id ="@+id/linear1"
    android:background="@android:color/white">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id = "@+id/textview"/>

</LinearLayout>

下面是我在构建代码时收到的错误消息。

10-30 12:56:21.393 21574-21574/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                   Process: com.example.abcd.color_change, PID: 21574
                                                   java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.abcd.color_change/com.example.abcd.color_change.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2762)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2848)
                                                       at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1552)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:154)
                                                       at android.app.ActivityThread.main(ActivityThread.java:6334)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                                                    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
                                                       at android.support.v4.app.BackStackRecord.doAddOp(BackStackRecord.java:394)
                                                       at android.support.v4.app.BackStackRecord.replace(BackStackRecord.java:441)
                                                       at android.support.v4.app.BackStackRecord.replace(BackStackRecord.java:432)
                                                       at com.example.abcd.color_change.MainActivity.onCreate(MainActivity.java:17)
                                                       at android.app.Activity.performCreate(Activity.java:6743)
                                                       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134)
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2715)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2848) 
                                                       at android.app.ActivityThread.-wrap12(ActivityThread.java) 
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1552) 
                                                       at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                       at android.os.Looper.loop(Looper.java:154) 
                                                       at android.app.ActivityThread.main(ActivityThread.java:6334) 
                                                       at java.lang.reflect.Method.invoke(Native Method) 
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 
10-30 12:56:21.393 21574-21574/? D/AppTracker: App Event: crash

最佳答案

如果您只有一个 Fragment,则无需使用 replace()。您只需要使用 add() 即可。以下代码是错误的:

FragmentManager fragment = getSupportFragmentManager();
        Fragment existingFragment = fragment.findFragmentById(R.id.container);
        fragment.beginTransaction().replace(R.id.linear1, existingFragment).commit();

因为R.id.container不是一个fragment而是一个FrameLayout。您的 Activity 布局中没有 fragment ,只有一个 FrameLayout,它是:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</FrameLayout>

它应该在哪里:

<LinearLayout>
    <fragment android:name="com.example.ColorChangeFragment"
            android:id="@+id/color_fragment"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="match_parent" />

</LinearLayout>
<小时/>

要解决该问题,您需要更改添加 fragment 的代码:

Fragment newFragment = new ColorChangeFragment();

FragmentTransaction fragmentTransaction = this.getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.container, fragment);
fragmentTransaction.commit();

然后,您需要修复 ColorChangeFragment 类以扩展 android.support.v4.app.Fragment。因此,将您的类(class)更改为如下所示:

...

import android.support.v4.app.Fragment;

public class ColorChangeFragment extends Fragment {

  ...

}

关于java - 添加 fragment 时应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47020179/

相关文章:

java - Android 照片分享与 FileProvider

java - 为二进制消息格式编写解析器

java - 设置隐藏表单元素的值

java - hbase:使用动态创建的限定符查询特定值

android - 将 Picasso 与位图一起使用

android - fragment 中的 GraphView

android - 如何使用唤醒锁防止 onStop

android - android studio 中 activity_main.xml 和 content_main.xml 之间的确切区别是什么

android - 带有导航组件的 Fragment 中的 BottomNavigation

android - Android TV 应用中搜索球旁边的图标