如何从列表视图中的sqlite检索数据单击并查看不同的活动android工作室

时间:2017-12-10 04:39:11

标签: java android database sqlite listview

我是Android工作室的新手,我正在尝试制作一个考勤移动应用程序,其中: - 我可以添加学生并查看添加的学生列表 - 添加事件并查看添加的事件列表 - 添加考勤,我有一个微调器,自动完成文本视图和一个按钮。在微调器上,事件名称是从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_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="400dp"
        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_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        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_width="match_parent"
        android:layout_height="wrap_content"
        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_width="wrap_content"
        android:layout_height="wrap_content"
        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_width="wrap_content"
        android:layout_height="wrap_content"
        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_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/attendance_list" />
</LinearLayout>

1 个答案:

答案 0 :(得分:0)

单击某个事件时,您将提取所单击事件的事件名称。然后,您希望启动一个活动,但将事件名称传递给该活动。

您可以通过添加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);

    }
}

//<<<<<<<< 表示已更改/添加的代码行

请注意,这还没有经过测试,并假设现有代码正常运行,可能会出现奇怪的错误。

P.S。你完成后应该关闭游标。

由于失败链而在评论后编辑。

以下是基于您的代码的代码,但简化为您对此问题所需的基础知识。

这是一个事件列表,在Listview中显示,点击一个项目可以生成一个参与者列表。

但是,这一切都在同一活动中完成,点击事件的与会者列在日志中。简而言之,这将验证上述答案中提供的基本过程是否有效,而您所遇到的问题很可能是由于数据库中的数据所致。

守则

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_width="match_parent"
    android:layout_height="match_parent"
    tools:context="acer.com.finals.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"/>

    <ListView
        android:id="@+id/EventsList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
    >
    </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;
    }
}

请注意,虽然这是类似的,但有一个重要的变化: -

  • 1 onUpgrade方法而不是连接表创建SQL而不是连接相应的表名。原始的onUpgrade方法会失败。

  • 2根据答案和评论,修改了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)在活动中添加出勤注意事件名称和学生最后一个名称与事件名称和学生姓名完全匹配
    • 请注意,使用名称作为参考是有限制的,例如当你使用姓氏作为参考时,你不可能有学生的汤姆史密斯和弗雷德史密斯。
    • 通常,ID用于引用/链接表之间的列。
  • 6)获取EventList并将其转换为ArrayList。
  • 7)设置ListAdapter以使用事件名称的ArrayList。
  • 8)将适配器绑定到ListView
  • 9)将onItemClick侦听器添加到listview。

  • 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

请注意,这是为了补充答案。