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

📅  最后修改于: 2021-05-08 19:33:31             🧑  作者: Mango

在上一篇文章中,我们已经看到将数据添加到Android中的领域数据库中。在本文中,我们将看一下如何从Android应用程序中的Realm数据库中读取此数据。

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

在本文中,我们将简单地添加一个Button,以在我们在上一篇文章中创建的项目中打开一个新活动。在新活动中,我们将以RecyclerView的形式显示数据。下面是视频,我们将在其中观看我们将要构建的内容。

分步实施

步骤1:使用activity_main.xml文件

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

XML


XML


 
    
    
 
    
    
 
    
    
 
    
    
 
    
    


Java
readCourseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(MainActivity.this, ReadCoursesActivity.class);
                startActivity(i);
        }
});


Java
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
 
import androidx.appcompat.app.AppCompatActivity;
 
import io.realm.Realm;
 
public class MainActivity extends AppCompatActivity {
 
    // creating variables for our edit text
    private EditText courseNameEdt, courseDurationEdt, courseDescriptionEdt, courseTracksEdt;
    private Realm realm;
    private Button readCourseBtn;
 
    // creating a strings for storing
    // our values from edittext fields.
    private String courseName, courseDuration, courseDescription, courseTracks;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // initializing our edittext and buttons
        realm = Realm.getDefaultInstance();
        courseNameEdt = findViewById(R.id.idEdtCourseName);
        courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription);
        courseDurationEdt = findViewById(R.id.idEdtCourseDuration);
        readCourseBtn = findViewById(R.id.idBtnReadData);
 
        // creating variable for button
        Button submitCourseBtn = findViewById(R.id.idBtnAddCourse);
        courseTracksEdt = findViewById(R.id.idEdtCourseTracks);
        submitCourseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
 
                // getting data from edittext fields.
                courseName = courseNameEdt.getText().toString();
                courseDescription = courseDescriptionEdt.getText().toString();
                courseDuration = courseDurationEdt.getText().toString();
                courseTracks = courseTracksEdt.getText().toString();
 
                // validating the text fields if empty or not.
                if (TextUtils.isEmpty(courseName)) {
                    courseNameEdt.setError("Please enter Course Name");
                } else if (TextUtils.isEmpty(courseDescription)) {
                    courseDescriptionEdt.setError("Please enter Course Description");
                } else if (TextUtils.isEmpty(courseDuration)) {
                    courseDurationEdt.setError("Please enter Course Duration");
                } else if (TextUtils.isEmpty(courseTracks)) {
                    courseTracksEdt.setError("Please enter Course Tracks");
                } else {
                    // calling method to add data to Realm database..
                    addDataToDatabase(courseName, courseDescription, courseDuration, courseTracks);
                    Toast.makeText(MainActivity.this, "Course added to database..", Toast.LENGTH_SHORT).show();
                    courseNameEdt.setText("");
                    courseDescriptionEdt.setText("");
                    courseDurationEdt.setText("");
                    courseTracksEdt.setText("");
                }
            }
        });
 
        readCourseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(MainActivity.this, ReadCoursesActivity.class);
                startActivity(i);
            }
        });
    }
 
    private void addDataToDatabase(String courseName, String courseDescription, String courseDuration, String courseTracks) {
 
        // on below line we are creating
        // a variable for our modal class.
        DataModal modal = new DataModal();
 
        // on below line we are getting id for the course which we are storing.
        Number id = realm.where(DataModal.class).max("id");
 
        // on below line we are
        // creating a variable for our id.
        long nextId;
 
        // validating if id is null or not.
        if (id == null) {
            // if id is null
            // we are passing it as 1.
            nextId = 1;
        } else {
            // if id is not null then
            // we are incrementing it by 1
            nextId = id.intValue() + 1;
        }
        // on below line we are setting the
        // data entered by user in our modal class.
        modal.setId(nextId);
        modal.setCourseDescription(courseDescription);
        modal.setCourseName(courseName);
        modal.setCourseDuration(courseDuration);
        modal.setCourseTracks(courseTracks);
 
        // on below line we are calling a method to execute a transaction.
        realm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                // inside on execute method we are calling a method
                // to copy to real m database from our modal class.
                realm.copyToRealm(modal);
            }
        });
    }
}


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.List;
 
public class CourseRVAdapter extends RecyclerView.Adapter {
     
    // variable for our array list and context
    private List dataModalArrayList;
    private Context context;
 
    public CourseRVAdapter(List dataModalArrayList, Context context) {
        this.dataModalArrayList = dataModalArrayList;
        this.context = context;
    }
 
    @NonNull
    @Override
    public CourseRVAdapter.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 CourseRVAdapter.ViewHolder holder, int position) {
        DataModal modal = dataModalArrayList.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() {
        return dataModalArrayList.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;
import java.util.List;
 
import io.realm.Realm;
 
public class ReadCoursesActivity extends AppCompatActivity {
     
    List dataModals;
     
    // creating variables for realm,
    // recycler view, adapter and our list.
    private Realm realm;
    private RecyclerView coursesRV;
    private CourseRVAdapter courseRVAdapter;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_read_courses);
         
        // on below lines we are initializing our variables.
        coursesRV = findViewById(R.id.idRVCourses);
        realm = Realm.getDefaultInstance();
        dataModals = new ArrayList<>();
         
        // calling a method to load
        // our recycler view with data.
        prepareRecyclerView();
    }
 
    private void prepareRecyclerView() {
        // on below line we are getting data from realm database in our list.
        dataModals = realm.where(DataModal.class).findAll();
        // on below line we are adding our list to our adapter class.
        courseRVAdapter = new CourseRVAdapter(dataModals, this);
        // on below line we are setting layout manager to our recycler view.
        coursesRV.setLayoutManager(new LinearLayoutManager(this));
        // at last we are setting adapter to our recycler view.
        coursesRV.setAdapter(courseRVAdapter);
    }
}


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

XML格式



 
    
    
 
    
    
 
    
    
 
    
    
 
    
    

步骤2:使用MainActivity。 Java文件

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

Java

readCourseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(MainActivity.this, ReadCoursesActivity.class);
                startActivity(i);
        }
});

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

Java

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
 
import androidx.appcompat.app.AppCompatActivity;
 
import io.realm.Realm;
 
public class MainActivity extends AppCompatActivity {
 
    // creating variables for our edit text
    private EditText courseNameEdt, courseDurationEdt, courseDescriptionEdt, courseTracksEdt;
    private Realm realm;
    private Button readCourseBtn;
 
    // creating a strings for storing
    // our values from edittext fields.
    private String courseName, courseDuration, courseDescription, courseTracks;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // initializing our edittext and buttons
        realm = Realm.getDefaultInstance();
        courseNameEdt = findViewById(R.id.idEdtCourseName);
        courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription);
        courseDurationEdt = findViewById(R.id.idEdtCourseDuration);
        readCourseBtn = findViewById(R.id.idBtnReadData);
 
        // creating variable for button
        Button submitCourseBtn = findViewById(R.id.idBtnAddCourse);
        courseTracksEdt = findViewById(R.id.idEdtCourseTracks);
        submitCourseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
 
                // getting data from edittext fields.
                courseName = courseNameEdt.getText().toString();
                courseDescription = courseDescriptionEdt.getText().toString();
                courseDuration = courseDurationEdt.getText().toString();
                courseTracks = courseTracksEdt.getText().toString();
 
                // validating the text fields if empty or not.
                if (TextUtils.isEmpty(courseName)) {
                    courseNameEdt.setError("Please enter Course Name");
                } else if (TextUtils.isEmpty(courseDescription)) {
                    courseDescriptionEdt.setError("Please enter Course Description");
                } else if (TextUtils.isEmpty(courseDuration)) {
                    courseDurationEdt.setError("Please enter Course Duration");
                } else if (TextUtils.isEmpty(courseTracks)) {
                    courseTracksEdt.setError("Please enter Course Tracks");
                } else {
                    // calling method to add data to Realm database..
                    addDataToDatabase(courseName, courseDescription, courseDuration, courseTracks);
                    Toast.makeText(MainActivity.this, "Course added to database..", Toast.LENGTH_SHORT).show();
                    courseNameEdt.setText("");
                    courseDescriptionEdt.setText("");
                    courseDurationEdt.setText("");
                    courseTracksEdt.setText("");
                }
            }
        });
 
        readCourseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(MainActivity.this, ReadCoursesActivity.class);
                startActivity(i);
            }
        });
    }
 
    private void addDataToDatabase(String courseName, String courseDescription, String courseDuration, String courseTracks) {
 
        // on below line we are creating
        // a variable for our modal class.
        DataModal modal = new DataModal();
 
        // on below line we are getting id for the course which we are storing.
        Number id = realm.where(DataModal.class).max("id");
 
        // on below line we are
        // creating a variable for our id.
        long nextId;
 
        // validating if id is null or not.
        if (id == null) {
            // if id is null
            // we are passing it as 1.
            nextId = 1;
        } else {
            // if id is not null then
            // we are incrementing it by 1
            nextId = id.intValue() + 1;
        }
        // on below line we are setting the
        // data entered by user in our modal class.
        modal.setId(nextId);
        modal.setCourseDescription(courseDescription);
        modal.setCourseName(courseName);
        modal.setCourseDuration(courseDuration);
        modal.setCourseTracks(courseTracks);
 
        // on below line we are calling a method to execute a transaction.
        realm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                // inside on execute method we are calling a method
                // to copy to real m database from our modal class.
                realm.copyToRealm(modal);
            }
        });
    }
}

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

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

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

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

XML格式



 
    
 
        
        
 
        
 
            
            
             
            
            
 
        
 
        
        
 
    
 

步骤5:创建一个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.List;
 
public class CourseRVAdapter extends RecyclerView.Adapter {
     
    // variable for our array list and context
    private List dataModalArrayList;
    private Context context;
 
    public CourseRVAdapter(List dataModalArrayList, Context context) {
        this.dataModalArrayList = dataModalArrayList;
        this.context = context;
    }
 
    @NonNull
    @Override
    public CourseRVAdapter.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 CourseRVAdapter.ViewHolder holder, int position) {
        DataModal modal = dataModalArrayList.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() {
        return dataModalArrayList.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);
        }
    }
}

步骤6:使用activity_read_courses.xml文件

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

XML格式



 
    
    
     

步骤7:使用ReadCoursesActivity。 Java文件

导航到应用程序> Java >您的应用程序包名称> ReadCoursesActivity。 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;
import java.util.List;
 
import io.realm.Realm;
 
public class ReadCoursesActivity extends AppCompatActivity {
     
    List dataModals;
     
    // creating variables for realm,
    // recycler view, adapter and our list.
    private Realm realm;
    private RecyclerView coursesRV;
    private CourseRVAdapter courseRVAdapter;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_read_courses);
         
        // on below lines we are initializing our variables.
        coursesRV = findViewById(R.id.idRVCourses);
        realm = Realm.getDefaultInstance();
        dataModals = new ArrayList<>();
         
        // calling a method to load
        // our recycler view with data.
        prepareRecyclerView();
    }
 
    private void prepareRecyclerView() {
        // on below line we are getting data from realm database in our list.
        dataModals = realm.where(DataModal.class).findAll();
        // on below line we are adding our list to our adapter class.
        courseRVAdapter = new CourseRVAdapter(dataModals, this);
        // on below line we are setting layout manager to our recycler view.
        coursesRV.setLayoutManager(new LinearLayoutManager(this));
        // at last we are setting adapter to our recycler view.
        coursesRV.setAdapter(courseRVAdapter);
    }
}

现在运行您的应用程序,并查看该应用程序的输出。

输出:

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