получить данные из базы данных Sqlite и показать в recyclerview в android studio - PullRequest
0 голосов
/ 08 мая 2020

Я пытаюсь получить данные из базы данных SQLite, в которую мне удалось добавить данные. Я использую класс databaseHelper для добавления данных и любых других запросов, которые могут потребоваться приложению. В браузере Sqlite данные отображаются, но не знаю, что данные не отображаются в recyclerview. Список Ndata отображается пустым, не могли бы вы предложить мне, как поместить данные в список Ndata

public class LocationsDB extends SQLiteOpenHelper {

    /** Database name */
    private static String DBNAME = "locationmarkersqlite";

    /** Version number of the database */
    private static int VERSION = 1;

    /** Field 1 of the table locations, which is the primary key */
    public static final String FIELD_ROW_ID = "_id";


    /** Field 2 of the table locations, stores the latitude */
    public static final String FIELD_LAT = "lat";

    /** Field 3 of the table locations, stores the longitude*/
    public static final String FIELD_LNG = "lng";

    /** Field 4 of the table locations, stores the zoom level of map*/
    public static final String FIELD_ZOOM = "zom";
    public static final String FIELD_LOCNAME = "loc_nametext";
    public static final String FIELD_MOBILE = "mobile";

    /** A constant, stores the the table name */
    private static final String DATABASE_TABLE = "locations";

    /** An instance variable for SQLiteDatabase */
    private SQLiteDatabase mDB;
    private static final String DATABASE_ALTER_LocName = "ALTER TABLE "
            + DATABASE_TABLE + " ADD COLUMN " + FIELD_LOCNAME + " string;";
    private static final String DATABASE_ALTER_Mobile = "ALTER TABLE "
            + DATABASE_TABLE + " ADD COLUMN " + FIELD_MOBILE + " Interger;";

    /** Constructor */
    public  LocationsDB(Context context) {
        super(context, DBNAME, null, VERSION);
        this.mDB = getWritableDatabase();
    }

    /** This is a callback method, invoked when the method getReadableDatabase() / getWritableDatabase() is called
     * provided the database does not exists
     * */
    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql =     "create table " + DATABASE_TABLE + " ( " +
                FIELD_ROW_ID + " integer primary key autoincrement , " +
                FIELD_LNG + " varchar , " +
                FIELD_LAT + " varchar , " +
//                FIELD_LOCNAME + " text , " +
//                FIELD_MOBILE + " integer , " +
                FIELD_ZOOM + " text " +

                " ) ";

        db.execSQL(sql);

        //uninstall ok
        //add data no what happend dont know any errors no
    }

    /** Inserts a new location to the table locations */
    public long insertData(ContentValues contentValues){
        long rowID = mDB.insert(DATABASE_TABLE, null, contentValues);
        return rowID;

    }

    /** Deletes all locations from the table */
    public int del(){
        int cnt = mDB.delete(DATABASE_TABLE, null , null);
        return cnt;
    }

    /** Returns all the locations from the table */
    public Cursor getAllLocations(){
        mDB = getReadableDatabase();
        return mDB.query(DATABASE_TABLE, new String[] { FIELD_ROW_ID,  FIELD_LAT , FIELD_LNG, FIELD_ZOOM } , null, null, null, null, null);
    }
//
public Cursor getAllResearch() {

    // Select All Query
    String selectQuery = "SELECT  * FROM locations";

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    Log.d("asddddd","student data"+ cursor);



    // looping through all rows and adding to list


   // Log.d("asddddd","student data"+ researchList.toString());

    // return research list
    return cursor;
}

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL(DATABASE_ALTER_LocName);
        db.execSQL(DATABASE_ALTER_Mobile);


    }
    public ArrayList<MyListData> listContacts(){
        String sql = "select * from " + DATABASE_TABLE;
        SQLiteDatabase db = this.getReadableDatabase();
        ArrayList<MyListData> storeContacts = new ArrayList<>();
        Cursor cursor = db.rawQuery(sql, null);
        if(cursor.moveToFirst()){
            do{
                int id = Integer.parseInt(cursor.getString(0));
                String lat = cursor.getString(1);
                String lan = cursor.getString(2);
                String locname = cursor.getString(2);

                storeContacts.add(new MyListData(id, lat, lan,locname));
                Log.d("xxxxasasad", "listContacts: "+storeContacts);
            }while (cursor.moveToNext());
        }
        cursor.close();
        return storeContacts;
    }

    public  void insertLocation(String lat,String lon,String mobile,String locationName,String zoom){

        mDB = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("lat",lat);
        contentValues.put("lng",lon);
        contentValues.put("zom",zoom);

        contentValues.put("mobile",mobile);
        contentValues.put("loc_nametext",locationName);
        mDB.insert(DATABASE_TABLE,null,contentValues);
    }

}






This is adapter class this is worked fine



public class GetDataAdapter extends RecyclerView.Adapter<GetDataAdapter.MyViewHolder> {
    Context context;
    private LocationsDB mDatabase;

    private List<MyListData> NData;
    public GetDataAdapter(Context context, List<MyListData> NData) {
        this.context = context;
        this.NData = NData;
        mDatabase = new LocationsDB(context);



    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView LatValue, LangValue,LocNameDetails;


        public MyViewHolder(View view) {
            super(view);
            LatValue = (TextView) view.findViewById(R.id.LatValue);

            LangValue = (TextView) view.findViewById(R.id.LangValue);

            LocNameDetails = (TextView) view.findViewById(R.id.LocNameDetails);


        }
    }


    public GetDataAdapter(List<MyListData> NData) {
        this.NData = NData;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View itemView = LayoutInflater.from(parent.getContext())

                .inflate(R.layout.getdb, parent, false);
        context = itemView.getContext();



        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(final MyViewHolder holder, final int position) {
        holder.LatValue.setText(NData.get(position).getLat());
        holder.LangValue.setText(NData.get(position).getLang());
        holder.LocNameDetails.setText(NData.get(position).getLocName());

        //NotifiMadel MODEL = NData.get(position);
      //  holder.Header.setText(NData.get(position).getResponseMessage());
        //holder.Header.setTypeface(Custum_Typeface.load_SegoeuiB_Fonts(context));

        // holder.SubHeader.setText(NData.get(position).getSubHeader());
        //holder.Nimg.setImageResource(NData.get(position).getNImg());

    }

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

Main activity:

  LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        getDB.setLayoutManager(linearLayoutManager);
        getDB.setHasFixedSize(true);
        db = new LocationsDB(this);
        NData = db.listContacts();
        Log.d("ShowDatass", "onCreate: "+NData);
        getDB.setAdapter(adapter);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...