在向SQLite数据库添加文本时,Android程序崩溃

时间:2016-07-01 07:57:07

标签: java android sqlite

我正在尝试获取用户输入并将其保存到数据库中。我必须在活动中使用EditText个字段,并使用一个按钮将数据保存到数据库中。每当我这样做时,程序就会崩溃,我不知道是什么导致它。

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    DatabaseHandler db = new DatabaseHandler(this);

    public void onAdd() {
        EditText name = (EditText)findViewById(R.id.inputName);
        String nameString = name.getText().toString();
        EditText quantity = (EditText)findViewById(R.id.inputQuantity);
        String quantityString = quantity.getText().toString();
        db.addWorkout(new Workout(nameString,quantityString));
    }
}


java.lang.IllegalStateException: Could not find method onAdd(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton
    at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:325)
    at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
    at android.view.View.performClick(View.java:5198)
    at android.view.View$PerformClick.run(View.java:21147)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

1 个答案:

答案 0 :(得分:2)

您必须将视图传递给onAdd方法,如下所示:

code