我的android项目有问题。我正在使用Datamap将数据发送到我的服装。我有一个datalistener用于获取磨损主要活动中的数据。
基本上我想从活动中更改片段的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>
Mainactivity
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);
}
}
答案 0 :(得分:1)
在片段中实现单一实现,在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
希望有所帮助!