SQLite数据库Unicode不可读

时间:2018-01-21 18:05:47

标签: android android-fragments android-recyclerview android-sqlite

我有数据表单并将其数据保存在sqlite数据库中。我的数据是英文和波斯文,包括文字,时间和日期。我想在recyclerview中显示数据。但每次部署应用程序时,列表都是空的。我查看了Device file explorer并检查了数据库文件。它看起来像这样: database

ListFragment 显示的recyclerview和包含该表单的Fragment是 NewTaskFragment

数据库处理器

public class DataBaseHandler extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "Task Database";
// Task table name
private static final String TASK_TABLE = "tasks";
// TaskTable Columns names
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_DATE = "date";
private static final String KEY_TIME = "time";
//private static final String KEY_REPEAT = "repeat";
public DataBaseHandler(Context context) {
    super(context, DATABASE_NAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(
            " CREATE TABLE " + TASK_TABLE +  "(" +
                    KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    KEY_TITLE + " TEXT, " +
                    KEY_DATE + " TEXT, " +
                    KEY_TIME + " TEXT); "       );    }

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TASK_TABLE);
    onCreate(db);    }

public boolean insertTask(String title, String date, String time) {
    SQLiteDatabase sqLiteDatabase = getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(KEY_TITLE, title);
    contentValues.put(KEY_DATE, date);
    contentValues.put(KEY_TIME, time);
    //contentValues.put(KEY_REPEAT, repeat);

    long result =  sqLiteDatabase.insert(TASK_TABLE, null, contentValues);
    //if date as inserted incorrectly it will return -1
    if (result == -1) {
        return false;
    } else {
        return true;
    }    }
    boolean updateTask(Integer id, String title, String date, String time) {
    SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(KEY_TITLE, title);
    contentValues.put(KEY_DATE, date);
    contentValues.put(KEY_TIME, time);
    sqLiteDatabase.update(TASK_TABLE, contentValues, KEY_ID + "=?",
            new String[]{Integer.toString(id)});
    return true;
   }

public Cursor getTasks(int id) {
    SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
    Cursor cursor = sqLiteDatabase.rawQuery("select * from tasks where id=" + id +  "", null);        return cursor;    }

public int numberOfRows() {
    SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
    int numRows = (int) DatabaseUtils.queryNumEntries(sqLiteDatabase, TASK_TABLE);        return numRows;    }

public Integer deleteTask(Integer id) {
    SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
    return sqLiteDatabase.delete("tasks", "id=?",
            new String[]{Integer.toString(id)});   }

public Cursor getAllTasks() {
   SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
    Cursor data = sqLiteDatabase.rawQuery("SELECT * FROM "+ TASK_TABLE, null);
      return data;    }}

ListFragment

  public class ListFragment extends Fragment {
private SQLiteDatabase sqLiteDatabase;
private DataBaseHandler dataBaseHandler;
Cursor cursor;
public List<Tasks> tasksList= new ArrayList<>();
private RecyclerView task_recycler_view;
private TaskListAdapter taskListAdapter;
String string;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                         @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_item_list,
            container, false);

    task_recycler_view=(RecyclerView) view.findViewById(R.id.task_recycler_v);
    taskListAdapter= new TaskListAdapter(tasksList);
    RecyclerView.LayoutManager layoutManager= new LinearLayoutManager(getContext());
    task_recycler_view.setLayoutManager(layoutManager);
    task_recycler_view.setItemAnimator(new DefaultItemAnimator());
    dataBaseHandler=new DataBaseHandler(getContext());
    ArrayList<String> theList= new ArrayList<>();
    Cursor data= dataBaseHandler.getAllTasks();
    if (data.getCount()==0){
        Toast.makeText(getContext(),"database is empty",Toast.LENGTH_SHORT).show();

    }else{
        while (data.moveToNext()){
            theList.add(data.getString(1));
            theList.add(data.getString(2));
            theList.add(data.getString(3));
            taskListAdapter= new TaskListAdapter( tasksList);
            task_recycler_view.setAdapter(taskListAdapter);
        }        }        return view;    }    }

NewTaskFragment

  public class NewTaskFragment extends Fragment implements DateSetListener{


Toolbar save_toolbar;
EditText subject;
TextView startDate;
ImageButton dateImageButton;
TextView taskTime;
ImageButton timeImageButton;
ImageButton saveBtn;
private Date mEndDate;
private Date mStartDate;
private int  _hour, _minute;
String subject_data ,time_data, date_data, repeat_data,getValue;
DataBaseHandler dataBaseHandler;
String subj_str;
Bundle bundle;
public NewTaskFragment(){}
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    setLocale("fa");
    View view = inflater.inflate(R.layout.task_top,
    container, false);
    save_toolbar= (Toolbar) view.findViewById(R.id.task_toolbar) ;
    bundle= getArguments();
    saveBtn = (ImageButton) view.findViewById(R.id.saveImgBtn);
    subject = (EditText) view.findViewById(R.id.subject);
    startDate = (TextView) view.findViewById(R.id.startDateTxt);
    dateImageButton = (ImageButton) view.findViewById(R.id.startDateBtn);
     taskTime = (TextView) view.findViewById(R.id.timeTxt);
     timeImageButton = (ImageButton) 
    view.findViewById(R.id.timeImageButton);
    mEndDate = new Date();
    mStartDate = new Date();
    dataBaseHandler=new DataBaseHandler(getActivity());
    saveBtn.setOnClickListener(new View.OnClickListener() {
  @Override
    public void onClick(View v) {
   String title=subject.getText().toString();
    String date=startDate.getText().toString();
    String time=taskTime.getText().toString();
    if (subject.length()!=0||startDate.length()!=0||taskTime.length()!=0){
        addData(title,date,time);
        subject.setText("");
        startDate.setText("");
        taskTime.setText("");
    }else{
     Toast.makeText(getContext(),"the field id empty",Toast.LENGTH_SHORT).show();
    }        }
private void addData(String title, String date, String time) {
    boolean insertData=dataBaseHandler.insertTask(title,date,time );
    if (insertData==true){
         Toast.makeText(getContext(),"subject saved",Toast.LENGTH_SHORT).show();
    }else{            Toast.makeText(getContext(),"something went wrong",Toast.LENGTH_SHORT).show();        }    }});
    timeImageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final Calendar calendar = Calendar.getInstance();
            _hour = calendar.get(Calendar.HOUR_OF_DAY);
            _minute = calendar.get(Calendar.MINUTE);
            TimePickerDialog timePickerDialog = new TimePickerDialog(
                    getContext(), new TimePickerDialog.OnTimeSetListener() {
                @Override
                public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                    taskTime.setText(hourOfDay + ":" + minute);
                }
            }, _hour, _minute, false);
        timePickerDialog.show();
        }        });
    dateImageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int id = v.getId() == R.id.startDateBtn ? 1 : 2;
            new DatePicker.Builder()
                    .id(id)
                    .date(mStartDate.getDay(), mStartDate.getMonth(), mStartDate.getYear())
                    .build(NewTaskFragment.this)
                    .show(getFragmentManager(), "");
        }
    });        return view;    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    setLocale("fa");   }

private void setLocale(String language) {
    Locale locale = new Locale(language);
    Locale.setDefault(locale);
    Configuration config = new Configuration();
    config.locale = locale;
    getContext().getResources().updateConfiguration(config,
            getContext().getResources().getDisplayMetrics());   }
@Override
public void onDateSet(int id, @Nullable Calendar calendar, int day, int month, int year) {
    mStartDate.setDate(day, month, year);
    startDate.setText(mStartDate.getDate());    }}

1 个答案:

答案 0 :(得分:0)

在将ArrayList初始化为if (data.getCount()==0){ Toast.makeText(getContext(),"database is empty",Toast.LENGTH_SHORT).show(); } else { for (data.moveToFirst(); !data.isAfterLast(); data.moveToNext()) { theList.add(data.getString(1)); theList.add(data.getString(2)); theList.add(data.getString(3)); taskListAdapter= new TaskListAdapter( tasksList); task_recycler_view.setAdapter(taskListAdapter); } } 之前,您应该使用while

for

尝试此操作,您也可以将其与{{1}}一起使用,但我更喜欢{{1}}循环。