MainControlScreenFragment

MainControlScreenFragment

我的android项目有问题。我正在使用Datamap发送数据。我有一个数据侦听器,用于获取磨损主要活动中的数据。

基本上我想从活动更改片段的textView的文本。当我尝试执行此操作时,它失败了,并显示-> NullPointerException。我该如何解决?

那是因为我在mainactivity的onCreate方法中调用该片段吗?

MainActivity xml:

<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

</android.support.v4.view.ViewPager>


主要活动

public class MainActivity extends FragmentActivity {

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

        viewpager = (ViewPager) findViewById(R.id.pager);
        FragmentManager fm = getSupportFragmentManager();
        viewpager.setAdapter(new FragmentAdapter(fm));

        dataListener = new DataApi. DataListener() {
            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onDataChanged(DataEventBuffer dataEvents) {
                final ArrayList<DataEvent> events = FreezableUtils.freezeIterable(dataEvents);
                DataMap mediaMap;
                DataMap updateMap;
                for (DataEvent event : events) {
                    PutDataMapRequest putDataMapRequest =
                            PutDataMapRequest.createFromDataMapItem(DataMapItem.fromDataItem(event.getDataItem()));

                    if (event.getType() == DataEvent.TYPE_CHANGED) {
                        if (event.getDataItem().getUri().getPath().equals("/myPath")) {
                            dataMap= DataMapItem.fromDataItem(event.getDataItem()).getDataMap();

                            FragmentA fragment = (MainControlScreenFragment) getSupportFragmentManager().findFragmentById(R.id.fragmentA);

}
}

最佳答案

在片段中执行单例实现,在onCreateView()方法上方的MainControlScreenFragment.class中添加以下行:

private static MainControlScreenFragment instance;

public MainControlScreenFragment() {
}

/**
 * Static method which return the instance of the fragment. If the fragment is null, load it,
 * else create new fragment. Singleton pattern.
 *
 * @return
 */
public static MainControlScreenFragment getInstance() {
    if (instance == null) {
        instance = new MainControlScreenFragment();

    }

    return instance;
}


之后,在您的活动中呼叫MainControlScreenFragment.getInstance().changeTextMethod();而不是MainControlScreenFragment fragment = (MainControlScreenFragment) getSupportFragmentManager().findFragmentById(R.id.fragmentA);

请注意,您的changeTextMethod()应该在MainControlScreenFragment.class中声明为公开

希望对您有所帮助!

10-04 23:10