java – 使用sqlite数据库中的数据填充微调器 – 应用程序崩溃

我正在尝试将数据(表中的特定列)加载到微调器中.
我创建了一个DatabaseHelper类,我在其中定义了数据库/表,并选择了微调器的数据.
我的类Allgemein是我保存微调器数据的类.
我创建了一个Unterkunft类,我实现了一个微调器.当我点击这个微调器时,应该显示Allgemein类的数据.

每次我在Allgemein中保存数据然后尝试打开Unterkunft Activity我的应用程序崩溃.

我添加了DatabaseHelper和Unterkunft以及Logcat的代码.

我希望有人可以帮助我!
谢谢

类DatabaseHelper

package com.group6.TakeOff;


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

import java.util.ArrayList;
import java.util.List;

/**
 * Created by STzavelas on 28.06.17.
 */

public class DatabaseHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "TakeOff.db";

    //Table Names
    public static final String TABLE_PROJEKT = "create_project";
    public static final String TABLE_UNTERKUNFT = "unterkunft";
    public static final String TABLE_AUTO = "auto";
    public static final String TABLE_FLUGZEUG = "flugzeug";
    public static final String TABLE_TAXI = "taxi";
    public static final String TABLE_BAHN  = "bahn";


    //Common column names
    public static final String KEY_ID = "ID";
    public static final String KEY_PROJECT = "PROJEKT";

    //create project column names
    public static final String KEY_DATE_FROM= "DATE_FROM";
    public static final String KEY_DATE_TO= "DATE_TO";
    public static final String KEY_NAME = "NACHNAME";
    public static final String KEY_VORNAME = "VORNAME";
    public static final String KEY_KOSTENST = "KOSTENSTELLE";

    //Expenses column names
    public static final String KEY_ENTFERNUNG= "ENTFERNUNG";
    public static final String KEY_PRICE= "PRICE";
    public static final String KEY_MWST= "MWST";
    public static final String KEY_RECHNUNG_IMG= "RECHNUNG_IMG";

    //Übersicht column names

    //TABLE CREATE STATEMENTS
    private static final String CREATE_TABLE_PROJEKT = "create table " + TABLE_PROJEKT + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
            "PROJEKT TEXT, " +
            "DATE_FROM TEXT, " +
            "DATE_TO TEXT, " +
            "NACHNAME TEXT, " +
            "VORNAME TEXT, " +
            "KOSTENSTELLE TEXT)";

    private static final String CREATE_TABLE_UNTERKUNFT = "create table " + TABLE_UNTERKUNFT +
            "(ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
            "PROJEKT TEXT, " +
            "ENTFERNUNG INT, " +
            "PRICE INT, " +
            "MWST INT)";



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

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_PROJEKT);
        db.execSQL(CREATE_TABLE_UNTERKUNFT);
        //db.execSQL(CREATE_TABLE_AUTO);
        //db.execSQL(CREATE_TABLE_FLUGZEUG);
        //db.execSQL(CREATE_TABLE_BAHN);
        //db.execSQL(CREATE_TABLE_TAXI);


    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int i, int i1) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_PROJEKT);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_UNTERKUNFT);
        onCreate(db);
    }


    //+++++++++++++CREATE A PROJECT++++++++++++//

    public boolean createProject(String project, String date_from, String date_to, String name, String vorname, String kostenstelle){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(KEY_PROJECT, project);
        contentValues.put(KEY_DATE_FROM, date_from);
        contentValues.put(KEY_DATE_TO, date_to);
        contentValues.put(KEY_NAME, name);
        contentValues.put(KEY_VORNAME, vorname);
        contentValues.put(KEY_KOSTENST, kostenstelle);
        long result = db.insert(TABLE_PROJEKT,null,contentValues);
        if(result == -1)
            return false;
        else
            return true;

    }


    //+++++++++++++CREATE A UNTERKUNFT++++++++++++//
    public boolean createUnterkunft(String project, String date_from, String date_to, String name, String vorname, String kostenstelle){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(KEY_PROJECT, project);
        contentValues.put(KEY_DATE_FROM, date_from);
        contentValues.put(KEY_DATE_TO, date_to);
        contentValues.put(KEY_NAME, name);
        contentValues.put(KEY_VORNAME, vorname);
        contentValues.put(KEY_KOSTENST, kostenstelle);
        long result = db.insert(TABLE_PROJEKT,null,contentValues);
        if(result == -1)
            return false;
        else
            return true;

    }


    //Getting values from spinner (Drop-Down)
    public List<String> getAllProjects(){
        List<String> projects = new ArrayList<String>();

        String selectQuery = "SELECT " + KEY_PROJECT + "FROM " + TABLE_PROJEKT;

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery,null);
        if (cursor.moveToFirst()) {
            do {
                projects.add(cursor.getString(1));
            } while (cursor.moveToNext());
        }

        // closing connection
        cursor.close();
        db.close();

        // returning lables
        return projects;
    }

}

Unterkunft类

package com.group6.TakeOff;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.ArrayAdapter;;
import java.util.List;

/**
 * Created by STzavelas on 24.06.17.
 */

public class activity_unterkunft extends AppCompatActivity {

    DatabaseHelper myDb;
    Button btn_save;
    Spinner ChooseProject;
    EditText Entfernung,Price,MWST;

    private BottomNavigationView bottomNavigationView;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_unterkunft);
        myDb = new DatabaseHelper(this);

        ChooseProject = (Spinner) findViewById(R.id.ChooseProject);
        Entfernung = (EditText) findViewById(R.id.Entfernung);
        Price = (EditText) findViewById(R.id.Preis);
        MWST = (EditText) findViewById(R.id.MwSt);
        btn_save=(Button) findViewById(R.id.btn_save);
        //ChooseProject.setOnItemSelectedListener(this);
        loadSpinnerData();
        //SaveData();


        //++++++++++++BOTTOM NAVIGATION BAR++++++++++++//
        bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavigationView);

        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener(){
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item){
                if (item.getItemId()==R.id.menu_start){
                    startActivity(new Intent(activity_unterkunft.this, MainActivity.class));
                } else if(item.getItemId()==R.id.menu_allgemein){
                    startActivity(new Intent(activity_unterkunft.this, activity_allgemein.class));
                } else if(item.getItemId()==R.id.menu_transport){
                    startActivity(new Intent(activity_unterkunft.this, activity_transport.class));
                } else if(item.getItemId()==R.id.menu_rechnung){
                    startActivity(new Intent(activity_unterkunft.this, activity_rechnung.class));
                } else if(item.getItemId()==R.id.menu_unterkunft){
                    startActivity(new Intent(activity_unterkunft.this, activity_unterkunft.class));
                }
                return true;
            }
        });

        bottomNavigationView.setSelectedItemId(R.id.menu_unterkunft);
    }

    /**
     * Function to load the spinner data from SQLite database
     * */
    private void loadSpinnerData() {
        // database handler
        DatabaseHelper db = new DatabaseHelper (getApplicationContext());

        // Spinner Drop down elements
        List<String> projects = db.getAllProjects();

        // Creating adapter for spinner
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, projects);

        // Drop down layout style - list view with radio button
        dataAdapter
                .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        // attaching data adapter to spinner
        ChooseProject.setAdapter(dataAdapter);
    }

}

来自logcat的运行时异常:

8-04 15:09:28.193 10721-10721/com.group6.travlhoe E/AndroidRuntime: FATAL EXCEPTION: main
                                                                     Process: com.group6.travlhoe, PID: 10721
                                                                     java.lang.RuntimeException: Unable to start activity ComponentInfo{com.group6.travlhoe/com.group6.TakeOff.activity_unterkunft}: java.lang.IllegalStateException: Couldn't read row 0, col 1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.
                                                                         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
                                                                         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                                                                         at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                                                                         at android.os.Handler.dispatchMessage(Handler.java:105)
                                                                         at android.os.Looper.loop(Looper.java:164)
                                                                         at android.app.ActivityThread.main(ActivityThread.java:6540)
                                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                                         at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
                                                                      Caused by: java.lang.IllegalStateException: Couldn't read row 0, col 1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.
                                                                         at android.database.CursorWindow.nativeGetString(Native Method)
                                                                         at android.database.CursorWindow.getString(CursorWindow.java:438)
                                                                         at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
                                                                         at com.group6.TakeOff.DatabaseHelper.getAllProjects(DatabaseHelper.java:141)
                                                                         at com.group6.TakeOff.activity_unterkunft.loadSpinnerData(activity_unterkunft.java:77)
                                                                         at com.group6.TakeOff.activity_unterkunft.onCreate(activity_unterkunft.java:41)
                                                                         at android.app.Activity.performCreate(Activity.java:6980)
                                                                         at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
                                                                         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
                                                                         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) 
                                                                         at android.app.ActivityThread.-wrap11(Unknown Source:0) 
                                                                         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593) 
                                                                         at android.os.Handler.dispatchMessage(Handler.java:105) 
                                                                         at android.os.Looper.loop(Looper.java:164) 
                                                                         at android.app.ActivityThread.main(ActivityThread.java:6540) 
                                                                         at java.lang.reflect.Method.invoke(Native Method) 
                                                                         at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 
08-04 15:09:29.375 1518-1531/? E/memtrack: Couldn't load memtrack module
08-04 15:09:30.634 1518-1575/? E/InputDispatcher: channel '160c8 com.group6.travlhoe/com.group6.TakeOff.activity_unterkunft (server)' ~ Channel is unrecoverably broken and will be disposed!
08-04 15:09:30.634 1518-1575/? E/InputDispatcher: channel '8a33e37 com.group6.travlhoe/com.group6.TakeOff.activity_allgemein (server)' ~ Channel is unrecoverably broken and will be disposed!
08-04 15:09:30.636 1518-1575/? E/InputDispatcher: channel '32f6f4d com.group6.travlhoe/com.group6.TakeOff.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
08-04 15:09:30.703 1349-1368/? E/SurfaceFlinger: Failed to find layer (com.group6.travlhoe/com.group6.TakeOff.activity_allgemein#0) in layer parent (no-parent).
08-04 15:09:30.732 11098-11105/? E/zygote: Failed sending reply to debugger: Broken pipe
08-04 15:09:30.753 1518-2450/? E/ActivityManager: applyOptionsLocked: Unknown animationType=0
08-04 15:09:31.387 11098-11098/? E/CursorWindow: Failed to read row 0, column 1 from a CursorWindow which has 1 rows, 1 columns.
08-04 15:09:31.389 11098-11098/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                   Process: com.group6.travlhoe, PID: 11098
                                                   java.lang.RuntimeException: Unable to start activity ComponentInfo{com.group6.travlhoe/com.group6.TakeOff.activity_unterkunft}: java.lang.IllegalStateException: Couldn't read row 0, col 1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                                                       at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                                                       at android.os.Handler.dispatchMessage(Handler.java:105)
                                                       at android.os.Looper.loop(Looper.java:164)
                                                       at android.app.ActivityThread.main(ActivityThread.java:6540)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
                                                    Caused by: java.lang.IllegalStateException: Couldn't read row 0, col 1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.
                                                       at android.database.CursorWindow.nativeGetString(Native Method)
                                                       at android.database.CursorWindow.getString(CursorWindow.java:438)
                                                       at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
                                                       at com.group6.TakeOff.DatabaseHelper.getAllProjects(DatabaseHelper.java:141)
                                                       at com.group6.TakeOff.activity_unterkunft.loadSpinnerData(activity_unterkunft.java:77)
                                                       at com.group6.TakeOff.activity_unterkunft.onCreate(activity_unterkunft.java:41)
                                                       at android.app.Activity.performCreate(Activity.java:6980)
                                                       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) 
                                                       at android.app.ActivityThread.-wrap11(Unknown Source:0) 
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593) 
                                                       at android.os.Handler.dispatchMessage(Handler.java:105) 
                                                       at android.os.Looper.loop(Looper.java:164) 
                                                       at android.app.ActivityThread.main(ActivityThread.java:6540) 
                                                       at java.lang.reflect.Method.invoke(Native Method) 
                                                       at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 
08-04 15:09:31.563 1518-1606/? E/TaskPersister: File error accessing recents directory (directory doesn't exist?).
08-04 15:09:32.694 1518-1528/? E/ActivityManager: Found activity ActivityRecord{1e06b4f u0 com.group6.travlhoe/com.group6.TakeOff.activity_unterkunft t-1 f} in proc activity list using null instead of expected ProcessRecord{9c4d79f 11098:com.group6.travlhoe/u0a86}
08-04 15:09:33.051 1415-1496/? E/AudioFlinger: not enough memory for AudioTrack size=131296
08-04 15:09:33.052 1415-1496/? E/AudioFlinger: createRecordTrack_l() initCheck failed -12; no control block?
08-04 15:09:33.054 2179-10736/? E/AudioRecord: AudioFlinger could not create record track, status: -12
08-04 15:09:33.093 2179-10736/? E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -12.
08-04 15:09:33.093 2179-10736/? E/android.media.AudioRecord: Error code -20 when initializing native AudioRecord object.
最佳答案
在选择查询字符串中,在FROM之前需要一个空格:

String selectQuery = "SELECT " + KEY_PROJECT + " FROM " + TABLE_PROJEKT;
                                                ^
                                               HERE

查看logcat中的SQLiteException:

Caused by: SQLiteException: no such column: PROJEKTFROM (code 1): 

进行上述更改后崩溃:

在您的select语句中,您选择的是一列:

String selectQuery = "SELECT " + KEY_PROJECT + "  FROM " + TABLE_PROJEKT;

但是在从光标访问数据时,您正在执行以下操作:

projects.add(cursor.getString(1));

现在游标索引是从零开始的,你没有第1列只有0.

转载注明原文:java – 使用sqlite数据库中的数据填充微调器 – 应用程序崩溃 - 代码日志