在TabLayout中更新TextView会导致NullPointerException

时间:2016-06-29 06:37:29

标签: java android android-fragments nullpointerexception android-tablayout

我正在尝试创建一个包含3个标签的应用,每个标签代表我从其他设备收到的数据。我每5分钟左右收到一次这样的数据,所以我需要标签中的文字不断变化。但是,我无法更新选项卡中的TextView以匹配最新的传入数据,因为它会导致NullPointerException。以下是该问题的主要活动:

public class PlantStatsActivity extends FragmentActivity {

public DrawerLayout mDrawerLayout;
public ListView mDrawerList;
private TabLayout tabLayout;
private ViewPager viewPager;
private ViewPageAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_plant_stats);
    initPubNub();


    tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    tabLayout.addTab(tabLayout.newTab().setText("Moisture"));
    tabLayout.addTab(tabLayout.newTab().setText("Light"));
    tabLayout.addTab(tabLayout.newTab().setText("Temperature"));

    viewPager = (ViewPager) findViewById(R.id.pager);
    adapter = new ViewPageAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
    viewPager.setAdapter(adapter);

    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

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

        }

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

        }
    });

    LightFragment lightFragment = (LightFragment) adapter.getItem(1);
    lightFragment.setLightText("Test"); //This is where the problem lies.
}

我得到一个NullPointerException,因为字段lightText为空(我现在只是想让它在“Light”选项卡上工作)。

这是我试图在活动中更新TextView的片段

public class LightFragment extends Fragment {
    private int lightLevel;
    private TextView lightText;

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View v = inflater.inflate(R.layout.fragment_light, container, false);
        lightText = (TextView) v.findViewById(R.id.current_level_light);
        return v;
    }

    public int getLightLevel() {
        return lightLevel;
    }

    public void setLightLevel(int newLightLevel){
        lightLevel = newLightLevel;
    }

    public TextView getLightText() {
        return lightText;
    }

    public void setLightText(String newText) {
        lightText.setText(newText); //Method used in activity causing crash.
    }

}

我包含了ViewPageAdapter类:

public class ViewPageAdapter extends FragmentStatePagerAdapter {
    int mNumOfTabs;

    public ViewPageAdapter(FragmentManager fm, int numOfTabs){
        super(fm);
        this.mNumOfTabs = numOfTabs;
    }

    @Override
    public Fragment getItem(int position){
        switch (position){
            case 0:
                MoistureFragment tab1 = new MoistureFragment();
                return tab1;
            case 1:
                LightFragment tab2 = new LightFragment();
                return tab2;
            case 2:
                TemperatureFragment tab3 = new TemperatureFragment();
                return tab3;
            default:
                return null;
        }
    }

    @Override
    public int getCount(){
        return mNumOfTabs;
    }

}

显示接收和处理数据的过程的代码,这是一个存储我感兴趣的int值的JSON对象。在主要活动的开头调用。

public void initPubNub(){
    PNConfiguration pnConfiguration = new PNConfiguration();
    pnConfiguration.setPublishKey(PUBLISH_KEY);
    pnConfiguration.setSubscribeKey(SUBSCRIBE_KEY);
    pnConfiguration.setUuid("AndroidPiLight");
    mPubNub = new PubNub(pnConfiguration);
    mPubNub.subscribe().channels(Arrays.asList(CHANNEL)).execute();
    Log.d(TAG, "subscribed");

    mPubNub.addListener(new SubscribeCallback() {
        @Override
        public void status(PubNub pubnub, PNStatus status) {
            // handle any status
        }

        @Override
        public void message(PubNub pubnub, PNMessageResult message) {
            JsonNode lightNode = message.getMessage().findValue("lightValue"); // "lightValue" is JSON key.
            int newLight = lightNode.asInt();
            Log.d(TAG, "Got message as int");
            Bundle data = new Bundle();
            data.putInt("lightMessage", newLight);
            Message message1 = new Message();
            message1.setData(data);
            android.os.Handler handler = LightFragment.sUpdateHandler;
            if (handler != null){
                handler.sendMessage(message1);
            }

我是Android的初学者,所以我不确定我是否在应用程序中做错了什么,或者我是否需要添加完全不同的东西来使其工作。我已经彻底查看了Stack Overflow之前的问题,但找不到任何答案。这是我在Stack Exchange上的第一个问题,我们非常感谢任何反馈。

1 个答案:

答案 0 :(得分:0)

在寻呼机适配器类中尝试此操作

       LightFragment tab2 = new LightFragment();
        Bundle data = new Bundle();
        data.putInt("current_page", "id");
        data.putString("current_id","" );
        data.putInt("sub_cat_id","");
        myFragment.setArguments(data);

然后在你的LightFragment类onCreate中获取此包值

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    /** Getting the arguments to the Bundle object */
    Bundle data = getArguments();

    /** Getting integer data of the key current_page from the bundle */
    mCurrentPage = data.getInt("current_page", 0);

    }