当前位置: 首页 > 知识库问答 >
问题:

Android:无法更新活动片段中的文本视图。空指针异常

池麒
2023-03-14

我正在尝试从另一个活动更新片段中的文本视图。但是当调用setText方法时,我得到了一个NUllPointerExc的异常。我已经尝试了以下操作,但仍然得到了NPE。1.尝试在活动中使用FindViewbyId访问片段文本视图。2.尝试在片段中使用方法并从活动中调用它并将值作为参数传递

碎片家园活动

public class FragHome extends AppCompatActivity implements TabLayout.OnTabSelectedListener {

Handler bluetoothIn;
private static TextView tmpF, humF, CoF;
String tempGL, HumGL, coGL, devname;
double dblTemp, dblCo;
final int handlerState = 0; // used to identify handler message
private BluetoothAdapter btAdapter = null;
private TabLayout tabLayout;
private ViewPager viewPager;

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

    //Adding toolbar to the activity
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    //Initializing the tablayout
    tabLayout = (TabLayout) findViewById(R.id.tabLayout);
    //Initializing viewPager
    viewPager = (ViewPager) findViewById(R.id.pager);
    //Adding the tabs using addTab() method
    tabLayout.addTab(tabLayout.newTab().setText("Temperature"));
    tabLayout.addTab(tabLayout.newTab().setText("Humidity"));
    tabLayout.addTab(tabLayout.newTab().setText("CO"));
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

    //Creating our pager adapter
    Pager adapter = new Pager(getSupportFragmentManager(), tabLayout.getTabCount());

    //Adding adapter to pager
    viewPager.setAdapter(adapter);
    viewPager.setOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    //Adding onTabSelectedListener to swipe views
    tabLayout.setOnTabSelectedListener(this);

    bluetoothIn=new Handler() {

        String readMessage;
        String[] values = new String[]{""};

        public void handleMessage(android.os.Message msg) {

            if (msg.what == handlerState) {

                readMessage = (String) msg.obj;
                values = readMessage.split("#");
                for (int j = 0; j < values.length; j++) {

                    int rem = j % 3;

                    if (rem == 0) {

                        tmpF.setText(values[j] + " C");
                        tempGL = String.valueOf(values[j]);

                        try {
                            dblTemp = Double.parseDouble(tempGL);
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                        }

                    } else if (rem == 1) {

                        CoF.setText(values[j] + " ppm");
                        coGL = values[j];
                        try {
                            dblCo = Double.parseDouble(coGL);
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                        }

                    } else if (rem == 2) {
                        humF.setText(values[j] + " %");
                        HumGL = values[j];
                    }
                }
            }
        }
    };

    btAdapter=BluetoothAdapter.getDefaultAdapter(); // get Bluetooth
}

@Override
public void onTabSelected(TabLayout.Tab tab) {
    // mViewPager.setCurrentItem(tab.getPosition());

}

@Override
public void onTabUnselected(TabLayout.Tab tab) {

}

@Override
public void onTabReselected(TabLayout.Tab tab) {

}
}

寻呼机

  public class Pager extends FragmentStatePagerAdapter {

//integer to count number of tabs
int tabCount;

//Constructor to the class
public Pager(FragmentManager fm, int tabCount) {
    super(fm);
    //Initializing tab count
    this.tabCount= tabCount;
}

//Overriding method getItem
@Override
public Fragment getItem(int position) {
    //Returning the current tabs
    switch (position) {
        case 0:
            Tab1 tab1 = new Tab1();
            return tab1;
        case 1:
            Tab2 tab2 = new Tab2();
            return tab2;
        case 2:
            Tab3 tab3 = new Tab3();
            return tab3;
        default:
            return null;
    }
}

//Overriden method getCount to get the number of tabs
@Override
public int getCount() {
    return tabCount;
}
}

标签1

public class OneFragment extends Fragment {

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

}
}

fragment_one.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="shinil.tablayout.OneFragment"
android:id="@+id/rltnvnv">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Temperature"
    android:textSize="40dp"
    android:textStyle="bold"
    android:id="@+id/textviewtemp"
    android:layout_centerInParent="true"/>

 </RelativeLayout>

frag_home.xml

 LinearLayout
android:id="@+id/main_layout"
android:orientation="vertical"
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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<!-- our toolbar -->
<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:minHeight="?attr/actionBarSize"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

<!-- our tablayout to display tabs  -->
<android.support.design.widget.TabLayout
    android:id="@+id/tabLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"

    android:minHeight="?attr/actionBarSize"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

<!-- View pager to swipe views -->
<android.support.v4.view.ViewPager
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"/>

  </LinearLayout>    

当我试图从活动中设置文本时,就会出现NPE。请帮帮忙

共有1个答案

颛孙凯定
2023-03-14

使用以下回调:

片段类:

public class FragmentOne extends Fragment {


private ViewCallback mCallback;

 public FragmentOne(ViewCallback mCallback) {
    this.mCallback = mCallback;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.fragment_one, container, false);
    mCallback.updateTextView((TextView) view.findViewById(R.id.fragmentTextView));
    return view;
}

public interface ViewCallback {
    void updateTextView(TextView view);
}
}

下面是活动类:

public class MainCallbackActivity extends Activity implements CallbackFragment.ViewCallback {

public TextView textView;

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

    FragmentOne fragment = new FragmentOne(this);
    getFragmentManager().beginTransaction().add(R.id.frameLayout, fragment).commit();

}

@Override
protected void onResume() {
    super.onResume();
    if (textView != null)
        textView.setText("Updating Fragment TextView in Activity..!!");
}

@Override
public void updateTextView(TextView view) {
    this.textView = view;
}
}

在您的活动类中实现该回调…然后更新文本视图。

 类似资料:
  • 我在活动onCreate()中初始化列表,如下所示: 编辑:我的活动的launchmode是SingleTask 编辑2: 我无法发送更多有用的日志,因为这次崩溃是在生产中。我只有一些布料日志。 谢谢你的帮助,但我不能粘贴整个代码,因为隐私。 我想我在SingleTask-OnCreate-OnNewIntent用法上有问题。简单地说,我试图打开我的应用程序从通知与参数决定哪个片段将打开时,用户导

  • 我试图在列表视图的onItemClick中用另一个片段替换片段,我想将所选项目名称从列表片段发送到另一个片段,但它显示空指针异常 @覆盖onItemClick上的公共无效(AdapterView ar0,视图,int位置,长id){ 但是同样的概念在下面的按钮点击中工作

  • 08-0712:11:44.453:I/Choreographer(1257):跳过126帧! 应用程序可能在主线程上做了太多工作。08-07 12:11:46.313:I/Choreographer(1257):跳过了131帧! 应用程序可能在主线程上做了太多工作。08-07 12:11:48.033:I/Choreographer(1257):跳过了33个帧! 应用程序可能在主线程上做了太多的

  • 我找不到如何从< code>Activity更改fragment的< code>textview。我有4个文件: frag_class.xml有textView,我想更改MainActivity.java的文本。FragmentClass扩展了片段,此片段显示在MainActivity中,FragmentClass具有: 在MainActivity中,我尝试了这个: 但可悲的是,这段代码给了我Nu

  • 公共视图onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState){View v=inflater.inflate(r.layout.fragment_main,container,false); fragment.xml null

  • 设置文本指针异常,我得到错误。 } 我得到的错误; E/AndroidRuntime:致命异常:主进程:com.vortex.soruhafizam,PID:6341 java.lang.nullPointerException:尝试对位于com.vortex.soruhafizam.fragmentbirinci.onCreateView(Fragmentbirinci.java:32)的And