Java – populating the spinner with data from the SQLite database – application crash

I'm trying to load data (specific columns in the table) into the spinner

Every time I save data in allgemein and try to open Unterkunft activity, my application crashes

I added code for databasehelper, Unterkunft and logcat

I hope someone can help me! thank you

Class 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," +
            "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,contentValues);
        if(result == -1)
            return false;
        else
            return true;

    }


    //+++++++++++++CREATE A UNTERKUNFT++++++++++++//
    public boolean createUnterkunft(String project,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 class

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);
    }

}

Runtime exception from 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.

Solution

In the selection query string, a space is required before from:

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

View sqliteexception in logcat:

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

Crash after making the above changes:

In your select statement, you select a column:

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

However, when accessing data from the cursor, you are doing the following:

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

Now the cursor index starts from zero. You have no column 1, only 0

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>