如何从 sqlite 数据库中检索数据并显示在片段中
How to retrieve data from sqlite database and display in a fragment
我想将我的数据库中的数据显示到片段中的 EditText 中。
这是我的编码:
DBhelper
public void onCreate(SQLiteDatabase db) {
db.execSQL("Create table Tenant_login(name text, email text primary key, password text)" );
}
检索数据
public Cursor alldata() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor= db.rawQuery("Select * from Tenant_login",null);
return cursor;
}
片段class
public class profileFragement extends Fragment {
DatabaseHelper db;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.profile_fragment, container, false);
EditText et = (EditText) view.findViewById(R.id.text);
et.setVisibility(view.VISIBLE);
db = new DatabaseHelper(getActivity());
Cursor cursor = db.alldata();
et.setText(""+ cursor.getString(0));
return view;
}
}
此编码没有给我任何结果。
请帮帮我。
您必须将游标的索引移动到第一行(如果存在):
if (cursor.moveToFirst()) {
et.setText("" + cursor.getString(0));
}
我想将我的数据库中的数据显示到片段中的 EditText 中。
这是我的编码:
DBhelper
public void onCreate(SQLiteDatabase db) {
db.execSQL("Create table Tenant_login(name text, email text primary key, password text)" );
}
检索数据
public Cursor alldata() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor= db.rawQuery("Select * from Tenant_login",null);
return cursor;
}
片段class
public class profileFragement extends Fragment {
DatabaseHelper db;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.profile_fragment, container, false);
EditText et = (EditText) view.findViewById(R.id.text);
et.setVisibility(view.VISIBLE);
db = new DatabaseHelper(getActivity());
Cursor cursor = db.alldata();
et.setText(""+ cursor.getString(0));
return view;
}
}
此编码没有给我任何结果。 请帮帮我。
您必须将游标的索引移动到第一行(如果存在):
if (cursor.moveToFirst()) {
et.setText("" + cursor.getString(0));
}