SQLite:找不到ROWID

时间:2017-06-20 02:37:48

标签: java android xml database sqlite

每当我查询数据以插入另一个活动时,我都会收到错误。

主要问题是我没有在堆栈跟踪中获得输出并成为新的程序员,我无法弄清楚发生了什么。

我是SQLite的新手,并不完全了解查询的工作原理,所以任何帮助都会受到赞赏。

如果我想点击Listview布局activity_main上的某个项目,就会出现此问题。

我已将onItemClickListener设置为将活动更改为edit_data布局,并且只要列表中的项目为,就会使用SQLite数据库表中的相应数据填充EditText字段点击。

但每当我点击某个项目时,它就会举起一个祝词:“没有与该名称相关联的ID”。

这个Toast消息由我自己内置到应用程序中,所以我知道什么是这个消息,但我不知道为什么。

这是我的代码:

MainActivity.java

package com.TheAbstractLightbulb.cohen.not_at_homes_app;


import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.content.Intent;
import android.view.View;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;


public class MainActivity extends Activity {
    private static final String TAG = "MainActivity";
    DBHelper dbHelper;

    public MainActivity() {
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        requestWindowFeature(Window.FEATURE_ACTION_BAR);
        setContentView(R.layout.activity_main);
        dbHelper = new DBHelper(this);


        populateListView();
    }

    public void toInputScreen(View view) {
        Button addButton = (Button) findViewById(R.id.addButton);
        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent1 = new Intent(MainActivity.this, InputPage.class);
                startActivity(intent1);
            }
        });
    }

    private void populateListView() {
        Log.d(TAG, "populateListView: Displaying data in list view.");
        final Cursor data = dbHelper.getData();
        ArrayList<String> listData = new ArrayList<>();
        while (data.moveToNext()) {
            listData.add(data.getString(2));
        }
        ListView listview = (ListView) findViewById(R.id.MainListView);
        final ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData);
        listview.setAdapter(adapter);

        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String map = adapterView.getItemAtPosition(i).toString();
                String name = adapterView.getItemAtPosition(i).toString();
                String date = adapterView.getItemAtPosition(i).toString();
                String notAtHomes = adapterView.getItemAtPosition(i).toString();
                Log.d(TAG, "onItemClick: You Clicked on " + notAtHomes);

                Cursor data = dbHelper.getItemID(map, name, date, notAtHomes);
                int itemID = -1;
                while (data.moveToNext()) {
                    itemID = data.getInt(0);
                }
                if (itemID > -1) {
                    Log.d(TAG, "onItemClick: The ID is: " + itemID);
                    Intent editDataIntent = new Intent(MainActivity.this, EditData.class);
                    editDataIntent.putExtra("id", itemID);
                    editDataIntent.putExtra("map", map);
                    editDataIntent.putExtra("name", name);
                    editDataIntent.putExtra("date", date);
                    editDataIntent.putExtra("notAtHomes", notAtHomes);
                    startActivity(editDataIntent);
                } else {
                    Toast.makeText(getBaseContext(), "No ID associated with that name", Toast.LENGTH_LONG).show();
                }


            }
        });
    }
}

EditData.java

package com.TheAbstractLightbulb.cohen.not_at_homes_app;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


/**
 * Created by cohen on 2/06/2017.
 */

public class EditData extends Activity {
    private static final String TAG = "EditData";

    DBHelper dbhelper;

    private int selectedID;
    private String selectedMap;
    private String selectedName;
    private String selectedDate;
    private String selectedNotAtHomes;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit_data);
        final Button saveButton2 = (Button)findViewById(R.id.saveButton2);
        Button deleteButton1 = (Button)findViewById(R.id.deleteButton1);
        final EditText textNotAtHomes2 = (EditText)findViewById(R.id.textNotAtHomes2);
        final EditText mapNoDisplay2 = (EditText)findViewById(R.id.mapNoDisplay2);
        final EditText dateDisplay2 = (EditText)findViewById(R.id.dateDisplay2);
        final EditText ListName2 = (EditText)findViewById(R.id.ListName2);
        DBHelper DB = new DBHelper(this);

        Intent receivedIntent = getIntent();
        // ID
        selectedID = receivedIntent.getIntExtra("id",-1);
        // Map no
        selectedMap = receivedIntent.getStringExtra("map");
        // Name
        selectedName = receivedIntent.getStringExtra("name");
        // Date
        selectedDate = receivedIntent.getStringExtra("date");
        // Not at homes note file
        selectedNotAtHomes = receivedIntent.getStringExtra("notAtHomes");

        ListName2.setText(selectedName);
        mapNoDisplay2.setText(selectedMap);
        dateDisplay2.setText(selectedDate);
        textNotAtHomes2.setText(selectedNotAtHomes);

        saveButton2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String item1 = ListName2.getText().toString();
                String item2 = mapNoDisplay2.getText().toString();
                String item3 = dateDisplay2.getText().toString();
                String item4 = textNotAtHomes2.getText().toString();
                if (!item1.equals("")){
                    if (!item2.equals("")){
                        if (!item3.equals("")) {
                            if (!item4.equals("")) {
                                dbhelper.updateData(selectedID, item2, selectedMap, item1, selectedName, item3, selectedDate, item4, selectedNotAtHomes);
                            } else {
                                new AlertDialog.Builder(getBaseContext())
                                        .setTitle("emptyBoxes")
                                        .setMessage("Some boxes have been left empty, /n" +
                                                "are you sure you are done?")
                                        .setNegativeButton("Cancel", null)
                                        .setPositiveButton("Save", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {

                                            }
                                        }).create().show();
                            }

                        }

                        }
                    }

                }
            });

        deleteButton1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dbhelper.deleteData(selectedID, selectedMap, selectedName, selectedDate, selectedNotAtHomes);
                Intent intent = new Intent(EditData.this, MainActivity.class);
                startActivity(intent);
                Toast.makeText(getBaseContext(), "Note Deleted successfully", Toast.LENGTH_LONG).show();
            }
        });
        }

        private void toSendNote(View view){
            Button sendButton = (Button)findViewById(R.id.sendButton);
            sendButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent1 = new Intent(EditData.this, SendRecord.class);
                    intent1.putExtra("Note", selectedNotAtHomes);
                    startActivity(intent1);
                }
            });
        }

    }

DBHelper.java

package com.TheAbstractLightbulb.cohen.not_at_homes_app;

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

/**
 * Created by cohen on 31/05/2017.
 */

public class DBHelper extends SQLiteOpenHelper {
    public static final String DATABASE_NAME = "App_database.db";
    public static final String TABLE_NAME = "App_date_table";
    public static final String MAP_NO = "Map_no";
    public static final String LOCATION = "Location";
    public static final String DATE = "Date";
    public static final String NOTATHOMES = "Not_at_homes";
    public static final String ID = "ID";
    public static final String TAG = "DBHelper";


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

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
       String createTable = "CREATE TABLE " + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, " + MAP_NO + " INTEGER, " + LOCATION + " TEXT, " + DATE + " INTEGER, " + NOTATHOMES + " TEXT)";
        db.execSQL(createTable);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);

    }

    public boolean insertData(String Map_no, String Location, String Date, String Not_at_homes) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(MAP_NO, Map_no);
        contentValues.put(LOCATION, Location);
        contentValues.put(DATE, Date);
        contentValues.put(NOTATHOMES, Not_at_homes);

        Log.d(TAG, "addData: Adding " + Location + " to " + TABLE_NAME);

        long result = db.insert(TABLE_NAME, null, contentValues);
        if (result == -1) {
            return false;
        } else {
            return true;
        }


    }

    public Cursor getData() {
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "SELECT * FROM " + TABLE_NAME;
        Cursor data = db.rawQuery(query, null);
        return data;
    }

    public Cursor getItemID(String map, String location, String date, String notAtHomes) {
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "SELECT " + ID + " FROM " + TABLE_NAME +
                " WHERE " + MAP_NO + " = '" + map + "' AND " + LOCATION + " = '" + location +
                "' AND " + DATE + " = '" + date + "' AND "
                + NOTATHOMES + " = '" + notAtHomes + "'";
        Cursor data = db.rawQuery(query, null);
        return data;
    }

    public void updateData(int id,String newMapNo, String oldMapNo, String newLocation, String oldLocation, String newDate, String oldDate, String newNotAtHomes, String oldNotAtHomes){
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "UPDATE " + TABLE_NAME + " SET " + MAP_NO +
                " = '" + newMapNo + " WHERE " + ID + " = '" + id + "'" +
                " AND " + MAP_NO + " = '" + oldMapNo + "'"+ LOCATION +
                " = '" + newLocation + " WHERE " + ID + " = '" + id + "'" +
                " AND " + LOCATION + " = '" + oldLocation + "'"+ DATE +
                " = '" + newDate + " WHERE " + ID + " = '" + id + "'" +
                " AND " + DATE + " = '" + oldDate + "'"+ NOTATHOMES +
                " = '" + newNotAtHomes + " WHERE " + ID + " = '" + id + "'" +
                " AND " + NOTATHOMES + " = '" + oldNotAtHomes + "'";
        Log.d(TAG, "updating: query: " + query);
        Log.d(TAG, "updating: Setting map number, Location, Date and Not at homes to new values: Map number: " +
                newMapNo + " Location: " + newLocation + " Date: " +
                newDate + " Not at homes: " + newNotAtHomes);
        db.execSQL(query);
    }

    public void deleteData(int id, String mapNo, String location, String date, String notAtHomes){
        SQLiteDatabase database = this.getWritableDatabase();
        String query = "DELETE FROM " + TABLE_NAME + " WHERE "
                + ID + " + '" + id + "'" + " AND " + MAP_NO + " = '" + mapNo + "'" +
                LOCATION + " = '" + location + "'" + DATE + " = '" + date + "'" + NOTATHOMES +
                " = '" + notAtHomes + "'";
        Log.d(TAG, "deleting: query: " + query);
        Log.d(TAG, "deleting: Deleting note with values: Map number: " + mapNo + " Location: " + location + " Created on: " + date + " With notes: " + notAtHomes + ".");
        database.execSQL(query);
    }
}

MainActivity XML

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.TheAbstractLightbulb.cohen.not_at_homes_app.MainActivity"
    android:background="@color/BackgroundGrey">


    <Button
        android:id="@+id/addButton"
        android:layout_width="351dp"
        android:layout_height="61dp"
        android:layout_marginBottom="16dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="449dp"
        android:onClick="toInputScreen"
        android:background="@drawable/buttons"
        android:text="@string/ButtonAddButton"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.733"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0" />

    <ListView
        android:id="@+id/MainListView"
        android:layout_width="336dp"
        android:layout_height="521dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="8dp"
        android:divider="@color/blackText"
        android:headerDividersEnabled="false"
        android:visibility="visible"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.6"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0" />

</android.support.constraint.ConstraintLayout>

EditData XML

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".EditData"
    android:background="@color/BackgroundGrey">

    <Button
        android:id="@+id/saveButton2"
        android:layout_width="110dp"
        android:layout_height="66dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:background="@drawable/buttons"
        android:onClick="toSaveField"
        android:text="@string/saveButton"
        android:textSize="16sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.005"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0" />

    <Button
        android:id="@+id/deleteButton1"
        android:layout_width="110dp"
        android:layout_height="66dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:background="@drawable/buttons"
        android:onClick="toDeleteNote"
        android:text="@string/ButtonDeleteButton"
        android:textSize="16sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0" />

    <Button
        android:id="@+id/sendButton"
        android:layout_width="110dp"
        android:layout_height="66dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:background="@drawable/buttons"
        android:onClick="toSendNote"
        android:text="@string/sendButtonText"
        android:textSize="16sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0" />


    <EditText
        android:id="@+id/textNotAtHomes2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:ems="10"
        android:background="@color/hintTextColour"
        android:inputType="textMultiLine"
        android:hint="@string/hintText2"
        android:textColorHint="@color/hintTextColour2"
        android:layout_marginLeft="9dp"
        android:gravity="fill_horizontal"
        android:padding="6dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="9dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="89dp"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="89dp"
        tools:layout_constraintTop_creator="1"
        tools:layout_constraintRight_creator="1"
        tools:layout_constraintBottom_creator="1"
        android:layout_marginStart="9dp"
        android:layout_marginEnd="9dp"
        tools:layout_constraintLeft_creator="1"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintVertical_bias="1.0" />

    <EditText
        android:id="@+id/ListName2"
        android:layout_width="0dp"
        android:layout_height="37dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:background="@color/BackgroundGrey2"
        android:inputType="text"
        android:textColor="@color/blackText"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0"
        tools:layout_constraintLeft_creator="1"
        tools:layout_constraintRight_creator="1" />

    <EditText
        android:id="@+id/mapNoDisplay2"
        android:layout_width="172dp"
        android:layout_height="37dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:background="@color/BackgroundGrey2"
        android:inputType="number"
        android:textColor="@color/blackText"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.065" />

    <EditText
        android:id="@+id/dateDisplay2"
        android:layout_width="172dp"
        android:layout_height="37dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:background="@color/BackgroundGrey2"
        android:inputType="date"
        android:textColor="@color/blackText"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.065" />

</android.support.constraint.ConstraintLayout>

1 个答案:

答案 0 :(得分:0)

目前还不清楚你在询问什么。这些都是完全相同的字符串

String map = adapterView.getItemAtPosition(i).toString();
String name = adapterView.getItemAtPosition(i).toString();
String date = adapterView.getItemAtPosition(i).toString();
String notAtHomes = adapterView.getItemAtPosition(i).toString();

因此,sqlite无法找到您传入dbHelper.getItemID的内容,返回无效的ID值。

我认为您正在寻找从适配器获取不同的数据,这是不可能的,因为您只将光标的第三列添加到适配器。

    ArrayList<String> listData = new ArrayList<>();
    while (data.moveToNext()) {
        listData.add(data.getString(2));
    }

您应该考虑使用CursorAdapter正确实现带有数据库的ListView