从sqlite数据库访问数据?

时间:2016-06-08 16:29:56

标签: android

我正在尝试从数据库中检索数据但是当我调用showData()时,应用程序会停止。一切看起来都不错,但我不知道为什么会这样。请帮忙,我是android新手。

这属于主要活动:

   public class MainActivity extends AppCompatActivity {
    Button allContact,addContact,editContact,searchContact,deleteContact;
    EditText name,phone;Button add;
    TextView t,t2;
    String dbString="";
    String dbString2="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        allContact=(Button)findViewById(R.id.button);
        addContact =(Button)findViewById(R.id.button2);
        editContact=(Button)findViewById(R.id.button3);
        searchContact=(Button)findViewById(R.id.button4);
        deleteContact =(Button)findViewById(R.id.button5);

        addContact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setContentView(R.layout.addcontectlayout_main);
                name=(EditText)findViewById(R.id.editText);
                phone=(EditText)findViewById(R.id.editText2);
                add=(Button)findViewById(R.id.button6);

                add.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String takeName=name.getText().toString().toLowerCase();
                        String takePhone=phone.getText().toString();


                        ContactDatabase onbOfContactDatabase=new ContactDatabase(getBaseContext());
                        onbOfContactDatabase.insertContact(takeName,takePhone);
                        Toast.makeText(getBaseContext(), "data is inserted", Toast.LENGTH_LONG).show();

                    }
                });
            }
        });

        allContact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(v.getContext(), AllContact.class);
                startActivity(intent);


            }
        });

    }
}

此课程在计划开始后出现:

public class AllContact extends AppCompatActivity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.allcontactlayout_main);

      TextView  t=(TextView)findViewById(R.id.textView);
       TextView t2=(TextView)findViewById(R.id.textView2);

        ContactDatabase onbOfContactDatabase=new ContactDatabase(getBaseContext());

       Cursor get= onbOfContactDatabase.showData();
      //when i call showData application stope.


    }
}

这属于数据库:

public class ContactDatabase extends SQLiteOpenHelper {
    SQLiteDatabase db;
    public static final String DATABASE_NAME="totalContact.db";
    public static final  String TABLE_NAME="contact";
    public static final  String NAME="name";
    public static final  String PHONE="phone";

    public ContactDatabase(Context context) {
        super(context, DATABASE_NAME, null, 1);

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        try {
            db.execSQL("craete table contact" +
                    "(id integer primary key autoincrement, name text, phone text)");
        }catch(android.database.SQLException e){

        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS contact");
        onCreate(db);
    }

    public void insertContact(String nam,String mob){

        db=this.getWritableDatabase();
        ContentValues contentValues=new ContentValues();

        contentValues.put(NAME,nam);
        contentValues.put(PHONE,mob);

        db.insert(TABLE_NAME, null, contentValues);
        db.close();
    }

    public Cursor showData(){

        db=this.getWritableDatabase();

        Cursor res =  db.rawQuery("SELECT  * FROM contact", null);
        return res;

    }
}

logcat是:

01-06 21:51:36.282 177-177/? A/libc: invalid address or address of corrupt block 0xa2be0 passed to dlfree
06-08 21:53:00.359 11680-11680/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                   Process: com.example.firstproject.contactinfo, PID: 11680
                                                   android.database.sqlite.SQLiteException: no such table: contact (code 1): , while compiling: SELECT  * FROM contact
                                                       at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                       at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
                                                       at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
                                                       at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                       at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
                                                       at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
                                                       at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
                                                       at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1316)
                                                       at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1255)
                                                       at com.example.firstproject.contactinfo.ContactDatabase.showData(ContactDatabase.java:58)
                                                       at com.example.firstproject.contactinfo.MainActivity$2.onClick(MainActivity.java:64)
                                                       at android.view.View.performClick(View.java:4761)
                                                       at android.view.View$PerformClick.run(View.java:19767)
                                                       at android.os.Handler.handleCallback(Handler.java:739)
                                                       at android.os.Handler.dispatchMessage(Handler.java:95)
                                                       at android.os.Looper.loop(Looper.java:135)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5312)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at java.lang.reflect.Method.invoke(Method.java:372)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)

3 个答案:

答案 0 :(得分:0)

在初始化任何视图元素之前(setContentView(R.layout.allcontactlayout_main)之后),将onClickListeneronCreate移至super.onCreate方法。

该行初始化了该活动的视图,在您设置之前,您无法查找 allContact按钮(我假设它是按钮)内容视图。 内容视图包含按钮和其他元素,在该视图中调用方法findViewById

答案 1 :(得分:0)

首先将setContentView(R.layout.allcontactlayout_main)从onClickListener移动到onCreate方法然后

public Cursor showData()
{
  SQLiteDatabase database = this.getReadableDatabase();
    String selectQuery = "SELECT * FROM contact";
    return database.rawQuery(selectQuery, null);

}

调用数据库showdata()方法

ContactDatabase onbOfContactDatabase=new ContactDatabase(YOURACTIVITY.this);
Cursor get= onbOfContactDatabase.showData();

答案 2 :(得分:0)

1)您应该在TextView t方法之前声明TextView t2onCreate。然后在onCreate内部将其初始化为

t = (TextView)findViewById(R.id.textView);

t2 = (TextView)findViewById(R.id.textView2);

2)最好还有两个负责打开和关闭数据库的方法。这是我创建的数据库类的示例。

public class DaysDatabase {

    //some variables

    private DbHelper ourHelper;
    private final Context ourContext;
    private SQLiteDatabase ourDatabase;

    private static class DbHelper extends SQLiteOpenHelper {

        //again some code

    }

    public DaysDatabase open(){
        ourHelper = new DbHelper(ourContext);
        ourDatabase = ourHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        ourHelper.close();
    }

    //your method
    public Cursor showData(){
        Cursor res =  ourDatabase.rawQuery("SELECT  * FROM contact", null);
        return res;

    }

    /*
     *    rest of the necessary code
     */
}

要更好地了解本教程:

https://thenewboston.com/videos.php?cat=6&video=16832

该教程适用于多个视频,但我发现它们非常有用。