SQlite dataabase操作和AsyncTask

时间:2016-11-11 20:13:23

标签: android sqlite android-asynctask nullpointerexception android-sqlite

我正在学习AsyncTask类,并通过以下示例来练习。我有一个UI,它有一个EditText(用于数据输入),一个带5个radiobuttons的radiogroup和一个按钮(提交)。这个想法是当用户选择radiobutton并输入EDITTEXT的值时。按下按钮后,信息将转到数据库表。创建数据库表并且整个代码有效。但我想在后台使用AsyncTask运行数据库操作功能。应用AsyncTask类后出现问题。请帮帮我。

这里是没有AsyncTask的代码:

    package jhapps.com.myspending;

    import android.os.Bundle;
    import android.support.design.widget.FloatingActionButton;
    import android.support.design.widget.Snackbar;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.Toolbar;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.RadioButton;
    import android.widget.RadioGroup;
    import android.widget.Toast;

    public class Child extends AppCompatActivity {

private static Button btnsubmit;
private static RadioGroup rgChild;
private static RadioButton rbChild;
private static EditText dollarAmount;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_child);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
    DataSubmitChild();
}

private void DataSubmitChild(){
    btnsubmit=(Button)findViewById(R.id.btnSubmitChild);
    btnsubmit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            rgChild = (RadioGroup) findViewById(R.id.rgChildren);
            int selectedRbChild = rgChild.getCheckedRadioButtonId();
            rbChild = (RadioButton) findViewById(selectedRbChild);
            String rbChildF = rbChild.getText().toString();



            dollarAmount = (EditText) findViewById(R.id.amountEnterChild);
            String dollarAmountF = dollarAmount.getText().toString();
            float dollarAmountFloat = Float.parseFloat(dollarAmountF);





        DataBaseHelper dataBaseHelper = new DataBaseHelper(Child.this);

        if (dollarAmountFloat != 0 & rbChildF != "") {
            int itemID;

            switch (rbChildF) {
                case "Daycare":itemID=53;
                    dataBaseHelper.insertDataSpending(itemID, dollarAmountFloat);
                    break;
                case "Lessons and Activities": itemID=54;
                    dataBaseHelper.insertDataSpending(itemID, dollarAmountFloat);
                    break;
                case "Allowance":itemID=55;
                    dataBaseHelper.insertDataSpending(itemID, dollarAmountFloat);
                    break;
                case "School Supplies and Fees" :itemID=56;
                    dataBaseHelper.insertDataSpending(itemID, dollarAmountFloat);
                    break;
                case "Babysitting":itemID=57;
                    dataBaseHelper.insertDataSpending(itemID, dollarAmountFloat);
                    break;

            }
            Toast.makeText(Child.this,"Your spending is recorded!",Toast.LENGTH_LONG).show();

            dollarAmount.setText("");
            rgChild.clearCheck();
        }else
            Toast.makeText(Child.this,"Please choose an Item",Toast.LENGTH_LONG).show();
        }

    });


    }

}

这是使用AsyncTask的代码不起作用:

    package jhapps.com.myspending;

    import android.content.Context;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.support.design.widget.FloatingActionButton;
    import android.support.design.widget.Snackbar;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.Toolbar;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.RadioButton;
    import android.widget.RadioGroup;
    import android.widget.Toast;

    public class Child extends AppCompatActivity {
private static Button btnsubmit;
private static RadioGroup rgChild;
private static RadioButton rbChild;
private  EditText dollarAmount;

Context ctx;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_child);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
    //DataSubmitChild();
    rgChild = (RadioGroup) findViewById(R.id.rgChildren);
    int selectedRbChild = rgChild.getCheckedRadioButtonId();
    rbChild = (RadioButton) findViewById(selectedRbChild);

    dollarAmount = (EditText) findViewById(R.id.amountEnterChild);



    btnsubmit=(Button)findViewById(R.id.btnSubmitChild);
    btnsubmit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            BackgroundTask backgroundTask=new BackgroundTask();
            backgroundTask.execute();
        }
    });
    dollarAmount.setText("");
    rgChild.clearCheck();
}
    private class BackgroundTask extends AsyncTask<Void,Void,Void>{
String rbChildF = rbChild.getText().toString();
String dollarAmountF = dollarAmount.getText().toString();
float dollarAmountFloat = Float.parseFloat(dollarAmountF);

@Override
protected Void doInBackground(Void... params) {


    DataBaseHelper dataBaseHelper = new DataBaseHelper(getBaseContext());

            if (dollarAmountFloat != 0 & rbChildF != "") {
                int itemID;

                switch (rbChildF) {
                    case "Daycare":itemID=53;
                        dataBaseHelper.insertDataSpending(itemID, dollarAmountFloat);
                        break;
                    case "Lessons and Activities": itemID=54;
                        dataBaseHelper.insertDataSpending(itemID, dollarAmountFloat);
                        break;
                    case "Allowance":itemID=55;
                        dataBaseHelper.insertDataSpending(itemID, dollarAmountFloat);
                        break;
                    case "School Supplies and Fees" :itemID=56;
                        dataBaseHelper.insertDataSpending(itemID, dollarAmountFloat);
                        break;
                    case "Babysitting":itemID=57;
                        dataBaseHelper.insertDataSpending(itemID, dollarAmountFloat);
                        break;

                }
                Toast.makeText(Child.this,"Your spending is recorded!",Toast.LENGTH_LONG).show();


            }else
                Toast.makeText(Child.this,"Please choose an Item",Toast.LENGTH_LONG).show();

    return null;
}

} }

这是错误消息:

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: jhapps.com.myspending, PID: 27613
              java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.RadioButton.getText()' on a null object reference
                  at jhapps.com.myspending.Child$BackgroundTask.<init>(Child.java:62)
                  at jhapps.com.myspending.Child$BackgroundTask.<init>(Child.java:0)
                  at jhapps.com.myspending.Child$2.onClick(Child.java:54)
                  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)

2 个答案:

答案 0 :(得分:1)

这些观点都是空的......

private class BackgroundTask extends AsyncTask<Void,Void,Void>{

    // Don't put these here...
    String rbChildF = rbChild.getText().toString();
    String dollarAmountF = dollarAmount.getText().toString();
    float dollarAmountFloat = Float.parseFloat(dollarAmountF);

如果你真的需要这些值,那就做一个构造函数

private class BackgroundTask extends AsyncTask<Void,Void,Void>{

    String rbChildF, dollarAmountF;
    float dollarAmount;

    public BackgroundTask(String radio, String dollarAmtF, float dollars) {
        this.rbChildF = radio;
        this.dollarAmountF = dollarAmtF;
        this.dollarAmount = dollars;
    }

并在

中传递这些值
    String rbChildF = rbChild.getText().toString();
    String dollarAmountF = dollarAmount.getText().toString();
    float dollarAmountFloat = Float.parseFloat(dollarAmountF);

    new BackgroundTask(rbChildF, dollarAmountF, dollarAmountFloat).execute();

答案 1 :(得分:0)

man asyctask是一个独立的脚本块,它不知道你的观点值。 要使asynctask知道您的视图edittext或radio值,您应该将父视图传递给asyctask构造函数。在构造函数体中使用findviewbyid来检索将在doinbackground方法中使用的值。

记住。构造函数和onpostexecute在主线程上执行。 asyctask包含在doinbackground中发生的事情。