2014-11-05 13 views
-2

從EditText獲取字符串時,出現空指針異常。是否因爲我正在使用片段,我應該使用異步任務嗎?我不知道爲什麼會發生這種情況。當我添加​​行時出現錯誤。關於在片段中創建視圖,從EditText獲取字符串時獲取空指針異常

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:id="@+id/LinearLayout1" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    tools:context="com.tromto.analyzevalue.MainActivity$PlaceholderFragment" > 

    <EditText 
     android:id="@+id/editText1" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:ems="10" 
     android:inputType="numberDecimal" > 

     <requestFocus /> 
    </EditText> 

    <Button 
     android:id="@+id/button1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Button" /> 

</LinearLayout> 



public class MyFragment1 extends Fragment { 
    EditText text1; 
    Button button1; 
    String s1; 

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

     Toast t = Toast.makeText(getActivity(), "Section 1", Toast.LENGTH_LONG); 
     t.show(); 
    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 

     final View v = inflater.inflate(R.layout.fragment_main, container, false); 

     text1 = (EditText)getActivity().findViewById(R.id.editText1); 
     s1 = text1.getText().toString(); 

     return v; 
    } 
} 

回答

3

您正在嘗試使用Fragment的父級活動中的findViewById。相反,你應該在你的Fragment的View中找到ViewById。

使用:代替

text1 = (EditText) v.findViewById(R.id.editText1); 

text1 = (EditText)getActivity().findViewById(R.id.editText1); 
+1

雖然這個答案是正確的,考慮的是,你的EditText將在此點爲空值(或它的默認值)。沒有評論家,只是一個說明。 – Knickedi 2014-11-05 19:55:39

+1

此行的默認值不會導致錯誤,但之後可能會導致問題。 – 2014-11-05 20:02:56

+0

那麼我應該在哪裏編輯文本來聽取用戶的價值。我應該去做一個異步任務還是什麼是最好的程序? – 2014-11-05 20:15:41

-2

我剛剛回答了類似的問題。在EditText1開始時你的值是空的。不要在創建時使用解決方案,或者在必要時填寫一些文本。

相關問題