连接数据库时在android程序中获取错误

时间:2013-04-16 17:52:33

标签: android database sqlite

String getId=db1.getId().toString();

SQLiteDatabase db=this.getReadableDatabase();

在logcat的android程序中给出错误。 '过滤错误的Logcat数据'

04-16 03:10:09.769: E/dalvikvm(26422): Unable to open stack trace file '/data/anr/traces.txt': Is a directory
04-16 03:10:10.109: E/AndroidRuntime(26422): FATAL EXCEPTION: main
04-16 03:10:10.109: E/AndroidRuntime(26422): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.doctors.prescription/com.doctors.prescription.ThirdActivity}: java.lang.NullPointerException
04-16 03:10:10.109: E/AndroidRuntime(26422):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
04-16 03:10:10.109: E/AndroidRuntime(26422):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
04-16 03:10:10.109: E/AndroidRuntime(26422):    at android.app.ActivityThread.access$600(ActivityThread.java:123)
04-16 03:10:10.109: E/AndroidRuntime(26422):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
04-16 03:10:10.109: E/AndroidRuntime(26422):    at android.os.Handler.dispatchMessage(Handler.java:99)
04-16 03:10:10.109: E/AndroidRuntime(26422):    at android.os.Looper.loop(Looper.java:137)
04-16 03:10:10.109: E/AndroidRuntime(26422):    at android.app.ActivityThread.main(ActivityThread.java:4424)
04-16 03:10:10.109: E/AndroidRuntime(26422):    at java.lang.reflect.Method.invokeNative(Native Method)
04-16 03:10:10.109: E/AndroidRuntime(26422):    at java.lang.reflect.Method.invoke(Method.java:511)
04-16 03:10:10.109: E/AndroidRuntime(26422):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
04-16 03:10:10.109: E/AndroidRuntime(26422):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
04-16 03:10:10.109: E/AndroidRuntime(26422):    at dalvik.system.NativeStart.main(Native Method)
04-16 03:10:10.109: E/AndroidRuntime(26422): Caused by: java.lang.NullPointerException
04-16 03:10:10.109: E/AndroidRuntime(26422):    at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:157)
04-16 03:10:10.109: E/AndroidRuntime(26422):    at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:231)
04-16 03:10:10.109: E/AndroidRuntime(26422):    at com.doctors.prescription.ThirdActivityDb.selectOne(ThirdActivityDb.java:67)
04-16 03:10:10.109: E/AndroidRuntime(26422):    at com.doctors.prescription.ThirdActivity.onCreate(ThirdActivity.java:50)
04-16 03:10:10.109: E/AndroidRuntime(26422):    at android.app.Activity.performCreate(Activity.java:4465)
04-16 03:10:10.109: E/AndroidRuntime(26422):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
04-16 03:10:10.109: E/AndroidRuntime(26422):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
04-16 03:10:10.109: E/AndroidRuntime(26422):    ... 11 more

'数据库文件'

package com.doctors.prescription;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;

public class ThirdActivityDb extends SQLiteOpenHelper{


    public static final String KEY_ID = "id";
    public static final String KEY_NAME = "name";
    public static final String KEY_AGE = "age";
    public static final String KEY_GENDER = "gender";
    public static final String KEY_NUMBER = "number";
    public static final String KEY_EMAIL = "email";
    private static final String DATABASE_NAME = "Doctordb";
    private static final String DATABASE_TABLE = "doctor_register";
    private static final int DATABASE_VERSION = 2;


    private static final String CREATE_TABLE_QUERY = "CREATE TABLE "
            + ThirdActivityDb.DATABASE_NAME + " (" + ThirdActivityDb.KEY_ID
            + " INTEGER PRIMARY KEY AUTO INCREMENT , "
            + ThirdActivityDb.KEY_NAME + " VARCHAR," + ThirdActivityDb.KEY_AGE
            + " VARCHAR," + ThirdActivityDb.KEY_GENDER + " VARCHAR,"
            + ThirdActivityDb.KEY_NUMBER + " VARCHAR,"
            + ThirdActivityDb.KEY_EMAIL + " VARCHAR)";


    public ThirdActivityDb(Context context, String name, CursorFactory factory,
            int version) {
        super(context, DATABASE_NAME, factory, DATABASE_VERSION);
        // TODO Auto-generated constructor stub
    }


    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL(CREATE_TABLE_QUERY);
        onCreate(db);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        onUpgrade(db, 0,DATABASE_VERSION);
    }

    public void InsertData(String name,String age,String gender,String number,String email){
        SQLiteDatabase db=this.getWritableDatabase();
        ContentValues contentvalue=new ContentValues();
        contentvalue.put("name", name);
        contentvalue.put("age", age);
        contentvalue.put("gender", gender);
        contentvalue.put("number", number);
        contentvalue.put("email", email);
        db.insert("doctor_register", null, contentvalue);
        db.close();
    }
    public Cursor selectOne(String id)
    {
        SQLiteDatabase db=this.getReadableDatabase();
        String query = "select id from doctor_register order by id desc limit 1 ";
        Cursor c= db.rawQuery(query, new String[]{id});
        if(c.getCount()!=0)
        {
            return c;
        }
        return null;
    }
    public Cursor select(String id , String name)
    {
        SQLiteDatabase db=this.getReadableDatabase();
        String query = "select name from doctor_register where id="+id+" and name="+name;
        Cursor c= db.rawQuery(query, new String[]{name});
        if(c.getCount()!=0)
        {
            return c;
        }
        return null;
    }
    public Cursor getId(){
        SQLiteDatabase db=this.getReadableDatabase();
        Cursor c = db.rawQuery("select id from doctor_register order by id desc limit 1 " ,null );
        if(c.getCount()!=0)
            return c;
        return null;
    }

}

'ThirdActivity.class'

package com.doctors.prescription;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

public class ThirdActivity extends Activity {
    Button third_create, third_cancel;
    EditText name, age, number, email;
    TextView generated_id;
    private RadioGroup radio_group;
    RadioButton radio_Gender;
    int  radio_id;
    String KEY_ID="KEY_ID";
    String KEY_GETID="KEY_GETID";
    ThirdActivityDb db1 = new ThirdActivityDb(null, null, null, 2);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_third);
        //requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        name = (EditText) findViewById(R.id.third_editText1);
        age = (EditText) findViewById(R.id.third_editText2);
        radio_group=(RadioGroup)findViewById(R.id.radioGroup1);
        number = (EditText) findViewById(R.id.third_editText3);
        email = (EditText) findViewById(R.id.third_editText4);
        String getId=db1.getId().toString();
        SharedPreferences SPref=getPreferences(MODE_PRIVATE);
        SharedPreferences.Editor editor=SPref.edit();
        editor.putString(KEY_ID, getId);
        editor.commit();

        String id = SPref.getString(KEY_GETID, KEY_GETID );
        generated_id = (TextView) findViewById(R.id.generated_id);
        String s=db1.selectOne(id).toString();
        generated_id.setText(s);
        third_create = (Button) findViewById(R.id.third_create_new);
        third_create.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (name.getText().toString().length() == 0
                        || age.getText().toString().length() == 0
                        || number.getText().toString().length() == 0
                /* || email.getText().toString().length() == 0 */) {
                    name.setError("Please enter the name of patient!");
                    age.setError("Please enter the age of patient");
                    number.setError("Please enter the contact number of patient");
                    email.setError("Please enter the email of patient");
                } else {

                    //generated_id.setText(db.getRecord(TRIM_MEMORY_UI_HIDDEN).toString());
                    int selected_id = radio_group.getCheckedRadioButtonId();
                    radio_Gender = (RadioButton) findViewById(selected_id);


                    db1.InsertData(name.getText().toString(), age
                            .getText().toString(), radio_Gender.getText().toString(),
                            number.getText().toString(), email.getText()
                                    .toString());
                    db1.close();
                    Intent intent = new Intent(getApplicationContext(),
                            WriteTextActivity.class);
                    startActivity(intent);

                }
            }
        });
        third_cancel = (Button) findViewById(R.id.third_cancel);
        third_cancel.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(getApplicationContext(),
                        SecondActivity.class);
                startActivity(intent);
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.third, menu);
        return true;
    }

}

提前致谢。

2 个答案:

答案 0 :(得分:2)

我可以在代码中看到一些问题,CREATE_TABLE_QUERY您正在使用DATABASE_NAME代替DATABASE_TABLE

private static final String CREATE_TABLE_QUERY = "CREATE TABLE "
        + ThirdActivityDb.DATABASE_TABLE + " (" + ThirdActivityDb.KEY_ID
        + " INTEGER PRIMARY KEY AUTO INCREMENT , "
        + ThirdActivityDb.KEY_NAME + " VARCHAR," + ThirdActivityDb.KEY_AGE
        + " VARCHAR," + ThirdActivityDb.KEY_GENDER + " VARCHAR,"
        + ThirdActivityDb.KEY_NUMBER + " VARCHAR,"
        + ThirdActivityDb.KEY_EMAIL + " VARCHAR)";

onCreate(db);方法

中删除onCreate(SQLiteDatabase db)
@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    db.execSQL(CREATE_TABLE_QUERY);
}



@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE); 
    // Create tables again
    onCreate(db);
}

我不确定这是否会导致问题implements BaseColumns尝试删除它。

<强>被修改

public String getId(){
    SQLiteDatabase db=this.getReadableDatabase();
    Cursor c = db.rawQuery("select id from doctor_register order by id desc limit 1 " ,null );
    if(c.getCount() > 0) {
        c.moveToFirst();
        return c.getString(0);
    }
    return null;
}

呼叫

String getId = db1.getId();

答案 1 :(得分:0)

您只创建表Doctordb,但尝试查询表doctor_register

String query = "select name from doctor_register where id="+id+" and name="+name;