在记录时我发现我得到一个空列表
我是初学者,所以请让我知道我犯了什么错误,我真的需要让它工作。
package com.example.hospital;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.widget.Adapter;
import android.widget.Toast;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.helper.widget.Carousel;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.hospital.ui.main.DoctorAdapter;
import org.bson.Document;
import io.realm.OrderedRealmCollection;
import io.realm.Realm;
import io.realm.RealmAsyncTask;
import io.realm.RealmConfiguration;
import io.realm.mongodb.App;
import io.realm.mongodb.AppConfiguration;
import io.realm.mongodb.Credentials;
import io.realm.mongodb.User;
import io.realm.mongodb.mongo.MongoClient;
import io.realm.mongodb.mongo.MongoCollection;
import io.realm.mongodb.mongo.MongoDatabase;
public class docselect extends AppCompatActivity {
String Appid = "appid";
App app;
Realm realm;
DoctorAdapter adapter;
RecyclerView recyclerView;
@SuppressLint("MissingInflatedId")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_docselect);
try {
Realm.init(this);
RealmConfiguration config = new RealmConfiguration.Builder()
.schemaVersion(1)
.migration(new MyRealmMigration())
.build();
Realm.setDefaultConfiguration(config);
realm = Realm.getDefaultInstance();
} catch (Exception e) {
Log.e("DocSelectActivity", "Error initializing Realm", e);
Toast.makeText(docselect.this,"Error",Toast.LENGTH_SHORT).show();
}
app = new App(new AppConfiguration.Builder(Appid).build());
recyclerView = findViewById(R.id.recyclerView);
setupRecyclerView();
}
private void setupRecyclerView() {
OrderedRealmCollection<Doctor> doctors = realm.where(Doctor.class).findAll();
Log.d("DoctorAdapter", "Number of doctors: " + doctors.size());
adapter = new DoctorAdapter(doctors);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter.notifyDataSetChanged();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (realm != null) {
realm.close();
}
}
}
Doctor 类(它是 MongoDB 本身为指定模式提供的,意味着它是自动生成的,我只是复制粘贴它)。
package com.example.hospital;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
import io.realm.annotations.Required;
import org.bson.types.ObjectId;
public class Doctor extends RealmObject {
@PrimaryKey
@Required
private ObjectId _id;
private String emp_id;
private String name;
private String specialisation;
// Standard getters & setters
public ObjectId getId() { return _id; }
public void setId(ObjectId _id) { this._id = _id; }
public String getEmpId() { return emp_id; }
public void setEmpId(String emp_id) { this.emp_id = emp_id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getSpecialisation() { return specialisation; }
public void setSpecialisation(String specialisation) { this.specialisation = specialisation; }
}
DoctorAdapter 类
package com.example.hospital.ui.main;
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 com.example.hospital.Doctor;
import com.example.hospital.R;
import io.realm.OrderedRealmCollection;
public class DoctorAdapter extends RecyclerView.Adapter<DoctorAdapter.ViewHolder> {
private OrderedRealmCollection<Doctor> data;
public DoctorAdapter(OrderedRealmCollection<Doctor> data) {
this.data = data;
setHasStableIds(true); // If your Doctor model has a primary key
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_doctor, parent, false);
return new ViewHolder(itemView);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Doctor doctor = data.get(position);
holder.textViewName.setText(doctor.getName());
holder.textViewSpecialisation.setText(doctor.getSpecialisation());
// Bind other details here
}
@Override
public int getItemCount() {
return data != null ? data.size() : 0;
}
static class ViewHolder extends RecyclerView.ViewHolder {
TextView textViewName;
TextView textViewSpecialisation;
ViewHolder(View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.textViewName);
textViewSpecialisation = itemView.findViewById(R.id.textViewSpecialisation);
}
}
}
我阅读了文档,但那太复杂了,对我没有多大帮助。 我的数据库名称是
maindb
,集合名称是 doctors
我也想过使用 queryfilter,但放弃了这种太讨厌的想法,如果那是更好的方法,请告诉我。
我的应用程序的示例(旧版本现在在 kotlin 中):
将指令插入项目的 build.gradle 文件中
dependencies {
classpath 'com.android.tools.build:gradle:8.1.3' }
在应用程序的 build.gradle 文件中,在文件开头使用以下指令调用插件
应用插件:'realm-android'
领域初始化
public class MyApplication extends Application {
Realm.init(this);
RealmConfiguration realmConfiguration =
new RealmConfiguration.Builder()
.name("default.realm")
.schemaVersion(3)
.migration(new customRealmMigration())
// .deleteRealmIfMigrationNeeded()
.build();
Realm.setDefaultConfiguration(realmConfiguration); }
AndroidManifest.xml 文件内
<application
android:name="com.sampietro.NaiveAAC.activities.Main.MyApplication"
通过扩展 RealmObject 创建类
public class Images extends RealmObject {
/**
* word or phrase.
*/
private String descrizione;
/**
* contains the file path (originally contained the uri).
*/
private String uri;
/*
* getter, setter and other methods
*/
/**
* get <code>descrizione</code>.
*
* @return descrizione string data to get
*/
public String getDescrizione() {
return descrizione;
}
/**
* get <code>uri</code>.
*
* @return uri string file path to get
*/
public String getUri() {
return uri;
}
//
/**
* set <code>descrizione</code>.
*
* @param descrizione string data to set
*/
public void setDescrizione(String descrizione) {
this.descrizione = descrizione;
}
/**
* set <code>uri</code>.
*
* @param uri string file path to set
*/
public void setUri(String uri) {
this.uri = uri;
}
}
将对象插入数据库后,使用片段、适配器和列表视图显示我的案例中的内容
public class ImagesFragment extends Fragment {
public View rootView;
public TextView textView;
public Context ctext;
/**
* <h1>onFragmentEventListenerSettings</h1>
* <p><b>onFragmentEventListenerSettings</b>
* interface used to refer to the Activity without having to explicitly use its class
* <p>
*
* @see #onAttach
*/
public interface onFragmentEventListenerSettings
{
// insert here any references to the Settings Activity
void receiveResultSettings(View v);
}
//
public onFragmentEventListenerSettings listener=null;
/**
* listener setting for settings activity callbacks and context annotation
*
* @see androidx.fragment.app.Fragment#onAttach
*/
@Override
public void onAttach (Context context)
{
super.onAttach(context);
Activity activity = (Activity) context;
//
listener=(onFragmentEventListenerSettings) activity;
//
ctext = context;
}
//
private Realm realm;
//
private ListView listView=null;
private ImagesAdapter adapter;
/**
* prepares the ui also using a listview and makes the callback to the activity
*
* @see androidx.fragment.app.Fragment#onCreateView
* @see com.example.a20210823simsim.activities.Graphics.Images
* @see com.example.a20210823simsim.activities.Graphics.ImagesAdapter
*/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
rootView = inflater.inflate(R.layout.activity_settings_images, container, false);
// logic of fragment
realm= Realm.getDefaultInstance();
// ListView
// 1) we get a reference to the data structure through the RealmResults class which constitutes
// the query result set and is an iterable collection accessible with Java constructs:
// for loop, basic access to position and Iterator.
// The approach for realm queries is object-oriented.
// The where method will retrieve the objects from the specified class and the result will
// be treated with filtrate by other specific methods.
// At the end of the selection configuration, the findAll method will be invoked to retrieve
// all the corresponding results.
// 2) we instantiate an Adapter by assigning it, the collection and the layout related to
// each single row
// 3) we retrieve the ListView prepared in the layout and assign it the reference to the adapter
// which will be your View "supplier".
RealmResults<Images> results = realm.where(Images.class).findAll();
//
listView=(ListView) rootView.findViewById(R.id.listview);
//
adapter=new ImagesAdapter(ctext, results, listView);
//
listView.setAdapter(adapter);
//
listener.receiveResultSettings(rootView);
//
return rootView;
}
}