База данных SQLite извлекает все данные в Recyclerview через адаптер.(ищет настройки)

#android #json #sqlite #parsing

#Android #json #sqlite #синтаксический анализ

Вопрос:

Я работаю с базой данных SQLite и Recyclerview с адаптером. моя проблема в том, как я могу преобразовать / проанализировать мои данные в базе данных SQLite в JSON (мне нравится сохранять все мои данные в моем конструкторе и извлекать через адаптер после отображения адаптера с помощью Recyclerview).

ps. пожалуйста, спросите меня о других деталях, большое спасибо 🙂

в любом случае, это мои коды:

мои коды:

                //sqliteselectReader
               DatabaseHelper databaseHelper = new 
               DatabaseHelper(getContext());
                SQLiteDatabase db = databaseHelper.getWritableDatabase();
                Cursor c=databaseHelper.selectDisplaySchedule(db);


 my recyclerview binds with adapter:

              List<ScheduleDisplayDetails> get ="**my problem is here**"//I would like to fetch my data from database here on my getter setter. 


                        layoutManager = new 
              LinearLayoutManager(getContext());
                        RecyclerView recyclerView = inflatedView.
                        findViewById(R.id.scheduleRecycler);
                        recyclerView.setLayoutManager(layoutManager);
                        recyclerView.addItemDecoration(new 
              DividerItemDecoration(getContext(), 
              LinearLayoutManager.VERTICAL));
                        ScheduleModuleAdapter recyclerViewAdapter =
                        new ScheduleModuleAdapter(get);

                        recyclerView.setAdapter(recyclerViewAdapter);
  

Мой DbQuery:

     public Cursor selectDisplaySchedule(SQLiteDatabase db) {
    String sql = "SELECT ScheduleId, ScheduleLocation, ScheduleLatitude, 
    ScheduleLongitude, ScheduleExpectedTimeOfTransaction, 
    ScheduleEstimatedTimeOfDeparture, ScheduleStatus from tFleetSchedule;";
    return (db.rawQuery(sql, null));
}
  

это мои данные, которые я хотел бы сохранить (я открыл через браузер sqlite, извините, другие данные конфиденциальны):
введите описание изображения здесь

Это мой GetterSetter:

 public class ScheduleDisplayDetails {

private String ID;
private String Location;
private String Latitude;
private String Longitude;
private String ExpectedTimeOfTransaction;
private String EstimatedTimeOfDeparture;
private String Status;

public ScheduleDisplayDetails(String ID, String location, String latitude, String longitude, String expectedTimeOfTransaction, String estimatedTimeOfDeparture, String status) {
    this.ID = ID;
    Location = location;
    Latitude = latitude;
    Longitude = longitude;
    ExpectedTimeOfTransaction = expectedTimeOfTransaction;
    EstimatedTimeOfDeparture = estimatedTimeOfDeparture;
    Status = status;
}

public String getID() {
    return ID;
}

public void setID(String ID) {
    this.ID = ID;
}

public String getLocation() {
    return Location;
}

public void setLocation(String location) {
    Location = location;
}

public String getLatitude() {
    return Latitude;
}

public void setLatitude(String latitude) {
    Latitude = latitude;
}

public String getLongitude() {
    return Longitude;
}

public void setLongitude(String longitude) {
    Longitude = longitude;
}

public String getExpectedTimeOfTransaction() {
    return ExpectedTimeOfTransaction;
}

public void setExpectedTimeOfTransaction(String expectedTimeOfTransaction) {
    ExpectedTimeOfTransaction = expectedTimeOfTransaction;
}

public String getEstimatedTimeOfDeparture() {
    return EstimatedTimeOfDeparture;
}

public void setEstimatedTimeOfDeparture(String estimatedTimeOfDeparture) {
    EstimatedTimeOfDeparture = estimatedTimeOfDeparture;
}

public String getStatus() {
    return Status;
}

public void setStatus(String status) {
    Status = status;
}
  

}

это мой адаптер:

    public class ScheduleModuleAdapter extends 
   RecyclerView.Adapter<ScheduleModuleAdapter.MyViewHolder> {

private List<ScheduleDisplayDetails> schedlist;

public class MyViewHolder extends RecyclerView.ViewHolder {
    public TextView location, schedule_status, id, expected, estimated;


    public MyViewHolder(View view) {
        super(view);
        location = view.findViewById(R.id.schedule_location);
        estimated = view.findViewById(R.id.schedule_estimated_time);
        schedule_status = view.findViewById(R.id.schedule_Status);
        expected = view.findViewById(R.id.schedule_expected_time);
        id = view.findViewById(R.id.schedule_ID);


    }
}


public ScheduleModuleAdapter(List<ScheduleDisplayDetails> scheduleList) {
    this.schedlist = scheduleList;
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.schedule_module_card_view, parent, false);

    return new MyViewHolder(itemView);
}

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    ScheduleDisplayDetails sched = schedlist.get(position);
    holder.location.setText(sched.getLocation());
    holder.schedule_status.setText(sched.getStatus());
    holder.estimated.setText(sched.getEstimatedTimeOfDeparture());
    holder.expected.setText(sched.getExpectedTimeOfTransaction());
    holder.id.setText(sched.getID());

     }


@Override
public int getItemCount() {
    return schedlist.size();
}
  

}

Ответ №1:

Просто выполните цикл Cursor , создайте каждый объект на итерации и установите значения:

 //sqliteselectReader
               DatabaseHelper databaseHelper = new 
               DatabaseHelper(getContext());
                SQLiteDatabase db = databaseHelper.getWritableDatabase();
                Cursor c=databaseHelper.selectDisplaySchedule(db);

ArrayList<ScheduleDisplayDetails> get = new ArrayList<>(); initialize your list

while(c.moveToNext()) {
    ScheduleDisplayDetails details = new ScheduleDisplayDetails(); // you should create an empty constructor also on your object

    details.setID(c.getString(c.getColumnIndexOrThrow("ScheduleId")));
    details.setLocation(c.getString(c.getColumnIndexOrThrow("ScheduleLocation")));
    //set other details also....

    get.add(details); // add the object on your list
}

//then setup your recyclerview and adapter...
  

Комментарии:

1. спасибо, ребята, я новичок в разработке.. также пытаюсь это исправить, но я не знаю логики. кстати, большое спасибо : D это лучший ответ для этого.

2. рад помочь 🙂