📜  如何从Android中的SQLite数据库读取数据?

📅  最后修改于: 2021-05-13 15:31:32             🧑  作者: Mango

在我们的SQLite数据库的第一部分中,我们看到了如何在Android中创建数据并将其添加到SQLite数据库。在那篇文章中,我们已经将数据添加到了SQLite数据库中。在本文中,我们将从SQLite数据库中读取所有这些数据,并将这些数据显示在RecyclerView中

我们将在本文中构建什么?

我们将处理上一篇文章中构建的现有应用程序。在该应用程序中,我们仅添加课程列表部分即可在其中查看课程列表。下面提供了一个示例视频,以使您对本文中的工作有个大概的了解。注意,我们将使用Java语言实现该项目。

分步实施

步骤1:使用activity_main.xml文件

转到activity_main.xml文件并添加一个新的Button,以打开一个新活动以显示我们的课程列表。

XML


XML


  
    
    
  
    
    
  
    
    
  
    
    
  
    
    


Java
public class CourseModal {
  
    // variables for our coursename,
    // description, tracks and duration, id.
    private String courseName;
    private String courseDuration;
    private String courseTracks;
    private String courseDescription;
    private int id;
  
    // creating getter and setter methods
    public String getCourseName() {
        return courseName;
    }
  
    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }
  
    public String getCourseDuration() {
        return courseDuration;
    }
  
    public void setCourseDuration(String courseDuration) {
        this.courseDuration = courseDuration;
    }
  
    public String getCourseTracks() {
        return courseTracks;
    }
  
    public void setCourseTracks(String courseTracks) {
        this.courseTracks = courseTracks;
    }
  
    public String getCourseDescription() {
        return courseDescription;
    }
  
    public void setCourseDescription(String courseDescription) {
        this.courseDescription = courseDescription;
    }
  
    public int getId() {
        return id;
    }
  
    public void setId(int id) {
        this.id = id;
    }
  
    // constructor
    public CourseModal(String courseName, String courseDuration, String courseTracks, String courseDescription) {
        this.courseName = courseName;
        this.courseDuration = courseDuration;
        this.courseTracks = courseTracks;
        this.courseDescription = courseDescription;
    }
}


Java
// we have created a new method for reading all the courses.
public ArrayList readCourses() {
        // on below line we are creating a
        // database for reading our database.
        SQLiteDatabase db = this.getReadableDatabase();
  
        // on below line we are creating a cursor with query to read data from database.
        Cursor cursorCourses = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
  
        // on below line we are creating a new array list.
        ArrayList courseModalArrayList = new ArrayList<>();
  
        // moving our cursor to first position.
        if (cursorCourses.moveToFirst()) {
            do {
                // on below line we are adding the data from cursor to our array list.
                courseModalArrayList.add(new CourseModal(cursorCourses.getString(1), 
                                             cursorCourses.getString(4), 
                                             cursorCourses.getString(2), 
                                             cursorCourses.getString(3)));
            } while (cursorCourses.moveToNext());
            // moving our cursor to next.
        }
        // at last closing our cursor 
        // and returning our array list.
        cursorCourses.close();
        return courseModalArrayList;
}


Java
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;
  
public class DBHandler extends SQLiteOpenHelper {
  
    // creating a constant variables for our database.
    // below variable is for our database name.
    private static final String DB_NAME = "coursedb";
  
    // below int is our database version
    private static final int DB_VERSION = 1;
  
    // below variable is for our table name.
    private static final String TABLE_NAME = "mycourses";
  
    // below variable is for our id column.
    private static final String ID_COL = "id";
  
    // below variable is for our course name column
    private static final String NAME_COL = "name";
  
    // below variable id for our course duration column.
    private static final String DURATION_COL = "duration";
  
    // below variable for our course description column.
    private static final String DESCRIPTION_COL = "description";
  
    // below variable is for our course tracks column.
    private static final String TRACKS_COL = "tracks";
  
    // creating a constructor for our database handler.
    public DBHandler(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }
  
    // below method is for creating a database by running a sqlite query
    @Override
    public void onCreate(SQLiteDatabase db) {
        // on below line we are creating
        // an sqlite query and we are
        // setting our column names
        // along with their data types.
        String query = "CREATE TABLE " + TABLE_NAME + " ("
                + ID_COL + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + NAME_COL + " TEXT,"
                + DURATION_COL + " TEXT,"
                + DESCRIPTION_COL + " TEXT,"
                + TRACKS_COL + " TEXT)";
  
        // at last we are calling a exec sql
        // method to execute above sql query
        db.execSQL(query);
    }
  
    // this method is use to add new course to our sqlite database.
    public void addNewCourse(String courseName, String courseDuration, String courseDescription, String courseTracks) {
  
        // on below line we are creating a variable for
        // our sqlite database and calling writable method
        // as we are writing data in our database.
        SQLiteDatabase db = this.getWritableDatabase();
  
        // on below line we are creating a
        // variable for content values.
        ContentValues values = new ContentValues();
  
        // on below line we are passing all values
        // along with its key and value pair.
        values.put(NAME_COL, courseName);
        values.put(DURATION_COL, courseDuration);
        values.put(DESCRIPTION_COL, courseDescription);
        values.put(TRACKS_COL, courseTracks);
  
        // after adding all values we are passing
        // content values to our table.
        db.insert(TABLE_NAME, null, values);
  
        // at last we are closing our
        // database after adding database.
        db.close();
    }
  
    // we have created a new method for reading all the courses.
    public ArrayList readCourses() {
        // on below line we are creating a
        // database for reading our database.
        SQLiteDatabase db = this.getReadableDatabase();
  
        // on below line we are creating a cursor with query to read data from database.
        Cursor cursorCourses = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
  
        // on below line we are creating a new array list.
        ArrayList courseModalArrayList = new ArrayList<>();
  
        // moving our cursor to first position.
        if (cursorCourses.moveToFirst()) {
            do {
                // on below line we are adding the data from cursor to our array list.
                courseModalArrayList.add(new CourseModal(cursorCourses.getString(1),
                                             cursorCourses.getString(4),
                                             cursorCourses.getString(2),
                                             cursorCourses.getString(3)));
            } while (cursorCourses.moveToNext());
            // moving our cursor to next.
        }
        // at last closing our cursor
        // and returning our array list.
        cursorCourses.close();
        return courseModalArrayList;
    }
  
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // this method is called to check if the table exists already.
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }
}


Java
readCourseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // opening a new activity via a intent.
                Intent i = new Intent(MainActivity.this, ViewCourses.class);
                startActivity(i);
        }
});


Java
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
  
import androidx.appcompat.app.AppCompatActivity;
  
public class MainActivity extends AppCompatActivity {
  
    // creating variables for our edittext, button and dbhandler
    private EditText courseNameEdt, courseTracksEdt, courseDurationEdt, courseDescriptionEdt;
    private Button addCourseBtn, readCourseBtn;
    private DBHandler dbHandler;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // initializing all our variables.
        courseNameEdt = findViewById(R.id.idEdtCourseName);
        courseTracksEdt = findViewById(R.id.idEdtCourseTracks);
        courseDurationEdt = findViewById(R.id.idEdtCourseDuration);
        courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription);
        addCourseBtn = findViewById(R.id.idBtnAddCourse);
        readCourseBtn = findViewById(R.id.idBtnReadCourse);
  
        // creating a new dbhandler class
        // and passing our context to it.
        dbHandler = new DBHandler(MainActivity.this);
  
        // below line is to add on click listener for our add course button.
        addCourseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
  
                // below line is to get data from all edit text fields.
                String courseName = courseNameEdt.getText().toString();
                String courseTracks = courseTracksEdt.getText().toString();
                String courseDuration = courseDurationEdt.getText().toString();
                String courseDescription = courseDescriptionEdt.getText().toString();
  
                // validating if the text fields are empty or not.
                if (courseName.isEmpty() && courseTracks.isEmpty() && courseDuration.isEmpty() && courseDescription.isEmpty()) {
                    Toast.makeText(MainActivity.this, "Please enter all the data..", Toast.LENGTH_SHORT).show();
                    return;
                }
  
                // on below line we are calling a method to add new
                // course to sqlite data and pass all our values to it.
                dbHandler.addNewCourse(courseName, courseDuration, courseDescription, courseTracks);
  
                // after adding the data we are displaying a toast message.
                Toast.makeText(MainActivity.this, "Course has been added.", Toast.LENGTH_SHORT).show();
                courseNameEdt.setText("");
                courseDurationEdt.setText("");
                courseTracksEdt.setText("");
                courseDescriptionEdt.setText("");
            }
        });
  
        readCourseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // opening a new activity via a intent.
                Intent i = new Intent(MainActivity.this, ViewCourses.class);
                startActivity(i);
            }
        });
    }
}


XML


  
    
  
        
        
  
        
  
            
            
  
  
            
            
  
        
  
        
        
          
    
  


Java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
  
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
  
import java.util.ArrayList;
  
public class CourseRVAdapter extends RecyclerView.Adapter {
  
    // variable for our array list and context
    private ArrayList courseModalArrayList;
    private Context context;
  
    // constructor
    public CourseRVAdapter(ArrayList courseModalArrayList, Context context) {
        this.courseModalArrayList = courseModalArrayList;
        this.context = context;
    }
  
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // on below line we are inflating our layout
        // file for our recycler view items.
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.course_rv_item, parent, false);
        return new ViewHolder(view);
    }
  
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        // on below line we are setting data 
        // to our views of recycler view item.
        CourseModal modal = courseModalArrayList.get(position);
        holder.courseNameTV.setText(modal.getCourseName());
        holder.courseDescTV.setText(modal.getCourseDescription());
        holder.courseDurationTV.setText(modal.getCourseDuration());
        holder.courseTracksTV.setText(modal.getCourseTracks());
    }
  
    @Override
    public int getItemCount() {
        // returning the size of our array list
        return courseModalArrayList.size();
    }
  
    public class ViewHolder extends RecyclerView.ViewHolder {
          
        // creating variables for our text views.
        private TextView courseNameTV, courseDescTV, courseDurationTV, courseTracksTV;
  
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            // initializing our text views
            courseNameTV = itemView.findViewById(R.id.idTVCourseName);
            courseDescTV = itemView.findViewById(R.id.idTVCourseDescription);
            courseDurationTV = itemView.findViewById(R.id.idTVCourseDuration);
            courseTracksTV = itemView.findViewById(R.id.idTVCourseTracks);
        }
    }
}


XML


  
    
    
  


Java
import android.os.Bundle;
  
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
  
import java.util.ArrayList;
  
public class ViewCourses extends AppCompatActivity {
  
    // creating variables for our array list, 
    // dbhandler, adapter and recycler view.
    private ArrayList courseModalArrayList;
    private DBHandler dbHandler;
    private CourseRVAdapter courseRVAdapter;
    private RecyclerView coursesRV;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_courses);
          
        // initializing our all variables.
        courseModalArrayList = new ArrayList<>();
        dbHandler = new DBHandler(ViewCourses.this);
          
        // getting our course array 
        // list from db handler class.
        courseModalArrayList = dbHandler.readCourses();
          
        // on below line passing our array lost to our adapter class.
        courseRVAdapter = new CourseRVAdapter(courseModalArrayList, ViewCourses.this);
        coursesRV = findViewById(R.id.idRVCourses);
          
        // setting layout manager for our recycler view.
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(ViewCourses.this, RecyclerView.VERTICAL, false);
        coursesRV.setLayoutManager(linearLayoutManager);
          
        // setting our adapter to recycler view.
        coursesRV.setAdapter(courseRVAdapter);
    }
}


现在下面是activity_main.xml文件的更新代码 添加以上代码段后。

XML格式



  
    
    
  
    
    
  
    
    
  
    
    
  
    
    

第2步:创建用于存储数据的模式类

导航到应用程序> Java >应用程序的程序包名称>右键单击它>新建> Java类,并将其命名为CourseModal,然后将以下代码添加到其中。在代码内部添加了注释,以更详细地了解代码。

Java

public class CourseModal {
  
    // variables for our coursename,
    // description, tracks and duration, id.
    private String courseName;
    private String courseDuration;
    private String courseTracks;
    private String courseDescription;
    private int id;
  
    // creating getter and setter methods
    public String getCourseName() {
        return courseName;
    }
  
    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }
  
    public String getCourseDuration() {
        return courseDuration;
    }
  
    public void setCourseDuration(String courseDuration) {
        this.courseDuration = courseDuration;
    }
  
    public String getCourseTracks() {
        return courseTracks;
    }
  
    public void setCourseTracks(String courseTracks) {
        this.courseTracks = courseTracks;
    }
  
    public String getCourseDescription() {
        return courseDescription;
    }
  
    public void setCourseDescription(String courseDescription) {
        this.courseDescription = courseDescription;
    }
  
    public int getId() {
        return id;
    }
  
    public void setId(int id) {
        this.id = id;
    }
  
    // constructor
    public CourseModal(String courseName, String courseDuration, String courseTracks, String courseDescription) {
        this.courseName = courseName;
        this.courseDuration = courseDuration;
        this.courseTracks = courseTracks;
        this.courseDescription = courseDescription;
    }
}

步骤5:更新我们的Java类以执行SQLite操作。

导航到应用程序> Java >应用程序的程序包名称> DBHandler,然后将以下代码添加到其中。在此,我们只是添加了一种新方法,用于从SQLite数据库读取所有课程。

Java

// we have created a new method for reading all the courses.
public ArrayList readCourses() {
        // on below line we are creating a
        // database for reading our database.
        SQLiteDatabase db = this.getReadableDatabase();
  
        // on below line we are creating a cursor with query to read data from database.
        Cursor cursorCourses = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
  
        // on below line we are creating a new array list.
        ArrayList courseModalArrayList = new ArrayList<>();
  
        // moving our cursor to first position.
        if (cursorCourses.moveToFirst()) {
            do {
                // on below line we are adding the data from cursor to our array list.
                courseModalArrayList.add(new CourseModal(cursorCourses.getString(1), 
                                             cursorCourses.getString(4), 
                                             cursorCourses.getString(2), 
                                             cursorCourses.getString(3)));
            } while (cursorCourses.moveToNext());
            // moving our cursor to next.
        }
        // at last closing our cursor 
        // and returning our array list.
        cursorCourses.close();
        return courseModalArrayList;
}

下面是DBHandler的更新代码。 Java文件 添加以上代码段后。

Java

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;
  
public class DBHandler extends SQLiteOpenHelper {
  
    // creating a constant variables for our database.
    // below variable is for our database name.
    private static final String DB_NAME = "coursedb";
  
    // below int is our database version
    private static final int DB_VERSION = 1;
  
    // below variable is for our table name.
    private static final String TABLE_NAME = "mycourses";
  
    // below variable is for our id column.
    private static final String ID_COL = "id";
  
    // below variable is for our course name column
    private static final String NAME_COL = "name";
  
    // below variable id for our course duration column.
    private static final String DURATION_COL = "duration";
  
    // below variable for our course description column.
    private static final String DESCRIPTION_COL = "description";
  
    // below variable is for our course tracks column.
    private static final String TRACKS_COL = "tracks";
  
    // creating a constructor for our database handler.
    public DBHandler(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }
  
    // below method is for creating a database by running a sqlite query
    @Override
    public void onCreate(SQLiteDatabase db) {
        // on below line we are creating
        // an sqlite query and we are
        // setting our column names
        // along with their data types.
        String query = "CREATE TABLE " + TABLE_NAME + " ("
                + ID_COL + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + NAME_COL + " TEXT,"
                + DURATION_COL + " TEXT,"
                + DESCRIPTION_COL + " TEXT,"
                + TRACKS_COL + " TEXT)";
  
        // at last we are calling a exec sql
        // method to execute above sql query
        db.execSQL(query);
    }
  
    // this method is use to add new course to our sqlite database.
    public void addNewCourse(String courseName, String courseDuration, String courseDescription, String courseTracks) {
  
        // on below line we are creating a variable for
        // our sqlite database and calling writable method
        // as we are writing data in our database.
        SQLiteDatabase db = this.getWritableDatabase();
  
        // on below line we are creating a
        // variable for content values.
        ContentValues values = new ContentValues();
  
        // on below line we are passing all values
        // along with its key and value pair.
        values.put(NAME_COL, courseName);
        values.put(DURATION_COL, courseDuration);
        values.put(DESCRIPTION_COL, courseDescription);
        values.put(TRACKS_COL, courseTracks);
  
        // after adding all values we are passing
        // content values to our table.
        db.insert(TABLE_NAME, null, values);
  
        // at last we are closing our
        // database after adding database.
        db.close();
    }
  
    // we have created a new method for reading all the courses.
    public ArrayList readCourses() {
        // on below line we are creating a
        // database for reading our database.
        SQLiteDatabase db = this.getReadableDatabase();
  
        // on below line we are creating a cursor with query to read data from database.
        Cursor cursorCourses = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
  
        // on below line we are creating a new array list.
        ArrayList courseModalArrayList = new ArrayList<>();
  
        // moving our cursor to first position.
        if (cursorCourses.moveToFirst()) {
            do {
                // on below line we are adding the data from cursor to our array list.
                courseModalArrayList.add(new CourseModal(cursorCourses.getString(1),
                                             cursorCourses.getString(4),
                                             cursorCourses.getString(2),
                                             cursorCourses.getString(3)));
            } while (cursorCourses.moveToNext());
            // moving our cursor to next.
        }
        // at last closing our cursor
        // and returning our array list.
        cursorCourses.close();
        return courseModalArrayList;
    }
  
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // this method is called to check if the table exists already.
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }
}

第6步:创建一个新活动以显示我们的课程列表

要创建新的活动,我们必须导航至应用程序> Java >应用程序的包名称>右键单击包名称>新建>空活动,并将您的活动命名为ViewCourses并创建新的活动。确保选择空活动

步骤7:使用MainActivity。 Java文件

由于我们在activity_main.xml文件中添加了一个新按钮,因此我们必须在MainActivity中将setOnClickListener()添加到该按钮。 Java文件。

Java

readCourseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // opening a new activity via a intent.
                Intent i = new Intent(MainActivity.this, ViewCourses.class);
                startActivity(i);
        }
});

以下是MainActivity的更新代码。 Java文件 添加以上代码段后。

Java

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
  
import androidx.appcompat.app.AppCompatActivity;
  
public class MainActivity extends AppCompatActivity {
  
    // creating variables for our edittext, button and dbhandler
    private EditText courseNameEdt, courseTracksEdt, courseDurationEdt, courseDescriptionEdt;
    private Button addCourseBtn, readCourseBtn;
    private DBHandler dbHandler;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // initializing all our variables.
        courseNameEdt = findViewById(R.id.idEdtCourseName);
        courseTracksEdt = findViewById(R.id.idEdtCourseTracks);
        courseDurationEdt = findViewById(R.id.idEdtCourseDuration);
        courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription);
        addCourseBtn = findViewById(R.id.idBtnAddCourse);
        readCourseBtn = findViewById(R.id.idBtnReadCourse);
  
        // creating a new dbhandler class
        // and passing our context to it.
        dbHandler = new DBHandler(MainActivity.this);
  
        // below line is to add on click listener for our add course button.
        addCourseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
  
                // below line is to get data from all edit text fields.
                String courseName = courseNameEdt.getText().toString();
                String courseTracks = courseTracksEdt.getText().toString();
                String courseDuration = courseDurationEdt.getText().toString();
                String courseDescription = courseDescriptionEdt.getText().toString();
  
                // validating if the text fields are empty or not.
                if (courseName.isEmpty() && courseTracks.isEmpty() && courseDuration.isEmpty() && courseDescription.isEmpty()) {
                    Toast.makeText(MainActivity.this, "Please enter all the data..", Toast.LENGTH_SHORT).show();
                    return;
                }
  
                // on below line we are calling a method to add new
                // course to sqlite data and pass all our values to it.
                dbHandler.addNewCourse(courseName, courseDuration, courseDescription, courseTracks);
  
                // after adding the data we are displaying a toast message.
                Toast.makeText(MainActivity.this, "Course has been added.", Toast.LENGTH_SHORT).show();
                courseNameEdt.setText("");
                courseDurationEdt.setText("");
                courseTracksEdt.setText("");
                courseDescriptionEdt.setText("");
            }
        });
  
        readCourseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // opening a new activity via a intent.
                Intent i = new Intent(MainActivity.this, ViewCourses.class);
                startActivity(i);
            }
        });
    }
}

步骤8:为我们的RecyclerView项目创建一个新的布局文件

导航到应用程序> res>布局>右键单击它>新建>布局资源文件,并将其命名为course_rv_item,然后将以下代码添加到其中。

XML格式



  
    
  
        
        
  
        
  
            
            
  
  
            
            
  
        
  
        
        
          
    
  

第9步:创建一个Adapter类,用于将数据设置到我们的RecyclerView项目中

导航到应用程序> Java >应用程序的程序包名称>右键单击它>新建> Java类,并将其命名为CourseRVAdapter,然后将以下代码添加到其中。在代码内部添加了注释,以更详细地了解代码。

Java

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
  
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
  
import java.util.ArrayList;
  
public class CourseRVAdapter extends RecyclerView.Adapter {
  
    // variable for our array list and context
    private ArrayList courseModalArrayList;
    private Context context;
  
    // constructor
    public CourseRVAdapter(ArrayList courseModalArrayList, Context context) {
        this.courseModalArrayList = courseModalArrayList;
        this.context = context;
    }
  
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // on below line we are inflating our layout
        // file for our recycler view items.
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.course_rv_item, parent, false);
        return new ViewHolder(view);
    }
  
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        // on below line we are setting data 
        // to our views of recycler view item.
        CourseModal modal = courseModalArrayList.get(position);
        holder.courseNameTV.setText(modal.getCourseName());
        holder.courseDescTV.setText(modal.getCourseDescription());
        holder.courseDurationTV.setText(modal.getCourseDuration());
        holder.courseTracksTV.setText(modal.getCourseTracks());
    }
  
    @Override
    public int getItemCount() {
        // returning the size of our array list
        return courseModalArrayList.size();
    }
  
    public class ViewHolder extends RecyclerView.ViewHolder {
          
        // creating variables for our text views.
        private TextView courseNameTV, courseDescTV, courseDurationTV, courseTracksTV;
  
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            // initializing our text views
            courseNameTV = itemView.findViewById(R.id.idTVCourseName);
            courseDescTV = itemView.findViewById(R.id.idTVCourseDescription);
            courseDurationTV = itemView.findViewById(R.id.idTVCourseDuration);
            courseTracksTV = itemView.findViewById(R.id.idTVCourseTracks);
        }
    }
}

步骤10:使用activity_view_course.xml文件

导航至应用程序> res>布局> activity_view_course.xml,然后将以下代码添加到该文件中。以下是activity_view_course.xml文件的代码。

XML格式



  
    
    
  

步骤11:使用ViewCourses。 Java文件

导航到应用程序> Java >您的应用程序包名称> ViewCourses。 Java文件,并向其中添加以下代码。在代码内部添加了注释,以更详细地了解代码。

Java

import android.os.Bundle;
  
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
  
import java.util.ArrayList;
  
public class ViewCourses extends AppCompatActivity {
  
    // creating variables for our array list, 
    // dbhandler, adapter and recycler view.
    private ArrayList courseModalArrayList;
    private DBHandler dbHandler;
    private CourseRVAdapter courseRVAdapter;
    private RecyclerView coursesRV;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_courses);
          
        // initializing our all variables.
        courseModalArrayList = new ArrayList<>();
        dbHandler = new DBHandler(ViewCourses.this);
          
        // getting our course array 
        // list from db handler class.
        courseModalArrayList = dbHandler.readCourses();
          
        // on below line passing our array lost to our adapter class.
        courseRVAdapter = new CourseRVAdapter(courseModalArrayList, ViewCourses.this);
        coursesRV = findViewById(R.id.idRVCourses);
          
        // setting layout manager for our recycler view.
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(ViewCourses.this, RecyclerView.VERTICAL, false);
        coursesRV.setLayoutManager(linearLayoutManager);
          
        // setting our adapter to recycler view.
        coursesRV.setAdapter(courseRVAdapter);
    }
}

现在运行您的应用程序,并查看该应用程序的输出。在读取数据之前,请确保添加数据。

输出:

下面是执行读取操作后的完整项目文件结构: