如何从列表视图中从 sqlite 检索数据单击并查看不同的活动 android studio
Posted
技术标签:
【中文标题】如何从列表视图中从 sqlite 检索数据单击并查看不同的活动 android studio【英文标题】:How to retrieve data from sqlite from list view click and view on a different activity android studio 【发布时间】:2018-05-23 23:20:36 【问题描述】:我是 android studio 的新手,我正在尝试制作一个出勤移动应用程序,其中: - 我可以添加学生并查看添加的学生列表 - 添加事件并查看添加的事件列表 - 在我有一个微调器、自动完成文本视图和一个按钮的地方添加出勤率。在微调器上,事件名称是从 SQLite 数据库表中检索的。在自动完成文本视图中,学生的姓氏也在 SQLite DB 中的表中检索。
我的问题是我不知道如何查看出席该活动的学生名单。当我单击事件列表视图时,我希望它这样做,新活动将打开并显示所有在场的学生。
我的学生表有 StudentID(主键、自动增量)、姓氏、名字、年份。 事件表有EventId(主键,自增),事件名称,日期,时间。 考勤表:考勤ID(主键,自增),事件名,学生姓。
非常感谢你们的帮助。这是我的代码。
ViewEvents.java
package com.example.acer.finals;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class ViewEvents extends AppCompatActivity
DatabaseHelper myDB;
private ListView mylistView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_viewevents);
mylistView = (ListView) findViewById(R.id.listView3);
myDB = new DatabaseHelper(this);
populateEventView();
private void populateEventView()
ArrayList<String> theList = new ArrayList<>();
Cursor data = myDB.getEventsList();
int numRows = data.getCount();
if(numRows == 0)
Toast.makeText(ViewEvents.this, "Event List Empty!", Toast.LENGTH_LONG).show();
else
while (data.moveToNext())
theList.add("Event Name: " + data.getString(1) + "\nDate: " + data.getString(2) + "\nTime: " + data.getString(3));
ListAdapter listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, theList);
mylistView.setAdapter(listAdapter);
//set an onItemClickListener to the ListView
mylistView.setOnItemClickListener(new AdapterView.OnItemClickListener()
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l)
String ename = adapterView.getItemAtPosition(i).toString();
Cursor data = myDB.getEventName(ename);
Intent intent = new Intent(ViewEvents.this, Load_Attendance.class);
startActivity(intent);
);
AddAttendance.java
package com.example.acer.finals;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
public class AddAttendance extends AppCompatActivity
Spinner spnrEvent;
Button btnSave;
AutoCompleteTextView autoCtv;
DatabaseHelper myDB;
ArrayList<String> names = new ArrayList<String>();
ArrayList<String> all_Lname = new ArrayList<String>();
ArrayAdapter<String> adapter;
ArrayAdapter<String> AllNames_adapter;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attendance);
spnrEvent = (Spinner) findViewById(R.id.spnrEvent);
btnSave = (Button) findViewById(R.id.btnSave);
autoCtv = (AutoCompleteTextView) findViewById(R.id.autoCtv);
//ADAPTER
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, names);
myDB = new DatabaseHelper(this);
final Cursor event = myDB.getAllEvents();
while(event.moveToNext())
String name = event.getString(1);
names.add(name);
spnrEvent.setAdapter(adapter);
//================================================
all_Lname = myDB.getAll_Lname();
AllNames_adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, all_Lname);
autoCtv.setAdapter(AllNames_adapter);
//================================================
btnSave.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
String evname = spnrEvent.getSelectedItem().toString();
String lastname = autoCtv.getText().toString();
if(evname.length() != 0 && lastname.length() != 0)
createAttendance(evname,lastname);
spnrEvent.setSelection(0);
autoCtv.setText("");
else
Toast.makeText(AddAttendance.this,"You must put something in the text field!",Toast.LENGTH_LONG).show();
);
public void createAttendance(String evname, String lastname)
boolean insertData = myDB.createAttendanceTB(evname,lastname);
if(insertData==true)
Toast.makeText(AddAttendance.this,"Successfully Entered Data!",Toast.LENGTH_LONG).show();
else
Toast.makeText(AddAttendance.this,"Something went wrong :(.",Toast.LENGTH_LONG).show();
Load_Attendance.java
package com.example.acer.finals;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class Load_Attendance extends AppCompatActivity
DatabaseHelper myDB;
private ListView attendance_list;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loadattendance);
attendance_list = (ListView) findViewById(R.id.attendance_list);
myDB = new DatabaseHelper(this);
populateListViewAttendance();
private void populateListViewAttendance()
String name= "";
ArrayList<String> theList = new ArrayList<>();
Cursor data = myDB.getEventAttendance(name);
int numRows = data.getCount();
if(numRows == 0)
Toast.makeText(Load_Attendance.this, "Attendance List Empty!", Toast.LENGTH_LONG).show();
else
while(data.moveToNext())
theList.add(data.getString(1));
ListAdapter listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, theList);
attendance_list.setAdapter(listAdapter);
DatabaseHelper.java
package com.example.acer.finals;
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;
/**
* Created by acer on 12/3/2017.
*/
public class DatabaseHelper extends SQLiteOpenHelper
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "Finals";
// Table Names
private static final String StudentInfo = "StudentInfo";
private static final String EventTB= "EventTB";
private static final String AttendanceTB = "AttendanceTB";
// StudentInfo Table - column names
private static final String StudentID = "StudentID";
private static final String LastName = "LastName";
private static final String FirstName = "FirstName";
private static final String Year = "Year";
// TAGS Table - column names
private static final String EventID = "EventID";
private static final String EventName = "EventName";
private static final String EDate = "EDate";
private static final String Time = "Time";
// NOTE_TAGS Table - column names
private static final String AttendanceID = "AttendanceID";
private static final String Event_Name = "EventName";
private static final String Student_Lname = "Student_Lname";
public DatabaseHelper(Context context)
super(context,DATABASE_NAME, null, DATABASE_VERSION);
// Table Create Statements
// createStudentInfo table create statement
private static final String createStudentInfo = "CREATE TABLE " + StudentInfo + "("
+ StudentID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ LastName + " TEXT,"
+ FirstName + " TEXT,"
+ Year + " TEXT " + ")";
// createEventTB table create statement
private static final String createEventTB = "CREATE TABLE " + EventTB + "("
+ EventID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ EventName + " TEXT,"
+ EDate + " TEXT,"
+ Time + " TEXT " + ")";
// AttendanceTB table create statement
private static final String createAttendanceTB = "CREATE TABLE " + AttendanceTB + "("
+ AttendanceID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ Event_Name + " TEXT,"
+ Student_Lname + " TEXT "+ ")";
@Override
public void onCreate(SQLiteDatabase db)
db.execSQL(createStudentInfo);
db.execSQL(createEventTB);
db.execSQL(createAttendanceTB);
@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1)
// on upgrade drop older tables
db.execSQL("DROP TABLE IF EXISTS " + createStudentInfo);
db.execSQL("DROP TABLE IF EXISTS " + createEventTB);
db.execSQL("DROP TABLE IF EXISTS " + createAttendanceTB);
// create new tables
onCreate(db);
public boolean createStudentInfo(String lname, String fname, String year)
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(LastName,lname);
contentValues.put(FirstName,fname);
contentValues.put(Year, year);
long result = db.insert(StudentInfo, null, contentValues);
if(result == -1)
return false;
else
return true;
public boolean createEventTB(String ename, String edate, String time)
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(EventName,ename);
contentValues.put(EDate,edate);
contentValues.put(Time,time);
long result = db.insert(EventTB, null, contentValues);
if(result == -1)
return false;
else
return true;
public boolean createAttendanceTB(String evname, String lastname)
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Event_Name,evname);
contentValues.put(Student_Lname,lastname);
long result = db.insert(AttendanceTB, null, contentValues);
if(result == -1)
return false;
else
return true;
//returns all data from StudentInfo db
public Cursor getStudentsList()
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + StudentInfo;
Cursor data = db.rawQuery(query, null);
return data;
//returns all events list
public Cursor getEventsList()
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + EventTB;
Cursor data = db.rawQuery(query, null);
return data;
//Returns only the ID that matches the name passed in
public Cursor getEventName(String ename)
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + AttendanceTB +
" WHERE " + EventName + " = '" + ename + "'";
Cursor data = db.rawQuery(query, null);
return data;
//Returns only the ID that matches the name passed in
public Cursor getEventAttendance(String name)
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT * " + Student_Lname + " FROM " + AttendanceTB +
" WHERE " + EventName + " = '" + name + "'";
Cursor data = db.rawQuery(query, null);
return data;
//GET ALL Events
public Cursor getAllEvents()
SQLiteDatabase db = this.getWritableDatabase();
String[] columns=EventID,EventName;
return db.query(EventTB, columns, null, null, null, null, null);
//spinner
public ArrayList<String> getAll_Lname()
ArrayList<String> all_Lname = new ArrayList<String>();
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT DISTINCT " + LastName + " FROM " + StudentInfo;
Cursor data = db.rawQuery(query, null);
if (data.getCount() > 0)
data.moveToFirst();
while(!data.isAfterLast())
all_Lname.add(data.getString(0));
data.moveToNext();
return all_Lname;
activity_viewevents.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_
android:layout_>
<ListView
android:layout_
android:layout_
android:id="@+id/listView3"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_margin="20dp" />
</RelativeLayout>
acivity_addattendance.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_
android:layout_>
<TextView
android:layout_
android:layout_
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Choose Event :"
android:id="@+id/textView15"
android:textSize="22sp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="20dp"
android:layout_marginTop="50dp" />
<Spinner
android:layout_
android:layout_
android:id="@+id/spnrEvent"
android:layout_gravity="right"
android:clickable="false"
android:layout_below="@+id/textView15"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp" />
<Button
android:layout_
android:layout_
android:text="SAVE"
android:id="@+id/btnSave"
android:textSize="25sp"
android:layout_marginTop="45dp"
android:layout_below="@+id/autoCtv"
android:layout_alignLeft="@+id/autoCtv"
android:layout_alignStart="@+id/autoCtv"
android:layout_alignRight="@+id/autoCtv"
android:layout_alignEnd="@+id/autoCtv"
android:background="@color/material_deep_teal_500"
android:textColor="@color/primary_text_default_material_dark" />
<AutoCompleteTextView
android:layout_
android:layout_
android:id="@+id/autoCtv"
android:layout_marginTop="50dp"
android:textSize="20sp"
android:visibility="visible"
android:layout_below="@+id/spnrEvent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:hint="Last Name"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp" />
</RelativeLayout>
activity_loadattendance.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_
android:layout_>
<ListView
android:layout_
android:layout_
android:id="@+id/attendance_list" />
</LinearLayout>
【问题讨论】:
【参考方案1】:当您单击一个事件时,您会提取被单击事件的事件名称。然后,您想要启动一个活动,但将事件名称传递给该活动。
您可以通过添加 Intent Extra 来做到这一点,例如:-
Intent intent = new Intent(ViewEvents.this, Load_Attendance.class);
intent.putExtra("EVENT_NAME",ename); //<<<<<<<< ADD this Line
startActivity(intent);
那么 Load_Attendance
可能是:-
public class Load_Attendance extends AppCompatActivity
DatabaseHelper myDB;
private ListView attendance_list;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loadattendance);
attendance_list = (ListView) findViewById(R.id.attendance_list);
myDB = new DatabaseHelper(this);
populateListViewAttendance(getIntent().getStringExtra("EVENT_NAME")); //<<<<<<<< invoke with retrieved event name
private void populateListViewAttendance(String name) //<<<<<<<< added parameter
ArrayList<String> theList = new ArrayList<>();
Cursor data = myDB.getEventAttendance(name);
int numRows = data.getCount();
if(numRows == 0)
Toast.makeText(Load_Attendance.this, "Attendance List Empty!", Toast.LENGTH_LONG).show();
else
while(data.moveToNext())
theList.add(data.getString(1));
ListAdapter listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, theList);
attendance_list.setAdapter(listAdapter);
//<<<<<<<<
表示更改/添加的代码行
请注意,这尚未经过测试,并假定现有代码正在运行,可能存在奇怪的错误。
附:你应该在完成后关闭游标。
由于一连串的失败,在 cmets 之后进行编辑。
以下是基于您的代码的代码,但简化为您想要的关于此问题的基础知识。
这是一个事件列表显示在一个列表视图中,单击一个项目会生成一个参与者列表。
但是,这都是在同一个活动中完成的,点击事件的参与者会在日志中列出。简而言之,这验证了上述答案中提供的基本过程是否有效,而您遇到的问题很可能是由于您在数据库中拥有的数据。
代码
activity_main.xml :-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_
android:layout_
tools:context="acer.com.finals.MainActivity">
<TextView
android:layout_
android:layout_
android:text="Hello World!"/>
<ListView
android:id="@+id/EventsList"
android:layout_
android:layout_
>
</ListView>
</LinearLayout>
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "Finals";
// Table Names
private static final String StudentInfo = "StudentInfo";
private static final String EventTB= "EventTB";
private static final String AttendanceTB = "AttendanceTB";
// StudentInfo Table - column names
private static final String StudentID = "StudentID";
private static final String LastName = "LastName";
private static final String FirstName = "FirstName";
private static final String Year = "Year";
// TAGS Table - column names
private static final String EventID = "EventID";
private static final String EventName = "EventName";
private static final String EDate = "EDate";
private static final String Time = "Time";
// NOTE_TAGS Table - column names
private static final String AttendanceID = "AttendanceID";
private static final String Event_Name = "EventName";
private static final String Student_Lname = "Student_Lname";
public DatabaseHelper(Context context)
super(context,DATABASE_NAME, null, DATABASE_VERSION);
// Table Create Statements
// createStudentInfo table create statement
private static final String createStudentInfo = "CREATE TABLE " + StudentInfo + "("
+ StudentID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ LastName + " TEXT,"
+ FirstName + " TEXT,"
+ Year + " TEXT " + ")";
// createEventTB table create statement
private static final String createEventTB = "CREATE TABLE " + EventTB + "("
+ EventID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ EventName + " TEXT,"
+ EDate + " TEXT,"
+ Time + " TEXT " + ")";
// AttendanceTB table create statement
private static final String createAttendanceTB = "CREATE TABLE " + AttendanceTB + "("
+ AttendanceID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ Event_Name + " TEXT,"
+ Student_Lname + " TEXT "+ ")";
@Override
public void onCreate(SQLiteDatabase db)
db.execSQL(createStudentInfo);
db.execSQL(createEventTB);
db.execSQL(createAttendanceTB);
@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1)
// on upgrade drop older tables
db.execSQL("DROP TABLE IF EXISTS " + StudentInfo);
db.execSQL("DROP TABLE IF EXISTS " + EventTB);
db.execSQL("DROP TABLE IF EXISTS " + AttendanceTB);
// create new tables
onCreate(db);
public boolean createStudentInfo(String lname, String fname, String year)
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(LastName,lname);
contentValues.put(FirstName,fname);
contentValues.put(Year, year);
long result = db.insert(StudentInfo, null, contentValues);
if(result == -1)
return false;
else
return true;
public boolean createEventTB(String ename, String edate, String time)
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(EventName,ename);
contentValues.put(EDate,edate);
contentValues.put(Time,time);
long result = db.insert(EventTB, null, contentValues);
if(result == -1)
return false;
else
return true;
public boolean createAttendanceTB(String evname, String lastname)
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Event_Name,evname);
contentValues.put(Student_Lname,lastname);
long result = db.insert(AttendanceTB, null, contentValues);
if(result == -1)
return false;
else
return true;
//returns all data from StudentInfo db
public Cursor getStudentsList()
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + StudentInfo;
Cursor data = db.rawQuery(query, null);
return data;
//returns all events list
public Cursor getEventsList()
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + EventTB;
Cursor data = db.rawQuery(query, null);
return data;
//Returns only the ID that matches the name passed in
public Cursor getEventName(String ename)
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + AttendanceTB +
" WHERE " + EventName + " = '" + ename + "'";
Cursor data = db.rawQuery(query, null);
return data;
//Returns only the ID that matches the name passed in
public Cursor getEventAttendance(String name)
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT * FROM " + AttendanceTB +
" WHERE " + EventName + " = '" + name + "'";
Cursor data = db.rawQuery(query, null);
return data;
//GET ALL Events
public Cursor getAllEvents()
SQLiteDatabase db = this.getWritableDatabase();
String[] columns=EventID,EventName;
return db.query(EventTB, columns, null, null, null, null, null);
//spinner
public ArrayList<String> getAll_Lname()
ArrayList<String> all_Lname = new ArrayList<String>();
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT DISTINCT " + LastName + " FROM " + StudentInfo;
Cursor data = db.rawQuery(query, null);
if (data.getCount() > 0)
data.moveToFirst();
while(!data.isAfterLast())
all_Lname.add(data.getString(0));
data.moveToNext();
return all_Lname;
请注意,虽然这相似,但有 2) 重要更改:-
1 onUpgrade
方法不是连接表创建 SQL,而是连接相应的表名。原来的onUpgrade
方法会失败。
2 根据答案和 cmets,getEventAttendance
方法已被修改为以 eventname 作为参数并从出席表中选择所有列。
MainActivity.java
公共类 MainActivity 扩展 AppCompatActivity
DatabaseHelper dbhelper;
ListAdapter mEventListAdapter;
ArrayList<String> mEventList;
ListView mEventsListView;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEventsListView = this.findViewById(R.id.EventsList);
dbhelper = new DatabaseHelper(this);
dbhelper.getWritableDatabase().delete("EventTB",null,null);
dbhelper.getWritableDatabase().delete("StudentInfo", null,null);
dbhelper.getWritableDatabase().delete("AttendanceTB", null,null);
dbhelper.createEventTB("The Main Event","31/12/2017","10:30");
dbhelper.createEventTB("The Normal Event","31/12/2017","10:30");
dbhelper.createEventTB("The Minor Event","31/12/2017","10:30");
dbhelper.createStudentInfo("Bloggs","Fred","2017");
dbhelper.createStudentInfo("Smith","Tom", "2016");
dbhelper.createStudentInfo("Thomas","John","2015");
dbhelper.createAttendanceTB("The Main Event","Bloggs");
dbhelper.createAttendanceTB("The Main Event", "Smith");
dbhelper.createAttendanceTB("The Normal Event","Thomas");
dbhelper.createAttendanceTB("The Minor Event","Thomas");
dbhelper.createAttendanceTB("The Minor Event","Smith");
Cursor csr = dbhelper.getEventsList();
mEventList = new ArrayList<>();
while (csr.moveToNext())
mEventList.add(csr.getString(1));
mEventListAdapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,mEventList);
mEventsListView.setAdapter(mEventListAdapter);
mEventsListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
String eventname = parent.getItemAtPosition(position).toString();
Log.d("EVLIST_ITEMCLCK","You clicked Item at Position " + position + " and extracted Event name as " + eventname);
logEventAttendance(eventname);
);
private void logEventAttendance(String eventname)
Cursor csr = dbhelper.getEventAttendance(eventname);
Log.d("EVATTEND","Number of attendance rows extracted is " + csr.getCount());
while (csr.moveToNext())
Log.d("EVATTEND", "Attendee is " + csr.getString(2) + " at Event " + csr.getString(1));
这个:-
1) 进行非常普通的初始化,然后通过它的 ID 获取 ListView。 2) 创建数据库助手的实例,清空 3 个表(数据库和表将在应用程序的第一次运行时创建)。 3) 添加 3 个事件。 4) 添加 3 名学生。 5) 在活动中添加出席人数请注意,活动名称和学生姓氏必须与相应的活动名称和学生姓名完全匹配 请注意,使用名称作为引用是有限制的,例如您不能使用学生的 Tom Smith 和 Fred Smith,因为您使用姓氏作为参考。 通常 ID 用于在表之间引用/链接列。 6) 获取 EventList 并将其转换为 ArrayList。 7) 设置 ListAdapter 以使用事件名称的 ArrayList。 8) 将适配器绑定到 ListView9) 向列表视图添加一个 onItemClick 侦听器。
10) 单击项目时,事件的出席行数会显示在日志中,并且会为每个(如果有)创建一个日志条目。
输出
以下是上面依次点击每一项后的输出:-
12-12 04:58:53.014 2860-2860/acer.com.finals D/EVLIST_ITEMCLCK: You clicked Item at Position 0 and extracted Event name as The Main Event
12-12 04:58:53.014 2860-2860/acer.com.finals D/EVATTEND: Number of attendance rows extracted is 2
12-12 04:58:53.014 2860-2860/acer.com.finals D/EVATTEND: Attendee is Bloggs at Event The Main Event
12-12 04:58:53.014 2860-2860/acer.com.finals D/EVATTEND: Attendee is Smith at Event The Main Event
12-12 04:58:54.192 2860-2860/acer.com.finals D/EVLIST_ITEMCLCK: You clicked Item at Position 1 and extracted Event name as The Normal Event
12-12 04:58:54.193 2860-2860/acer.com.finals D/EVATTEND: Number of attendance rows extracted is 1
12-12 04:58:54.193 2860-2860/acer.com.finals D/EVATTEND: Attendee is Thomas at Event The Normal Event
12-12 04:58:55.477 2860-2860/acer.com.finals D/EVLIST_ITEMCLCK: You clicked Item at Position 2 and extracted Event name as The Minor Event
12-12 04:58:55.478 2860-2860/acer.com.finals D/EVATTEND: Number of attendance rows extracted is 2
12-12 04:58:55.478 2860-2860/acer.com.finals D/EVATTEND: Attendee is Thomas at Event The Minor Event
12-12 04:58:55.478 2860-2860/acer.com.finals D/EVATTEND: Attendee is Smith at Event The Minor Event
请注意,这是为了补充答案。
【讨论】:
嗨,迈克先生,这条线.. getIntent 是红线:populateListViewAttendance(getIntent.getStringExtra("EVENT_NAME"); 哎呀应该是populateListViewAttendance(getIntent().getStringExtra("EVENT_NAME"));
我的 databasehelper.java 先生有一个错误 :( 它说 :: Caused by: android.database.sqlite.SQLiteException: near "Student_Lname": syntax error (code 1): , while编译:SELECT * Student_Lname FROM AttendanceTB WHERE EventName = '事件名称:qqwde ___数据库中的这一行 helper.java.. 字符串查询 = "SELECT * " + Student_Lname + " FROM " + AttendanceTB + " WHERE " + EventName + " = '" + 名称 + "'";
您需要用逗号 (*, Student_Lname
) 将结果光标中所需的列分开。但是,* 表示所有列,所以您只需要*
。
嗨,迈克爵士!谢谢你一直回答我的问题。我已从查询中取出 *.. 它确实打开了新活动,即 load_attendance.. 但它没有显示在活动中输入的学生列表。它只说“出席名单是空的”:(以上是关于如何从列表视图中从 sqlite 检索数据单击并查看不同的活动 android studio的主要内容,如果未能解决你的问题,请参考以下文章
单击 Listview 中的项目时,如何在新活动中从 Firebase 检索数据?
如何在 JAVA 中从数据库中检索无线电组数据? M 使用 Java Swing 和 SQLite [重复]