为什么SQLite在我的Android Studio中不起作用?

时间:2019-01-19 15:55:59

标签: android sqlite

我正在使用sqlite在android studio中制作一个应用程序,但它不起作用。我创建了一个新项目来测试sqlite,但同样没有成功。然后,我使用sqlite创建了一个更简单的应用程序来避免出错,但是仍然无法正常工作。该应用程序只是不断停止。有谁知道为什么它不起作用?

有一个应用logcat

Logcat:

2019-01-19 16:52:48.127 1605-1605/? E/AudioFlinger: not enough memory for AudioTrack size=131296
2019-01-19 16:52:48.127 1605-1605/? E/AudioFlinger: createRecordTrack_l() initCheck failed -12; no control block?
2019-01-19 16:52:48.141 1605-18287/? I/AudioFlinger: AudioFlinger's thread 0xdf9836c0 tid=18287 ready to run
2019-01-19 16:52:48.143 3235-17962/com.google.android.googlequicksearchbox:search E/IAudioFlinger: createRecord returned error -12
2019-01-19 16:52:48.144 3235-17962/com.google.android.googlequicksearchbox:search E/AudioRecord: AudioFlinger could not create record track, status: -12
2019-01-19 16:52:48.156 3235-17962/com.google.android.googlequicksearchbox:search E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -12.
2019-01-19 16:52:48.160 3235-17962/com.google.android.googlequicksearchbox:search E/android.media.AudioRecord: Error code -20 when initializing native AudioRecord object.
     com.google.android.apps.gsa.shared.speech.b.g: Error reading from input stream
        at com.google.android.apps.gsa.staticplugins.microdetection.d.k.a(SourceFile:91)
        at com.google.android.apps.gsa.staticplugins.microdetection.d.l.run(Unknown Source:14)
        at com.google.android.libraries.gsa.runner.a.a.b(SourceFile:32)
        at com.google.android.libraries.gsa.runner.a.c.call(Unknown Source:4)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:458)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at com.google.android.apps.gsa.shared.util.concurrent.b.g.run(Unknown Source:4)
        at com.google.android.apps.gsa.shared.util.concurrent.b.aw.run(SourceFile:4)
        at com.google.android.apps.gsa.shared.util.concurrent.b.aw.run(SourceFile:4)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:764)
        at com.google.android.apps.gsa.shared.util.concurrent.b.i.run(SourceFile:6)
     Caused by: com.google.android.apps.gsa.shared.exception.GsaIOException: Error code: 393238 | Buffer overflow, no available space.
        at com.google.android.apps.gsa.speech.audio.Tee.j(SourceFile:103)
        at com.google.android.apps.gsa.speech.audio.au.read(SourceFile:2)
        at java.io.InputStream.read(InputStream.java:101)
        at com.google.android.apps.gsa.speech.audio.ao.run(SourceFile:17)
        at com.google.android.apps.gsa.speech.audio.an.run(SourceFile:2)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:458)

还有更多行。如果您愿意,我可以向您发送logcat屏幕。 MainActivity:

public class MainActivity extends Activity {

EditText studentid = (EditText) findViewById(R.id.id);
EditText studentname = (EditText) findViewById(R.id.name);
TextView first = (TextView) findViewById(R.id.first);

@Override
public void onCreate(Bundle save) {
    super.onCreate(save);
}

public void loadStudents(View view) {
    MyDBHandler dbHandler = new MyDBHandler(this, null, null, 1);
    first.setText(dbHandler.loadHandler());
    studentid.setText("");
    studentname.setText("");
}


public void addStudent(View view) {
    MyDBHandler dbHandler = new MyDBHandler(this, null, null, 1);
    int id = Integer.parseInt(studentid.getText().toString());
    String name = studentname.getText().toString();
    Student student = new Student(id, name);
    dbHandler.addHandler(student);
    studentid.setText("");
    studentname.setText("");
}
}

学生:

public class Student {
// fields
private int studentID;
private String studentName;
// constructors
public Student() {}
public Student(int id, String studentname) {
    this.studentID = id;
    this.studentName = studentname;
}
// properties
public void setID(int id) {
    this.studentID = id;
}
public int getID() {
    return this.studentID;
}
public void setStudentName(String studentname) {
    this.studentName = studentname;
}
public String getStudentName() {
    return this.studentName;
}
}

MyDBHandler:

public class MyDBHandler extends SQLiteOpenHelper {
//information of database
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "studentDB.db";
public static final String TABLE_NAME = "Student";
public static final String COLUMN_ID = "StudentID";
public static final String COLUMN_NAME = "StudentName";
//initialize the database
public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
    super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_TABLE = "CREATE TABLE" + TABLE_NAME + "(" + COLUMN_ID +
            "INTEGER PRIMARYKEY," + COLUMN_NAME + "TEXT )";
    db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {}
public String loadHandler() {
    String result = "";
    String query = "SELECT * FROM " + TABLE_NAME;
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(query, null);
    while (cursor.moveToNext()) {
        int result_0 = cursor.getInt(0);
        String result_1 = cursor.getString(1);
        result += String.valueOf(result_0) + " " + result_1 +
                System.getProperty("line.separator");
    }
    cursor.close();
    db.close();
    return result;
}
public void addHandler(Student student) {
        ContentValues values = new ContentValues();
        values.put(COLUMN_ID, student.getID());
        values.put(COLUMN_NAME, student.getStudentName());
        SQLiteDatabase db = this.getWritableDatabase();
        db.insert(TABLE_NAME, null, values);
        db.close();
}
public Student findHandler(String studentname) {

    String query = "Select * FROM " + TABLE_NAME + " WHERE " + COLUMN_NAME + " = " + "'" + studentname + "'";
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(query, null);
    Student student = new Student();
    if (cursor.moveToFirst()) {
        cursor.moveToFirst();
        student.setID(Integer.parseInt(cursor.getString(0)));
        student.setStudentName(cursor.getString(1));
        cursor.close();
    } else {
        student = null;
    }
    db.close();
    return student;
}
public boolean deleteHandler(int ID) {

    boolean result = false;
    String query = "Select * FROM " + TABLE_NAME + " WHERE " + COLUMN_ID + " = '" + String.valueOf(ID) + "'";
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(query, null);
    Student student = new Student();
    if (cursor.moveToFirst()) {
        student.setID(Integer.parseInt(cursor.getString(0)));
        db.delete(TABLE_NAME, COLUMN_ID + "=?",
                new String[] {
            String.valueOf(student.getID())
        });
        cursor.close();
        result = true;
    }
    db.close();
    return result;
}
public boolean updateHandler(int ID, String name) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues args = new ContentValues();
    args.put(COLUMN_ID, ID);
    args.put(COLUMN_NAME, name);
    return db.update(TABLE_NAME, args, COLUMN_ID + "=" + ID, null) > 0;
}
}

activity_main:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.testovanisql.MainActivity">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/first"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"/>
<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingTop="50dp"
    android:layout_centerHorizontal="true"
    android:ems="15"
    android:id="@+id/id"/>
<EditText
    android:layout_width="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_height="wrap_content"
    android:ems="15"
    android:paddingTop="90dp"
    android:id="@+id/name"/>
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="save"
    android:layout_below="@+id/name"
    android:id="@+id/save"
    android:layout_centerHorizontal="true"
    android:onClick="addStudent"/>
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="load"
    android:layout_below="@+id/save"
    android:id="@+id/load"
    android:layout_centerHorizontal="true"
    android:onClick="loadStudents"/>

</RelativeLayout>

2 个答案:

答案 0 :(得分:0)

我阅读了您的代码。我认为升级方法有问题。尝试以下代码:

public class SQLitehelper extends SQLiteOpenHelper {

private static String DATABASE_NAME = "Demochat.db";
String TABLE_NAME = "chatdata";
String COL_1 = "ID";
String COL_2 = "TYPE";
String COL_3 = "DATE";
String COL_4 = "TIME";
String COL_5 = "MSG";



public SQLitehelper(MainActivity context) {
    super(context, DATABASE_NAME, null, 1);

}

@Override
public void onCreate(SQLiteDatabase db) {
     db.execSQL("create table " + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT,TYPE TEXT,DATE TEXT,TIME TEXT,MSG TEXT)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
    onCreate(db);
}
public  boolean insertData(String type, String date, String time, String msg){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues=new ContentValues();
    contentValues.put(COL_2,type);
    contentValues.put(COL_3,date);
    contentValues.put(COL_4,time);
    contentValues.put(COL_5,msg);
    long results=db.insert(TABLE_NAME,null,contentValues);
    if(results==-1){
        return false;
    }
    else {
        return true;
    }
}
public Cursor gtealldata(){
    SQLiteDatabase db=this.getWritableDatabase();
    Cursor res=db.rawQuery("select * from "+TABLE_NAME,null);
    return res;
}

}

答案 1 :(得分:0)

仅查看您的数据库创建,我发现了一些错误(主要是空格)。应该是:

    @Override
    public void onCreate(SQLiteDatabase db) {
        final String CREATE_TABLE =
             "CREATE TABLE " + TABLE_NAME + " ("
            + COLUMN_ID + " INTEGER PRIMARY KEY, " 
            + COLUMN_NAME + " TEXT);";
        db.execSQL(CREATE_TABLE);
    }

我建议您查看有关如何构建SQLite数据库的官方文档:data storage SQLite

通常最好逐步进行:在开始添加数据库之前,请确保首先正确创建了数据库。您可以使用简单而有用的工具,例如Stetho来检查数据库。

此外,您可以通过选择“仅显示选定的应用程序”来过滤您的logcat。 Screenshot