EditText to String null指针异常

时间:2015-07-09 09:09:27

标签: android nullpointerexception

我正在尝试将EditText值转换为String,然后将其存储在Shared首选项中。

- 编辑

activity_my.xml

 <Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Next"
    android:id="@+id/button"
    android:onClick="gotonext"/>

function gotonext()

public void gotonext(View view) {
    EditText phone = (EditText) findViewById(R.id.phone);
    if (phone.getText().toString().length() != 10)
        phone.setError("Enter your mobile number!");
    else {
        SharedPrefs ob = new SharedPrefs();
        ob.storephoneno();
        Intent intent = new Intent(this, Enter_Subjects.class);
        startActivity(intent);
    }
}

SharedPrefs.java

public class SharedPrefs extends Activity {

EditText pNo,semDate,def,criticalDef;
public static String folder = "mySharedDetails";
SharedPreferences myDetails;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my);
    pNo = (EditText) findViewById(R.id.phone);
    semDate = (EditText) findViewById(R.id.semdate);
    def = (EditText) findViewById(R.id.defaulter);
    criticalDef = (EditText) findViewById(R.id.critical_defaulter);
    myDetails = getSharedPreferences(folder,0);
 }

public void storephoneno(){

    String p = pNo.getText().toString();
    SharedPreferences.Editor editor = myDetails.edit();
    editor.putString("phoneNo",p);
    editor.commit();
}

这是我得到的错误:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference

我提到了其他各种解决方案,但都是徒劳的。请尽快回复并解决我的疑问。提前谢谢!

1 个答案:

答案 0 :(得分:0)

你没有夸大你的布局。

如果您在Activity中进行此操作,则需要致电:

setContentView(R.layout.YOURLAYOUT);

在任何绑定之前(在super.onCreate(savedInstanceState);之后调用)

如果您在Fragment中执行此操作,则需要覆盖方法onCreateView

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
   View rootView = inflater.inflate(R.layout.YOURLAYOUT, container, false);
   rootView.findViewById(R.id.linearlayout);
   pNo = (EditText) rootView.findViewById(R.id.phone);
   //bind rest of your widgets in the same way here
   return rootView;
}