【发布时间】:2017-01-10 15:06:32
【问题描述】:
我正在尝试学习如何为 android 应用程序从数据库中存储和获取记录,我可以进行更新、插入、删除等操作,但是我在获取多条记录时遇到问题,我想问一下如何获取所有记录从 localhost phpmyadmin 中的表并使用共享首选项将结果导出到 android 应用程序中的列表视图中,这是我的 php 函数代码:
public function getLessons($teacher) {
$sql = 'SELECT * FROM lessons WHERE teacher = :teacher';
$query = $this -> conn -> prepare($sql);
$query -> execute(array(':teacher' => $teacher));
$data = $query -> fetchObject();
$lesson["title"] = $data -> title; // im not sure if this is true
$lesson["maxstudent"] = $data -> maxstudent; // im not sure if this is true
$lesson["about"] = $data -> about; // im not sure if this is true
return $lesson;// the result of sql query will be more than one record
}
上面的代码将检索查询的结果,但我不确定代码,如果结果多于一条记录,教训的结果是什么?那是一个字符串数组吗?这是我在数据库代码中获取所有课程的 java 方法:
private void getLessonProcess(String teacher){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RequestInterface requestInterface = retrofit.create(RequestInterface.class);
Lesson lesson = new Lesson();// its Java Class containing title,maxstudent and about
lesson.setTeacher(teacher);// we set the teacher, so only specific teacher's lesson will be given as a result
ServerRequest request = new ServerRequest();// server request is a class to connect to localhost
request.setOperation(Constants.LESSONS);// constants.LESSONS is 'getlessons' the key that i use to trigger the SQL Query above
request.setLesson(lesson);
Call<ServerResponse> response = requestInterface.operation(request);
response.enqueue(new Callback<ServerResponse>() {
@Override
public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {
ServerResponse resp = response.body();
Snackbar.make(getView(), resp.getMessage(), Snackbar.LENGTH_LONG).show();
if(resp.getResult().equals(Constants.SUCCESS)){
SharedPreferences.Editor editor = pref.edit();
editor.putString(Constants.LESSONS,resp.getLesson().getLessontitle());
editor.putString(???,resp.getLesson().getMaxstudent());
editor.putString(???,resp.getLesson().getAbout());
?????????? // What should i write here?
//in code above it will only put one record of the database and put it in shared preference
editor.apply();
}
}
@Override
public void onFailure(Call<ServerResponse> call, Throwable t) {
Log.d(Constants.TAG,"failed");
Snackbar.make(getView(), t.getLocalizedMessage(), Snackbar.LENGTH_LONG).show();
}
});
}
是否可以遍历所有数据并将其放入数组列表中,以便我可以使用适配器在 ListView 中显示结果?谢谢你
【问题讨论】:
标签: php android mysql database listview