设置sqlite数据库的问题

时间:2018-09-18 12:04:07

标签: java android sqlite

我是Android新手,并尝试使用开源项目。项目数据库是sqlite数据库。当我运行项目并检查时,我发现android设备监视器中没有数据。请有人检查我的代码是否有错误?

package com.andisofttechnology.myapplication;


import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.widget.Toast;

public class databaseHandler {
    SQLiteDatabase database;
    Activity activity;

    public databaseHandler(Activity activity) {
        this.activity = activity;
        database = activity.openOrCreateDatabase("ASSIST", activity.MODE_PRIVATE, null);
        createTable();
    }

    public void createTable()
    {
        try {
            String qu = "CREATE TABLE IF NOT EXISTS STUDENT(name varchar(1000)," +
                    "cl varchar(100), " +
                    "regno varchar(100) primary key, contact varchar(100),roll integer);";
            database.execSQL(qu);
        }catch (Exception e)
        {
            Toast.makeText(activity,"Error Occured for create table",Toast.LENGTH_LONG).show();
        }
        try {
            String qu = "CREATE TABLE IF NOT EXISTS ATTENDANCE(datex date," +
                    "hour int, " +
                    "register varchar(100) ,isPresent boolean);";
            database.execSQL(qu);
        }catch (Exception e)
        {
            Toast.makeText(activity,"Error Occured for create table",Toast.LENGTH_LONG).show();
        }

        try {
            String qu = "CREATE TABLE IF NOT EXISTS NOTES(title varchar(100) not null," +
                    "body varchar(10000), cls varchar(1000), sub varchar(1000) ,datex TIMESTAMP default CURRENT_TIMESTAMP);";
            database.execSQL(qu);
        }catch (Exception e)
        {
            Toast.makeText(activity,"Error Occured for create table",Toast.LENGTH_LONG).show();
        }

        try {
            String qu = "CREATE TABLE IF NOT EXISTS SCHEDULE(cl varchar(100),subject varchar(1000)," +
                    "timex time, day_week varchar(100));";
            database.execSQL(qu);
        }catch (Exception e)
        {
            Toast.makeText(activity,"Error Occured for create table",Toast.LENGTH_LONG).show();
        }
    }

    public boolean execAction(String qu)
    {
        Log.i("databaseHandler", qu);
        try {
            database.execSQL(qu);
        }catch (Exception e)
        {
            Log.e("databaseHandler", qu);
            Toast.makeText(activity,"Error Occured for execAction",Toast.LENGTH_LONG).show();
            return false;
        }
        return true;
    }

    Cursor execQuery(String qu)
    {
        try {
            return database.rawQuery(qu,null);
        }catch (Exception e)
        {
            Log.e("databaseHandler", qu);
//            Toast.makeText(activity,"Error Occured for execAction",Toast.LENGTH_LONG).show();
        }
        return null;
    }
}

Student_registration.class

package com.andisofttechnology.myapplication;

import android.app.Activity;
import android.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
/*import java.util.ArrayList;*/

public class Student_Registartion extends AppCompatActivity {

    private EditText name,register,contact;

    Activity activity = this;
    Spinner spinner;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_student__registartion);

        spinner = (Spinner) findViewById(R.id.spinner);
     /*   ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, AppBase.divisions);
        spinner.setAdapter(adapter);*/

        Button btn = (Button) findViewById(R.id.btnSave);
        assert btn != null;
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveToDatabase(v);
            }
        });
    }


    public void saveToDatabase(View view) {
        EditText name = (EditText)findViewById(R.id.name);
        EditText roll = (EditText)findViewById(R.id.roll);
        EditText register = (EditText)findViewById(R.id.register);
        EditText contact = (EditText)findViewById(R.id.contact);
        String classSelected = spinner.getSelectedItem().toString();

        if(name.getText().length()<2||roll.getText().length()==0||register.getText().length()<2||
                contact.getText().length()<2||classSelected.length()<2)
        {
            AlertDialog.Builder alert = new AlertDialog.Builder(activity);
            alert.setTitle("Invalid");
            alert.setMessage("Insufficient Data");
            alert.setPositiveButton("OK", null);
            alert.show();
            return;
        }

        String qu = "INSERT INTO STUDENT VALUES('" +name.getText().toString()+ "'," +
                "'" + classSelected +"',"+
                "'" + register.getText().toString().toUpperCase() +"',"+
                "'" + contact.getText().toString() +"',"+
                "" + Integer.parseInt(roll.getText().toString()) +");";
        Log.d("Student Reg" , qu);
        AppBase.handler.execAction(qu);
        qu = "SELECT * FROM STUDENT WHERE regno = '" + register.getText().toString() +  "';";
        Log.d("Student Reg" , qu);
        if(AppBase.handler.execQuery(qu)!=null)
        {
            Toast.makeText(getBaseContext(),"Student Added", Toast.LENGTH_LONG).show();
            this.finish();
        }
    }
}

............................................... .......................

原木猫

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.andisofttechnology.myapplication, PID: 32163
                  java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
                      at com.andisofttechnology.myapplication.Student_Registartion.saveToDatabase(Student_Registartion.java:48)
                      at com.andisofttechnology.myapplication.Student_Registartion$1.onClick(Student_Registartion.java:37)
                      at android.view.View.performClick(View.java:6294)
                      at android.view.View$PerformClick.run(View.java:24770)
                      at android.os.Handler.handleCallback(Handler.java:790)
                      at android.os.Handler.dispatchMessage(Handler.java:99)
                      at android.os.Looper.loop(Looper.java:164)
                      at android.app.ActivityThread.main(ActivityThread.java:6494)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

2 个答案:

答案 0 :(得分:0)

在OnCreate方法中执行FindViewById,这就是它创建NullPointException的原因

请参见下面的摘录,希望可以解决该问题

public class Student_Registartion extends AppCompatActivity {

    private EditText name,roll,register,contact;

    Activity activity = this;
    Spinner spinner;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_student__registartion);
         name = (EditText)findViewById(R.id.name);
        roll = (EditText)findViewById(R.id.roll);
        register = (EditText)findViewById(R.id.register);
        contact = (EditText)findViewById(R.id.contact);

        spinner = (Spinner) findViewById(R.id.spinner);
     /*   ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, AppBase.divisions);
        spinner.setAdapter(adapter);*/

        Button btn = (Button) findViewById(R.id.btnSave);
        assert btn != null;
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveToDatabase(v);
            }
        });
    }


    public void saveToDatabase(View view) {
       
        String classSelected = spinner.getSelectedItem().toString();

        if(name.getText().length()<2||roll.getText().length()==0||register.getText().length()<2||
                contact.getText().length()<2||classSelected.length()<2)
        {
            AlertDialog.Builder alert = new AlertDialog.Builder(activity);
            alert.setTitle("Invalid");
            alert.setMessage("Insufficient Data");
            alert.setPositiveButton("OK", null);
            alert.show();
            return;
        }

        String qu = "INSERT INTO STUDENT VALUES('" +name.getText().toString()+ "'," +
                "'" + classSelected +"',"+
                "'" + register.getText().toString().toUpperCase() +"',"+
                "'" + contact.getText().toString() +"',"+
                "" + Integer.parseInt(roll.getText().toString()) +");";
        Log.d("Student Reg" , qu);
        AppBase.handler.execAction(qu);
        qu = "SELECT * FROM STUDENT WHERE regno = '" + register.getText().toString() +  "';";
        Log.d("Student Reg" , qu);
        if(AppBase.handler.execQuery(qu)!=null)
        {
            Toast.makeText(getBaseContext(),"Student Added", Toast.LENGTH_LONG).show();
            this.finish();
        }
    }
}

答案 1 :(得分:0)

您有很多问题,基本上都是相同的,即对象不正确/没有实例化。

以下代码有效并且已被检查。更正用 // <<<<<<<<<< / 进行注释。

请注意,为了进行测试,添加了额外的一行以为微调框提供值,并且尝试从微调框获取值的行已被注释掉。

未对 databaseHandler.java

进行任何更改

Student_Registartion.java :-

public class Student_Registartion extends AppCompatActivity {

    private EditText name,roll,register,contact; //<<<<<<<<<< ADDED roll

    databaseHandler handler; //<<<<<<<<<< ADDED (used instead of AppBase.handler)

    Activity activity = this;
    Spinner spinner;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_student__registartion);

        //<<<<<<<<<< ADDED BLOCK
        name = this.findViewById(R.id.name);
        roll = this.findViewById(R.id.roll);
        register = this.findViewById(R.id.register);
        contact = this.findViewById(R.id.contact);
        //<<<<<<<<<< END OF ADDED BLOCK

        handler = new databaseHandler(this); //<<<<<<<<<< ADDED

        spinner = (Spinner) findViewById(R.id.spinner);
     /*   ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, AppBase.divisions);
        spinner.setAdapter(adapter);*/

        Button btn = (Button) findViewById(R.id.btnSave);
        assert btn != null;
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveToDatabase(v);
            }
        });
    }


    public void saveToDatabase(View view) {
        //<<<<<<<<<<< REMOVED BLOCK
        EditText name = (EditText)findViewById(R.id.name);
        EditText roll = (EditText)findViewById(R.id.roll);
        EditText register = (EditText)findViewById(R.id.register);
        EditText contact = (EditText)findViewById(R.id.contact);
        //<<<<<<<<<<< END OF REMOVED BLOCK

        //String classSelected = spinner.getSelectedItem().toString(); //<<<<<<<<<< commeneted out
        String classSelected = "MyCLass"; //<<<<<<<<<< Temporary get around for no spinner data

        if(name.getText().length()<2||roll.getText().length()==0||register.getText().length()<2||
                contact.getText().length()<2||classSelected.length()<2)
        {
            AlertDialog.Builder alert = new AlertDialog.Builder(activity);
            alert.setTitle("Invalid");
            alert.setMessage("Insufficient Data");
            alert.setPositiveButton("OK", null);
            alert.show();
            return;
        }

        String qu = "INSERT INTO STUDENT VALUES('" +name.getText().toString()+ "'," +
                "'" + classSelected +"',"+
                "'" + register.getText().toString().toUpperCase() +"',"+
                "'" + contact.getText().toString() +"',"+
                "" + Integer.parseInt(roll.getText().toString()) +");";
        Log.d("Student Reg" , qu);
        handler.execAction(qu); //<<<<<<<<<< changed
        qu = "SELECT * FROM STUDENT WHERE regno = '" + register.getText().toString() +  "';";
        Log.d("Student Reg" , qu);
        if(handler.execQuery(qu)!=null) //<<<<<<<<< changed
        {
            Toast.makeText(getBaseContext(),"Student Added", Toast.LENGTH_LONG).show();
            this.finish();
        }
    }
}

测试结果

以下是成功添加数据的运行日志(Toasts execAction发生错误,重复,Toasts Student已添加,并且在没有输入数据时显示对话框):-

09-18 20:45:23.160 1379-1379/so52386209.so52386209 D/Student Reg: INSERT INTO STUDENT VALUES('harold','MyCLass','BLAH','blah',54321);
09-18 20:45:23.160 1379-1379/so52386209.so52386209 I/databaseHandler: INSERT INTO STUDENT VALUES('harold','MyCLass','BLAH','blah',54321);
09-18 20:45:23.160 1379-1379/so52386209.so52386209 E/databaseHandler: INSERT INTO STUDENT VALUES('harold','MyCLass','BLAH','blah',54321);
09-18 20:45:23.164 1379-1379/so52386209.so52386209 D/Student Reg: SELECT * FROM STUDENT WHERE regno = 'blah';
09-18 20:45:23.212 1379-1379/so52386209.so52386209 W/IInputConnectionWrapper: showStatusIcon on inactive InputConnection
09-18 20:45:23.680 1379-1379/so52386209.so52386209 D/OpenGLRenderer: TextureCache::flush: target size: 2284
    TextureCache::callback: name, removed size, mSize = 57, 1728, 2080
09-18 20:49:49.900 1379-1379/so52386209.so52386209 W/EGL_genymotion: eglSurfaceAttrib not implemented
09-18 20:49:49.916 1379-1379/so52386209.so52386209 D/OpenGLRenderer: TextureCache::get: create texture(0xb8f77208): name, size, mSize = 158, 1728, 3808
09-18 20:49:58.896 1379-1382/so52386209.so52386209 D/dalvikvm: GC_CONCURRENT freed 223K, 9% free 6603K/7239K, paused 10ms+0ms, total 14ms
09-18 20:50:24.516 1379-1379/so52386209.so52386209 D/Student Reg: INSERT INTO STUDENT VALUES('ian','MyCLass','77889900','something',12345);
09-18 20:50:24.516 1379-1379/so52386209.so52386209 I/databaseHandler: INSERT INTO STUDENT VALUES('ian','MyCLass','77889900','something',12345);
09-18 20:50:24.520 1379-1379/so52386209.so52386209 D/Student Reg: SELECT * FROM STUDENT WHERE regno = '77889900';