ListView Android中的SQLite数据库
在android studio的列表视图中显示SQLite数据库中的一些记录时出现问题。显示列表视图的代码为:ListView Android中的SQLite数据库,android,sqlite,simplecursoradapter,Android,Sqlite,Simplecursoradapter,在android studio的列表视图中显示SQLite数据库中的一些记录时出现问题。显示列表视图的代码为: import android.app.DatePickerDialog; import android.content.Intent; import android.database.Cursor; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view
import android.app.DatePickerDialog;
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Calendar;
public class PreviousHunts extends AppCompatActivity implements View.OnClickListener
{
public TextView txtDate;
public String strDate = "";
public ListView lstView;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_previous_hunts);
Button btnDateGet = findViewById(R.id.btnGetHunts);
btnDateGet.setOnClickListener(this);
Button btnHome = findViewById(R.id.btnHuntsHome);
btnHome.setOnClickListener(this);
txtDate = findViewById(R.id.txtDateThing);
lstView = findViewById(R.id.lstView);
}
@Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.btnGetHunts:
getDate();
break;
case R.id.btnHuntsHome:
goHome();
break;
}
}
private void getDate()
{
final Calendar c = Calendar.getInstance();
final int Year = c.get(Calendar.YEAR);
final int Month = c.get(Calendar.MONTH);
final int Day = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener()
{
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth)
{
String day = String.valueOf(dayOfMonth);
String Smonth = String.valueOf(month + 1);
String sYear = String.valueOf(year);
txtDate.setText(day + "/" + Smonth + "/" + sYear);
strDate = day + "/" + Smonth + "/" + sYear;
}
},Year, Month, Day);
datePickerDialog.show();
DatabaseHelper dbHelp = new DatabaseHelper(this);
int huntID = dbHelp.getHuntIDforPastHunts(strDate);
if (huntID == 0)
{
Toast.makeText(getApplicationContext(), "No Hunts on that day.", Toast.LENGTH_LONG).show();
}
else
{
LastPart(huntID);
}
}
private void LastPart(int huntID)
{
DatabaseHelper dbHelp = new DatabaseHelper(this);
Cursor cursor = dbHelp.getPastHuntLogs(huntID);
cursor.moveToFirst();
//SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, lstView, cursor, new String[] {"BirdName", "SeenORShot", "BirdAge", "NumSeenORShot",
//"OtherAnimalShotORClayShoot", "AnimalShotNameORTypeClaysShot"}, new int[] {100}, 0);
//lstView.setAdapter(adapter);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.activity_previous_hunts,
cursor,
new String[]{"BirdName", "SeenORShot", "BirdAge", "NumSeenORShot", "OtherAnimalShotORClayShoot", "AnimalShotNameORTypeClaysShot"},
new int[]{1, 2, 3, 4, 5, 6}
,0);
lstView.setAdapter(adapter);
}
private void goHome()
{
Intent intent = new Intent(PreviousHunts.this, Home_Screen.class);
startActivity(intent);
finish();
}
}
The database helper code is:
public Cursor getPastHuntLogs(int huntID)
{
String query = "SELECT HuntID AS _id, BirdName, SeenORShot, BirdAge, NumSeenORShot, OtherAnimalShotORClayShoot, " +
"AnimalShotNameORTypeClaysShot FROM Log WHERE HuntID = " + "'huntID'";
Cursor cursor = db.rawQuery(query, null);
return cursor;
}
listview等的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=".PreviousHunts">
<Button
android:id="@+id/btnGetHunts"
android:layout_width="150dp"
android:layout_height="75dp"
android:layout_marginStart="15dp"
android:layout_marginTop="15dp"
android:text="Select Date you wish to see hunts from"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/txtDateThing"
android:layout_width="wrap_content"
android:layout_height="25dp"
android:layout_marginEnd="100dp"
android:layout_marginTop="45dp"
android:text="Date"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/btnHuntsHome"
android:layout_width="88dp"
android:layout_height="50dp"
android:layout_marginBottom="10dp"
android:layout_marginEnd="100dp"
android:layout_marginStart="100dp"
android:text="Home"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<ListView
android:id="@+id/lstView"
android:layout_width="362dp"
android:layout_height="342dp"
android:layout_marginEnd="15dp"
android:layout_marginStart="15dp"
android:layout_marginTop="10dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btnGetHunts" />
</android.support.constraint.ConstraintLayout>
问题是什么也没发生。运行日志中没有错误,也没有显示任何内容。非常感谢您的帮助。请尝试在选择日期后添加数据库代码 像这样
private void getDate() {
final Calendar c = Calendar.getInstance();
final int Year = c.get(Calendar.YEAR);
final int Month = c.get(Calendar.MONTH);
final int Day = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener()
{
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth)
{
String day = String.valueOf(dayOfMonth);
String Smonth = String.valueOf(month + 1);
String sYear = String.valueOf(year);
txtDate.setText(day + "/" + Smonth + "/" + sYear);
strDate = day + "/" + Smonth + "/" + sYear;
// Try database code here
DatabaseHelper dbHelp = new DatabaseHelper(this);
int huntID = dbHelp.getHuntIDforPastHunts(strDate);
if (huntID == 0)
{
Toast.makeText(getApplicationContext(), "No Hunts on that day.", Toast.LENGTH_LONG).show();
}
else
{
LastPart(huntID);
}
}
},Year, Month, Day);
datePickerDialog.show();
}
您遇到的主要问题是,在检索日期之后,您没有调用列表的填充。而是在检索日期之前填充列表视图 这就是代码:-
DatabaseHelper dbHelp = new DatabaseHelper(this);
int huntID = dbHelp.getHuntIDforPastHunts(strDate);
if (huntID == 0)
{
Toast.makeText(getApplicationContext(), "No Hunts on that day.", Toast.LENGTH_LONG).show();
}
else
{
LastPart(huntID);
}
将在获得日期之前执行,因此没有日期也没有提取数据
还有其他问题,例如每次按下按钮创建新适配器时,应该在何时使用适配器并刷新列表
下面是我的建议,它的工作代码已经过测试。然而,对于测试,我不得不猜测DatabaseHelper的大部分内容,因为可用的只是getPastHuntLogs方法
使用的DatabaseHelper.java是:-
public class DatabaseHelper extends SQLiteOpenHelper {
/**
* Suggest using 1 definitaion of table and column names and to ALWAYS use the constants
*/
public static final String DBNAME = "hunter";
public static final int DBVERSION = 1;
public static final String TABLE_LOG = "Log";
public static final String COL_TIMESTAMP = "timestamp";
public static final String COl_LOG_HUNTID = "HuntID";
public static final String COL_LOG_BIRDNAME = "BirdName";
public static final String COL_LOG_SEENORSHOT = "SeenOrShot";
public static final String COL_LOG_BIRDAGE = "BirdAge";
public static final String COL_LOG_NUMSEENORSHOT = "NumSeenOrShot";
public static final String COL_LOG_OTHERANIMALSSHOTORCLAYSHOOT = "OtherAnimalShotORClayShoot";
public static final String COL_LOG_ANIMALSHORORTYPECLAYSHOOT = "AnimalShotNameORTypeClaysShot";
SQLiteDatabase db;
public DatabaseHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
db = this.getWritableDatabase();
}
/**
* Guestimate
* @param db
*/
@Override
public void onCreate(SQLiteDatabase db) {
String crt_log_tbl_sql = "CREATE TABLE IF NOT EXISTS " + TABLE_LOG + "(" +
COl_LOG_HUNTID + " INTEGER PRIMARY KEY, " +
COL_TIMESTAMP + " TEXT DEFAULT CURRENT_TIMESTAMP, " +
COL_LOG_BIRDNAME + " TEXT, " +
COL_LOG_SEENORSHOT + " TEXT, " +
COL_LOG_BIRDAGE + " REAL," +
COL_LOG_NUMSEENORSHOT + " INTEGER, " +
COL_LOG_OTHERANIMALSSHOTORCLAYSHOOT + " TEXT," +
COL_LOG_ANIMALSHORORTYPECLAYSHOOT + " TEXT " +
")";
db.execSQL(crt_log_tbl_sql);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
/**
* Added so I could see the rows in the log
*/
public void dumpLogTable() {
Cursor csr = db.query(TABLE_LOG,null,null,null,null,null,null);
DatabaseUtils.dumpCursor(csr);
csr.close();
}
/**
* Guestimate. (note converts dates to YYYY-MM-DD format as stored )
* @param strDate
* @return
*/
public int getHuntIDforPastHunts(String strDate) {
int rv = 0;
String[] datevalues = strDate.split("/");
String srchdate = datevalues[2] + "-" + datevalues[1] + "-" + datevalues[0];
String whereclause = "date(" + COL_TIMESTAMP + ")=?";
String[] whereargs = new String[]{srchdate};
Cursor csr = db.query(TABLE_LOG,null,whereclause,whereargs,null,null,null);
if (csr.moveToFirst()) {
rv = csr.getInt(csr.getColumnIndex(COl_LOG_HUNTID));
}
return rv;
}
/**
* ALlows some testing data to be added
* @param birdname
* @param seenorshot
* @param birdage
* @param numseenorshot
* @param otheranimalshotorclayshoot
* @param animalshotortypeclayshoot
* @return
*/
public long insertLog(String birdname, String seenorshot,double birdage, int numseenorshot, String otheranimalshotorclayshoot, String animalshotortypeclayshoot) {
ContentValues cv = new ContentValues();
cv.put(COL_LOG_BIRDNAME,birdname);
cv.put(COL_LOG_SEENORSHOT,seenorshot);
cv.put(COL_LOG_BIRDAGE,birdage);
cv.put(COL_LOG_NUMSEENORSHOT,numseenorshot);
cv.put(COL_LOG_OTHERANIMALSSHOTORCLAYSHOOT,otheranimalshotorclayshoot);
cv.put(COL_LOG_ANIMALSHORORTYPECLAYSHOOT,animalshotortypeclayshoot);
return db.insert(TABLE_LOG,null,cv);
}
/**
* Very much as was
* @param huntID
* @return
*/
public Cursor getPastHuntLogs(int huntID)
{
String query = "SELECT HuntID AS _id, BirdName, SeenORShot, BirdAge, NumSeenORShot, OtherAnimalShotORClayShoot, " +
"AnimalShotNameORTypeClaysShot FROM Log " +
"WHERE HuntID = " + String.valueOf(huntID) + //<<<<<<<<<< Changed
""; //<<<<<<<<<< ADDED so that WHERE...... can be commented out so select all
return db.rawQuery(query, null); //<<<<<<<< returns cursor directly
}
}
public类DatabaseHelper扩展了SQLiteOpenHelper{
/**
*建议使用1定义表和列名,并始终使用常量
*/
公共静态最终字符串DBNAME=“hunter”;
公共静态最终int DBVERSION=1;
公共静态最终字符串表\u LOG=“LOG”;
公共静态最终字符串COL_TIMESTAMP=“TIMESTAMP”;
公共静态最终字符串COl\u LOG\u HUNTID=“HUNTID”;
公共静态最终字符串COL\u LOG\u BIRDNAME=“BIRDNAME”;
公共静态最终字符串COL\u LOG\u SEENORSHOT=“SEENORSHOT”;
公共静态最终字符串COL\u LOG\u BIRDAGE=“BIRDAGE”;
公共静态最终字符串COL_LOG_numsenoshot=“numsenoshot”;
公共静态最终字符串COL\u LOG\u otheranimalshotorclayshot=“otheranimalshotorclayshot”;
公共静态最终字符串COL\u LOG\u animalshortTypeClayShot=“animalshotNameorTypeClayShot”;
sqlitedb数据库;
公共数据库助手(上下文){
super(上下文,DBNAME,null,DBVERSION);
db=this.getWritableDatabase();
}
/**
*客栈
*@param-db
*/
@凌驾
public void onCreate(SQLiteDatabase db){
字符串crt\U log\U tbl\U sql=“创建不存在的表格”+表格\U log+”(“+
COl_LOG_HUNTID+“整数主键,”+
COL_TIMESTAMP+“文本默认当前_TIMESTAMP,”+
COL_LOG_BIRDNAME+“文本”+
COL_LOG_SEENORSHOT+“文本”+
COL_LOG_BIRDAGE+“真的,”+
COL_LOG_NUMSENORSHOT+“整数,”+
COL_LOG_其他动物快照或播放快照+文本+
COL_LOG_Animalshortype ClayShot+“文本”+
")";
execSQL(crt\u log\u tbl\u sql);
}
@凌驾
public void onUpgrade(SQLiteDatabase SQLiteDatabase,inti,inti1){
}
/**
*添加,以便我可以看到日志中的行
*/
公共无效转储日志表(){
游标csr=db.query(TABLE_LOG,null,null,null,null,null,null);
DatabaseUtils.dumpCursor(csr);
csr.close();
}
/**
*Guestimate.(注意将日期转换为存储的YYYY-MM-DD格式)
*@param strDate
*@返回
*/
public int GetHuntIDForpAshunts(字符串标准日期){
int-rv=0;
字符串[]datevalues=strDate.split(“/”);
字符串srchdate=datevalues[2]+“-”+datevalues[1]+“-”+datevalues[0];
字符串whereclause=“日期(“+COL_TIMESTAMP+”)=?”;
String[]wherergs=新字符串[]{srchdate};
游标csr=db.query(TABLE_LOG,null,where子句,wherergs,null,null,null);
if(csr.moveToFirst()){
rv=csr.getInt(csr.getColumnIndex(COl_LOG_HUNTID));
}
返回rv;
}
/**
*允许添加一些测试数据
*@param birdname
*@param seenorshot
*@param birdage
*@param numsenoshot
*@param otheranimalshot或layshot
*@param animalshot或typeclayshot
*@返回
*/
公共长插入日志(字符串birdname、字符串seenorshot、双birdage、int numseenorshot、字符串其他动物照片或layshot、字符串动物照片或类型clayshot){
ContentValues cv=新的ContentValues();
cv.put(COL_LOG_BIRDNAME,BIRDNAME);
cv.put(COL_LOG_SEENORSHOT,SEENORSHOT);
cv.put(COL_LOG_BIRDAGE,BIRDAGE);
cv.put(COL_LOG_NUMSENORSHOT,NUMSENORSHOT);
cv.put(COL_LOG_其他动物拍摄或放射学,其他动物拍摄或放射学);
cv.put(COL_LOG_AnimalshortypeClayshot,AnimalshortypeClayshot);
返回db.insert(TABLE_LOG,null,cv);
}
/**
*一如从前
*@param huntID
*@返回
*/
公共游标getPastHuntLogs(int-huntID)
{
String query=“选择HuntID作为_id,BirdName,参见norshot,BirdAge,numsenoshot,otheranimalshot或layshot,”+
“Animalshotname或TypeClaysshot来自日志”+
“其中HuntID=“+String.valueOf(HuntID))+/实际上在这之后走了一条不那么复杂但更简单的路线。只需制作一个长字符串,这实际上对以后的代码部分有帮助。谢谢大家的帮助。检查适配器是否为空。@AndroidTeam如何检查适配器是否为空?在getDate()中显示的DatePickerDialog
)
不会在该方法中暂停执行。它将立即继续您的数据库操作,并且在未设置strDate
的情况下,我可以想象您在返回的光标中没有得到任何记录。不幸的是,它没有工作,任何显示都没有更改。谢谢您的尝试。@AlexanderMcmichael您能确保查询是正确的?或者是否有来自数据库的值?
public class PreviousHunts extends AppCompatActivity implements View.OnClickListener {
public TextView txtDate;
public String strDate = "";
public ListView lstView;
SimpleCursorAdapter adapter; //<<<<<<<<<< ADDED
DatabaseHelper dbHelp; //<<<<<<<<<< ADDED
Cursor cursor; //<<<<<<<<<< ADDED
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_previous_hunts);
Button btnDateGet = findViewById(R.id.btnGetHunts);
btnDateGet.setOnClickListener(this);
Button btnHome = findViewById(R.id.btnHuntsHome);
btnHome.setOnClickListener(this);
txtDate = findViewById(R.id.txtDateThing);
lstView = findViewById(R.id.lstView);
dbHelp = new DatabaseHelper(this); //<<<<<<<<<< ADDED
addSomeTestData(); //<<<<<<<<<< ADDDED
}
@Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.btnGetHunts:
getDate();
break;
case R.id.btnHuntsHome:
goHome();
break;
}
}
private void getDate()
{
final Calendar c = Calendar.getInstance();
final int Year = c.get(Calendar.YEAR);
final int Month = c.get(Calendar.MONTH);
final int Day = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener()
{
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth)
{
String day = String.valueOf(dayOfMonth);
String Smonth = String.valueOf(month + 1);
String sYear = String.valueOf(year);
txtDate.setText(day + "/" + Smonth + "/" + sYear);
strDate = day + "/" + Smonth + "/" + sYear;
displayHuntList(strDate); //<<<<<<<<<< CHANGED calls displayHuntList
}
},Year, Month, Day);
datePickerDialog.show();
}
//<<<<<<<<<< NEW replaces last_hunt code
public void displayHuntList(String strDate) {
int huntID = dbHelp.getHuntIDforPastHunts(strDate);
if (huntID < 1) {
Toast.makeText(getApplicationContext(), "No Hunts on that day.", Toast.LENGTH_LONG).show();
}
cursor = dbHelp.getPastHuntLogs(huntID);
//<<<<<<<<<< Only create a SimpleCursorAdapter instance once and reuse
//<<<<<<<<<< NOTE!! Stock layout used for convenience >>>>>>>>>>
if (adapter == null) {
adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_2,
cursor,
new String[]{DatabaseHelper.COL_LOG_BIRDNAME,
DatabaseHelper.COL_LOG_SEENORSHOT},
new int[]{android.R.id.text1,android.R.id.text2},
0
);
lstView.setAdapter(adapter);
} else {
// if called after the initial call just swap the cursor to refresh the list
adapter.swapCursor(cursor);
}
}
private void goHome()
{
//<<<<<<<<<< Commented body out so hitting HOME does nothing >>>>>>>>>>
/*
Intent intent = new Intent(PreviousHunts.this, Home_Screen.class);
startActivity(intent);
finish();
*/
}
/**
* Added so some testing data is added (note 2 rows added each time App is run)
* All rows have a timestamp as per the day the App is run (ok for testing)
*/
private void addSomeTestData() {
dbHelp.insertLog("Pheasant","Seen",1.75,100,"N/A","N/A");
dbHelp.insertLog("Grouse","SHOT",2.3,10,"NO","MAYBE");
dbHelp.dumpLogTable();
}
}