getSelectedItem()。toString()返回null值

时间:2016-07-29 08:10:55

标签: java android sql database

---------- ------------ UPDATE

我运行查询的部分是

public class DatabaseAccess extends MainActivity{
    private SQLiteOpenHelper openHelper;
    private SQLiteDatabase database;
    private static DatabaseAccess instance;


    private String courseValue = " course = " + getCourseValue();
    private String hungerValue = " hungerLevel = " + getHungerValue();
    private String prepValue = " preparationTime " + getPrepValue();
    private String cuisineValue = " cuisine = " + getCuisineValue();

    /**
     * Private constructor to avoid object creation from outside classes.
     *
     * @param context
     */
    private DatabaseAccess(Context context) {
        this.openHelper = new DatabaseOpenHelper(context);
    }

    /**
     * Return a singleton instance of DatabaseAccess.
     *
     * @param context the Context
     * @return the instance of DabaseAccess
     */
    public static DatabaseAccess getInstance(Context context) {
        if (instance == null) {
            instance = new DatabaseAccess(context);
        }
        return instance;
    }

    /**
     * Open the database connection.
     */
    public void open() {
        this.database = openHelper.getWritableDatabase();
    }

    /**
     * Close the database connection.
     */
    public void close() {
        if (database != null) {
            this.database.close();
        }
    }

    /**
     * Read all quotes from the database.
     *
     * @return a List of quotes
     */
    public List<String> getResults() {
        List<String> list = new ArrayList<>();
        Cursor cursor = database.rawQuery("SELECT foodName FROM foodDB where" + cuisineValue +" &" + hungerValue +" &"+ prepValue +" &"+ courseValue, null);
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            list.add(cursor.getString(0));
            cursor.moveToNext();
        }
        cursor.close();
        return list;
    }

}

我正在Android Studio中创建一个应用程序,我想获取微调器的值并将其分配给变量。但是,应用程序在测试期间始终崩溃并显示:

java.lang.RuntimeException: Unable to start activity ComponentInfo{
    com.example.rcadit.foodgenie/com.example.rcadit.foodgenie.resultActivity}:
    android.database.sqlite.SQLiteException: near "null":
    syntax error (code 1): , while compiling:
    SELECT foodName FROM foodDB where cuisine = null 
            & hungerLevel = null & preparationTime null & course = null

这是我的mainActivity.java

package com.example.rcadit.foodgenie;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;

import butterknife.ButterKnife;
import butterknife.InjectView;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

public void onItemSelected(AdapterView<?> parent, View view,
                           int pos, long id) {
    // An item was selected. You can retrieve the selected item using
    parent.getItemAtPosition(pos);
}

public void onNothingSelected(AdapterView<?> parent) {
    // Another interface callback
}

Toolbar toolbar;
@InjectView(R.id.salty)
SeekBar salty;
private String hungerValue;
private String cuisineValue;
private String prepValue;
private String courseValue;

public void go(View view) {
    Intent intent = new Intent(this, resultActivity.class);
    startActivity(intent);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.inject(this);
    initToolBar();
    saltySlider();
    spicySlider();
    sweetSlider();

    Spinner hunger_spinner = (Spinner) findViewById(R.id.hunger_spinner);
        // Create an ArrayAdapter using the string array and a default spinner layout
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
            R.array.hunger_level, android.R.layout.simple_spinner_item);
        // Specify the layout to use when the list of choices appears
         adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // Apply the adapter to the spinner
         hunger_spinner.setAdapter(adapter);

    Spinner cuisine_spinner = (Spinner) findViewById(R.id.cuisine_spinner);
        // Create an ArrayAdapter using the string array and a default spinner layout
         ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(this,
                 R.array.cuisine, android.R.layout.simple_spinner_item);
                // Specify the layout to use when the list of choices appears
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // Apply the adapter to the spinner
        cuisine_spinner.setAdapter(adapter2);

    Spinner prep_spinner = (Spinner) findViewById(R.id.time_spinner);
    // Create an ArrayAdapter using the string array and a default spinner layout
    ArrayAdapter<CharSequence> adapter3 = ArrayAdapter.createFromResource(this,
            R.array.preparation_time, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
    prep_spinner.setAdapter(adapter3);

    Spinner course_spinner = (Spinner) findViewById(R.id.course_spinner);
    // Create an ArrayAdapter using the string array and a default spinner layout
    ArrayAdapter<CharSequence> adapter4 = ArrayAdapter.createFromResource(this,
            R.array.course, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
    course_spinner.setAdapter(adapter4);

    //give data to variables
    hungerValue = hunger_spinner.getSelectedItem().toString();
    if (hungerValue.equals("Low") ) {
        hungerValue = "1";
    }
    if (hungerValue.equals("Medium") ) {
        hungerValue = "2";
    }
    if (hungerValue.equals("High") ) {
        hungerValue = "3";
    }
    cuisineValue = cuisine_spinner.getSelectedItem().toString();
    prepValue = prep_spinner.getSelectedItem().toString();
    if (prepValue.equals("Under 10 mins") ) {
        prepValue = "< 10";
    }
    if (prepValue.equals("No Preparation") ) {
        prepValue = " = 0";
    }
    if (prepValue.equals("Under 20 mins") ) {
        prepValue = "< 20";
    }
    if (prepValue.equals("Under 30 mins") ) {
        prepValue = "< 30";
    }
    if (prepValue.equals("Over 30 mins") ) {
        prepValue = "> 30";
    }
    courseValue = course_spinner.getSelectedItem().toString();
}

// (...) getters and setter for hungerValue, cuisineValue, prepValue, courseValue

private void saltySlider() {
    salty.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        int progressChanged = 0;

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            progressChanged = progress * 50;
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            if (progressChanged < 100 / 3) {
                TextView textView = (TextView) findViewById(R.id.howSalty);
                textView.setHint("Not Salty");

            }
            if (progressChanged > 100 / 3 & progressChanged < 2 * (100 / 3)) {
                TextView textView = (TextView) findViewById(R.id.howSalty);
                textView.setHint("Salty");
            }
            if (progressChanged > 2 * (100 / 3)) {
                TextView textView = (TextView) findViewById(R.id.howSalty);
                textView.setHint("Very Salty");
            }
        }
    });
}

private void sweetSlider() {
    SeekBar sweet = (SeekBar) findViewById(R.id.sweet);
    sweet.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        int progressChanged = 0;

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            progressChanged = progress * 50;
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            if (progressChanged < 100 / 3) {
                TextView textView = (TextView) findViewById(R.id.howSweet);
                textView.setHint("Not Sweet");

            }
            if (progressChanged > 100 / 3 & progressChanged < 2 * (100 / 3)) {
                TextView textView = (TextView) findViewById(R.id.howSweet);
                textView.setHint("Sweet");
            }
            if (progressChanged > 2 * (100 / 3)) {
                TextView textView = (TextView) findViewById(R.id.howSweet);
                textView.setHint("Very Sweet");
            }
        }
    });
}

private void spicySlider() {
    SeekBar spicy = (SeekBar) findViewById(R.id.spicy);
    spicy.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        int progressChanged = 0;

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            progressChanged = progress * 50;
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            if (progressChanged < 100 / 3) {
                TextView textView = (TextView) findViewById(R.id.howSpicy);
                textView.setHint("Not Spicy");

            }
            if (progressChanged > 100 / 3 & progressChanged < 2 * (100 / 3)) {
                TextView textView = (TextView) findViewById(R.id.howSpicy);
                textView.setHint("Spicy");
            }
            if (progressChanged > 2 * (100 / 3)) {
                TextView textView = (TextView) findViewById(R.id.howSpicy);
                textView.setHint("Very Spicy");
            }
        }
    });
}

public void initToolBar() {
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitle(R.string.app_name);
    setSupportActionBar(toolbar);
}
}

这是我的完整日志文件:

07/29 15:49:54: Launching app
Cold swapped changes.
$ adb shell am start -n "com.example.rcadit.foodgenie/com.example.rcadit.foodgenie.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 3218 on device Nexus_5_API_23_x86 [emulator-5554]
W/System: ClassLoader referenced unknown path: /data/app/com.example.rcadit.foodgenie-1/lib/x86
W/System: ClassLoader referenced unknown path: /data/app/com.example.rcadit.foodgenie-1/lib/x86
D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true

                  [ 07-29 07:49:57.700  3218: 3218 D/         ]
                  HostConnection::get() New Host Connection established 0xae8acd80, tid 3218
D/android.widget.GridLayout: horizontal constraints: x2-x0>=792, x2-x1<=308, x1-x0<=325 are inconsistent; permanently removing: x2-x1<=308. 

                             [ 07-29 07:49:57.763  3218: 3236 D/         ]
                             HostConnection::get() New Host Connection established 0xae8acff0, tid 3236
I/OpenGLRenderer: Initialized EGL, version 1.4
E/Surface: getSlotFromBufferLocked: unknown buffer: 0xaab2cbf0
D/OpenGLRenderer: endAllStagingAnimators on 0xa9f31400 (ListPopupWindow$DropDownListView) with handle 0xad1d5ae0
E/Surface: getSlotFromBufferLocked: unknown buffer: 0xaab2f350
D/OpenGLRenderer: endAllStagingAnimators on 0xa9ef0c00 (ListPopupWindow$DropDownListView) with handle 0xa207d4a0
E/Surface: getSlotFromBufferLocked: unknown buffer: 0xaab2cbf0
D/OpenGLRenderer: endAllStagingAnimators on 0xa9ef5900 (ListPopupWindow$DropDownListView) with handle 0xa207d1a0
E/Surface: getSlotFromBufferLocked: unknown buffer: 0xaab2f350
I/SQLiteAssetHelper: successfully opened database foodfile.sqlite
E/SQLiteLog: (1) near "null": syntax error
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.rcadit.foodgenie, PID: 3218
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.rcadit.foodgenie/com.example.rcadit.foodgenie.resultActivity}: android.database.sqlite.SQLiteException: near "null": syntax error (code 1): , while compiling: SELECT foodName FROM foodDB where cuisine = null & hungerLevel = null & preparationTime null & course = null
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                      at android.app.ActivityThread.-wrap11(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:148)
                      at android.app.ActivityThread.main(ActivityThread.java:5417)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                   Caused by: android.database.sqlite.SQLiteException: near "null": syntax error (code 1): , while compiling: SELECT foodName FROM foodDB where cuisine = null & hungerLevel = null & preparationTime null & course = null
                      at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                      at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
                      at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
                      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.rcadit.foodgenie.DatabaseAccess.getResults(DatabaseAccess.java:72)
                      at com.example.rcadit.foodgenie.resultActivity.onCreate(resultActivity.java:21)
                      at android.app.Activity.performCreate(Activity.java:6237)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
                      at android.app.ActivityThread.-wrap11(ActivityThread.java) 
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
                      at android.os.Handler.dispatchMessage(Handler.java:102) 
                      at android.os.Looper.loop(Looper.java:148) 
                      at android.app.ActivityThread.main(ActivityThread.java:5417) 
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
I/Process: Sending signal. PID: 3218 SIG: 9
Application terminated.

我花了最近3天试图修复它,而这个论坛上的其他帖子对我没用。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

您的SQL请求是错误的。我认为应该是:

SELECT foodName FROM foodDB where cuisine is null and hungerLevel is null and preparationTime is null and course is null

答案 1 :(得分:0)

应该是IS NULL,而不是= NULLAND而不是&

基本SQL语法。