-1

我想從另一個活動的片段更新textview。但是當我調用setText方法時,我得到了一個N​​UllPointerException異常。我已經嘗試了以下,但仍然得到NPE。 1.嘗試在Activity中使用FindViewbyId訪問碎片文本視圖。 2.使用片段的方法和從活動呼叫,並傳遞值作爲參數Android:無法更新來自Activity的Fragment中的textview。空指針異常

FragHome活動

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; 
} 
} 

TAB1

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當我嘗試從活動的setText發生。請幫助下回調

+1

我得到了「你的名字未找到異常」 –

+1

你在哪裏初始化了textView。你應該在設置文本之前初始化它。使用findViewById(R.id.textviewtemp)初始化它; –

+0

而且textView存在於片段xml中,但您正嘗試在活動中使用它。這將永遠給NPE。 –

回答

1

用途:

片段類:

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; 
} 
} 

Implment調用回到你的活動class..then更新TextView中。

+0

仍然導致錯誤。你能告訴我如何使用它嗎? –

+0

我已經更新了我的答案。請參閱。 –

+0

你在哪裏添加片段到活動? –