【问题标题】:Android SQLite Order安卓 SQLite 订单
【发布时间】:2015-09-22 12:17:39
【问题描述】:

我正在尝试对基本数据库进行排序。 我可以将问题隔离到一个部分:(db.query -> order -> score + "ASC")。 当我在“订单”区域完成的情况下执行代码时,AVD 和设备总是会崩溃。 null 有效...但我想排序。 我已经尝试以我能想到的各种方式修改此代码..我做错了什么?希望能帮到你,谢谢

public class MainActivity extends ListActivity {

    Button insertButton;
    EditText name;
    EditText score;

    CustomOpenHelper myOpenHelper;

    private final static String DATABASE_NAME = "SQLiteDataBasePractical.db";
    private final static int VERSION_NUMBER = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        insertButton = (Button) findViewById(R.id.buttonInsert);
        name = (EditText) findViewById(R.id.editTextName);
        score = (EditText) findViewById(R.id.editTextScore);

        myOpenHelper = new CustomOpenHelper(this, DATABASE_NAME, null, VERSION_NUMBER);

        insertButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                String inputName = name.getText().toString();
                String inputScore = score.getText().toString();

                SQLiteDatabase db = myOpenHelper.getWritableDatabase();

                // Wrap the database data
                ContentValues values = new ContentValues();
                values.put("name", inputName);
                int intScore = Integer.parseInt(inputScore); //this line converts string to integer
                values.put("score", intScore);

                db.insert(CustomOpenHelper.TABLE_NAME, null, values);

                displayDataInTable();
            }
        });

    }

    void displayDataInTable() {
        List<String> values = queryTable();

        if (values != null) {
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, values);
            setListAdapter(adapter);
        }

    }

    List<String> queryTable() {
        List<String> player = new ArrayList<String>();

        SQLiteDatabase db = myOpenHelper.getReadableDatabase();
        Cursor cursor = db.query(CustomOpenHelper.TABLE_NAME, new String[]{"_id, name, score"}, null, null, null, null, score + " ASC");

        while (cursor.moveToNext()) {
            int id = cursor.getInt(cursor.getColumnIndex("_id"));
            String name = cursor.getString(cursor.getColumnIndex("name"));
            int score = cursor.getInt(cursor.getColumnIndex("score"));
            player.add(id + " --> the player " + name + " has got a score of " + score + "s");
        }

        return player;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);

根据建议,请参阅 LogCat 09-23 07:59:01.565 4399-4399/? I/SELinux﹕ Function: selinux_android_load_priority [0], There is no sepolicy file. 09-23 07:59:01.605 4399-4399/? I/SELinux﹕ Function: selinux_android_load_priority , spota verifySig and checkHash pass. priority version is VE=SEPF_GT-I9505_4.4.2_0046 09-23 07:59:01.605 4399-4399/? I/SELinux﹕ selinux_android_seapp_context_reload: seapp_contexts file is loaded from /data/security/spota/seapp_contexts 09-23 07:59:01.605 4399-4399/? E/dalvikvm﹕ >>>>> Normal User 09-23 07:59:01.605 4399-4399/? E/dalvikvm﹕ >>>>> com.example.eagle.sqlpracticalorder [ userId:0 | appId:10283 ] 09-23 07:59:01.605 4399-4399/? D/dalvikvm﹕ Late-enabling CheckJNI 09-23 07:59:01.715 4399-4399/com.example.eagle.sqlpracticalorder W/ApplicationPackageManager﹕ getCSCPackageItemText() 09-23 07:59:01.715 4399-4399/com.example.eagle.sqlpracticalorder I/PersonaManager﹕ getPersonaService() name persona_policy 09-23 07:59:01.795 4399-4399/com.example.eagle.sqlpracticalorder D/AbsListView﹕ Get MotionRecognitionManager 09-23 07:59:01.805 4399-4399/com.example.eagle.sqlpracticalorder D/AbsListView﹕ onVisibilityChanged() is called, visibility : 4 09-23 07:59:01.805 4399-4399/com.example.eagle.sqlpracticalorder D/AbsListView﹕ unregisterIRListener() is called 09-23 07:59:01.825 4399-4399/com.example.eagle.sqlpracticalorder D/AbsListView﹕ onVisibilityChanged() is called, visibility : 0 09-23 07:59:01.825 4399-4399/com.example.eagle.sqlpracticalorder D/AbsListView﹕ unregisterIRListener() is called 09-23 07:59:01.845 4399-4399/com.example.eagle.sqlpracticalorder D/AbsListView﹕ unregisterIRListener() is called 09-23 07:59:01.865 4399-4399/com.example.eagle.sqlpracticalorder I/Adreno-EGL﹕ <qeglDrvAPI_eglInitialize:381>: EGL 1.4 QUALCOMM build: (CL3869936) OpenGL ES Shader Compiler Version: 17.01.11.SPL Build Date: 01/17/14 Fri Local Branch: Remote Branch: Local Patches: Reconstruct Branch: 09-23 07:59:01.925 4399-4399/com.example.eagle.sqlpracticalorder D/OpenGLRenderer﹕ Enabling debug mode 0 09-23 07:59:01.925 4399-4399/com.example.eagle.sqlpracticalorder D/AbsListView﹕ unregisterIRListener() is called 09-23 07:59:24.797 4399-4399/com.example.eagle.sqlpracticalorder D/AbsListView﹕ unregisterIRListener() is called 09-23 07:59:24.928 4399-4399/com.example.eagle.sqlpracticalorder D/AbsListView﹕ unregisterIRListener() is called 09-23 07:59:25.308 4399-4399/com.example.eagle.sqlpracticalorder D/AbsListView﹕ unregisterIRListener() is called 09-23 07:59:28.071 4399-4399/com.example.eagle.sqlpracticalorder D/AbsListView﹕ unregisterIRListener() is called 09-23 07:59:30.443 4399-4399/com.example.eagle.sqlpracticalorder D/AndroidRuntime﹕ Shutting down VM 09-23 07:59:30.443 4399-4399/com.example.eagle.sqlpracticalorder W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41833da0) 09-23 07:59:30.453 4399-4399/com.example.eagle.sqlpracticalorder E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: com.example.eagle.sqlpracticalorder, PID: 4399 android.database.sqlite.SQLiteException: unrecognized token: "{" (code 1): , while compiling: SELECT DISTINCT _id, name, score FROM players ORDER BY android.widget.EditText{42a92ef8 VFED..CL .F...... 0,261-1080,378 #7f0c004f app:id/editTextScore}asc at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method) at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1121) at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:694) 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:1436) at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1283) at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1195) at com.example.eagle.sqlpracticalorder.MainActivity.queryTable(MainActivity.java:84) at com.example.eagle.sqlpracticalorder.MainActivity.displayDataInTable(MainActivity.java:69) at com.example.eagle.sqlpracticalorder.MainActivity$1.onClick(MainActivity.java:60) at android.view.View.performClick(View.java:4633) at android.view.View$PerformClick.run(View.java:19330) at android.os.Handler.handleCallback(Handler.java:733) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:157) at android.app.ActivityThread.main(ActivityThread.java:5356) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081) at dalvik.system.NativeStart.main(Native Method)

【问题讨论】:

  • 什么是崩溃?为我们提供 logcat !
  • 请看上面,我已经添加了整个LogCat。请告知是否只添加问题部分以供我将来参考?最好的问候,亚当

标签: java android sqlite android-studio


【解决方案1】:

我想,你忘记了“ASC”附近的空格:

Cursor cursor = db.query(CustomOpenHelper.TABLE_NAME, new String[]{"_id, name, score"}, null, null, null, null, score + " ASC");

【讨论】:

  • 谢谢你们的建议。我相信你是对的,我已经相应地编辑了代码。不幸的是,还有另一个问题。我敢打赌这与我将查询放在一起的方式有关吗?问候,亚当
【解决方案2】:

您需要在 asc 之前添加一个空格,否则它会将其视为

"order by 15asc" //if 15 is score value SQL 引擎可能无法理解

 Cursor cursor = db.query(CustomOpenHelper.TABLE_NAME, new String[]{"_id, name, score"}, null, null, null, null, score + " ASC");

【讨论】:

    【解决方案3】:

    已排序 - 感谢大家的帮助,从同事那里得到了一些额外的帮助:

    String[] dbArg = {"_id", "name", "score"}; 光标 cursor = db.query(CustomOpenHelper.TABLE_NAME, dbArg , null, null, null, null, "score DESC", null);

    【讨论】:

      【解决方案4】:

      通过查看我看到的堆栈跟踪,您在查询中使用了score。但是score 是上面声明的TextView。你可以在这里使用score.getText().toString() 之类的东西:

      Cursor cursor = db.query(CustomOpenHelper.TABLE_NAME, new String[]{"_id, name, score"}, null, null, null, null, score.getText().toString() + " ASC");
      

      【讨论】:

        【解决方案5】:

        看到你的logcat,答案就在里面:

        android.database.sqlite.SQLiteException: unrecognized token: "{" (code 1): , while compiling: SELECT DISTINCT _id, name, score FROM players ORDER BY android.widget.EditText{42a92ef8 VFED..CL .F...... 0,261-1080,378 #7f0c004f app:id/editTextScore}asc
        

        所以有两个问题:

        1. 正如其他答案中所说,您错过了“score”和“asc”之间的空格
        2. score 似乎是一个变量。当我们在 logcat 中看到一个对象的字符串表示时,我们可以确定 score 实际上是一个 EditText 而不是一个字符串。

        处理第二点的两种解决方案:

        • 如果您希望请求中的值“score”(作为字符串),请使用硬编码(或任何适合您项目的更好方式)
        • 如果您想使用用户在名为score 的EditText 中设置的值,您应该改用它:score.getText()

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-06-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-01-12
          相关资源
          最近更新 更多