从 android 中的 sqlite 读取日期

reading the date from sqlite in android

我在 sqlite 中存储一些日期,当我尝试检索数据时,它返回 null。

private ArrayList<String> file_list = new ArrayList<>();

     @Override
     protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

         ArrayList<String> _list = db.get_file
              (String.valueOf(myFiles.get(position).getId()), file_list);
         Log.e("TAG","_list " + _list);

         case R.id.get_file:
            boolean save_file = db.add_file(String.valueOf(myFiles.get(position).getId()),
                                 file_list);
                    if (save_file){
                        Toast.makeText(this, "saved successfully", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(this, "saved failed", Toast.LENGTH_SHORT).show();
                    }

    public ArrayList<String> get_file(String id, ArrayList<String> arrayList){

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery("SELECT " + COL_FILE + " FROM "
            +TABLE_NAME+" WHERE " + _ID +" =? " , new String[] {String.valueOf(id)});

    if(cursor.moveToFirst()){
        return arrayList;
    } else {
        return null;
    }
}

 public TrackGroupArray read_tga_file(String id, TrackGroupArray tga)
    {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT " + TGA_FILE + " FROM "
                +TABLE_NAME+" WHERE " + _ID +" =? " , new String[] {String.valueOf(id)});

        if(cursor.moveToFirst()){
            return tga;
        } else {
            return null;
        }
    }
  

   TrackGroupArray read_tga = db.read_tga_file(String.valueOf(myFiles.get(position).getId()),
                    trackGroupArray);

     

我每次保存文件,都保存成功,我查了db,文件在。但是当我想取回它时,Log.e("TAG","_list " + _list); returns null.

你的get_File方法,即使有一行并且moveToFirst成功,也总是return null 因为如果一行是 located/selected 你除了 return 一个 un-instantiated arrayList.

什么都不做

你需要

  • a) 实例化arrayList(否则为null)然后
  • b) 为存在的每一行添加元素到 arrayList

所以像 :-

   @SuppressLint("Range")
   public ArrayList<String> get_file(String id, ArrayList<String> arrayList) {

      SQLiteDatabase db = this.getReadableDatabase();
      Cursor cursor = db.rawQuery("SELECT " + COL_FILE + " FROM "
              + TABLE_NAME + " WHERE " + _ID + " =? ", new String[]{String.valueOf(id)});

      ArrayList<String> rv = new ArrayList<>(); //<<<<< A instantiate the ArrayList<String>
      
      /* Loop through the returned row(s) if any */
      while (cursor.moveToNext()) {
         /* for each iteration add an element to rv (the ArrayList) */
         rv.add(cursor.getString(cursor.getColumnIndex(COL_FILE)));
      }
      cursor.close(); //<<<<< should ALWAYS close Cursors when done with them
      return rv; // return the arraylist
   }