【问题标题】:How to select all records from SQL database and put it in Listview Android如何从 SQL 数据库中选择所有记录并将其放入 Listview Android
【发布时间】: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


    【解决方案1】:

    如果您的数据存储在数据库服务器(Mysql、oracle 等)中,您必须先用 Php 编写一个 Web 服务。该特定服务将从数据库中提取您的所有数据。然后,您必须编写一个 Web 逻辑,将提取的数据转换为 xml 或 json,因为只有这些格式的数据才能在网络中传输。如果您有多重数据,那么您也可以从该数据中创建 json 数组。 当android客户端通过Retrofit调用你的web服务时,它会自动在响应中获取json。那个json可以解析成java的ArrayList类。现在,您可以按照将列表数据填充到 ListView 中的基本步骤,在 ListView 中显示所有数据。

    【讨论】:

      【解决方案2】:
      @Override
      public void onCreate(SQLiteDatabase db) {
          // TODO Auto-generated method stub
      
      
          db.execSQL("CREATE TABLE " + TABLE_NAME
                  + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, " + key_msg + " STRING, " + key_isread + " STRING)");
      
      
      }
      
      @Override
      public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
          // TODO Auto-generated method stub
          db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
          onCreate(db);
      }
      

      //*************************--------插入 GCM 消息---------* *************************//

      public void insert_GCM_receive_data(String msg) {
      
          String value;
          SQLiteDatabase db = getWritableDatabase();
      
          ContentValues cv = new ContentValues();
      
          cv.put(key_msg, msg);
          cv.put(key_isread, "N");
      
          value = cv.toString();
      
          db.insert(TABLE_NAME, null, cv);
          System.out.println("/n******this is temp table name  " + TABLE_NAME + "\nthis is temp msg  " + cv + "\nmsg" + msg + "\nval" + value);
      
          db.close();
      
      }
      

      //--------------------------------------------- --------------------------------------------------//

      //**********************----------获取警报数据---------- --******************************// 公共 ArrayList get_alert_msg() {

          ArrayList<String> name = new ArrayList<String>();
          try {
              SQLiteDatabase db = getWritableDatabase();
              Cursor c = null;
              c = db.rawQuery("SELECT  * FROM " + TABLE_NAME, null);
      
              System.out.println(c);
      
              for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
      
                  String str_id = c.getString(0);
                  String str_msg = c.getString(1);
                  String str_read = c.getString(2);
                  Log.e("value", str_id + str_msg + str_read);
      
                  HashMap<String, String> hm = new HashMap<String, String>();
                  hm.put("msg", str_msg);
                  hm.put("isread", str_read);
      
      
                  name.add(str_msg);
      
      
              }
              c.close();
              db.close();
      
          } catch (Exception e) {
              Log.e("this not work", "" + e);
          }
      
          return name;
      }`
      

      //调用方法如

      dbHelper = new Database_for_Received_data(this.getActivity()); name= new ArrayList(dbHelper.get_alert_msg());

      使用“select * from table_name”之类的查询......然后在您的数据库类中扩展 SQLiteopenhelper。

      它来自于使用数据存储、获取和操作目的..

      【讨论】:

        猜你喜欢
        • 2023-04-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-31
        • 2017-12-02
        • 2015-07-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多