@Cheliaba86

Как отобразить данные, взятые из БД на экран?

Здравствуйте, уважаемые! Помогите пожалуйста внести изменения в код. Я ввожу информацию, а именно фамилию и баллы и она отображается в logcat. Мне необходимо сделать так, что бы вся информация выводилась на экран.
MainActivity.java
import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    //создание элементов экрана
    Button btnAdd, btnRead, btnClear;
    EditText etFamil, etBall;
    DBHelper dbHelper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//прописываем обработчики
        btnAdd = (Button) findViewById(R.id.btnAdd);
        btnAdd.setOnClickListener(this);
        btnRead = (Button) findViewById(R.id.btnRead);
        btnRead.setOnClickListener(this);
        btnClear = (Button) findViewById(R.id.btnClear);
        btnClear.setOnClickListener(this);
        etFamil = (EditText) findViewById(R.id.etFamil);
        etBall = (EditText) findViewById(R.id.etBall);
        dbHelper = new DBHelper(this); }
    @Override
    public void onClick(View v) {
// получаем данные из полей ввода
        String famil = etFamil.getText().toString();
        String ball = etBall.getText().toString();
//класс для управления базой sqlite
        SQLiteDatabase database = dbHelper.getWritableDatabase();
//контент используется для добавления новых строк в таблицу
        ContentValues contentValues = new ContentValues();
//разделение действий по отдельным кнопкам
        switch (v.getId()) {
            case R.id.btnAdd:
                Log.d("mLog", "Записано в базу");
                contentValues.put(DBHelper.KEY_FAMIL, famil);
            contentValues.put(DBHelper.KEY_BALL, ball);
            database.insert(DBHelper.TABLE_ABITYRS, null, contentValues);
                break;
//чтение всех записей из таблицы квери
            case R.id.btnRead:
                //делаем запрос всех данных из таблицы abityrs, получаем Cursor
                Cursor cursor = database.query(DBHelper.TABLE_ABITYRS, null, null, null, null, null, null);
                if (cursor.moveToFirst()) {
                    //определяем номера столбцов
                    int idIndex = cursor.getColumnIndex(DBHelper.KEY_ID);
                    int familIndex = cursor.getColumnIndex(DBHelper.KEY_FAMIL);
                    int ballIndex = cursor.getColumnIndex(DBHelper.KEY_BALL);
                    do { Log.d("mLog", "ID = " + cursor.getInt(idIndex) + ", famil = " + cursor.getString(familIndex) + ", ball = " + cursor.getString(ballIndex));
                    } while (cursor.moveToNext());
                } else Log.d("mLog","Нет записей");
                cursor.close();
                break;
            case R.id.btnClear:
                database.delete(DBHelper.TABLE_ABITYRS, null, null);
                break; }
        dbHelper.close();
    }
}


DBHelper
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper  extends SQLiteOpenHelper{

    public static final int DATABASE_VERSION = 2;
    public static final String DATABASE_NAME = "abiterDb";
    public static final String TABLE_ABITYRS = "abityrs";
    public static final String KEY_ID = "_id";
    public static final String KEY_FAMIL = "famil";
    public static final String KEY_BALL = "ball";
    public DBHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    @Override
    //вызывается при первом создании базы
    public void onCreate(SQLiteDatabase db)
    //логика создания таблиц
    { db.execSQL("create table " + TABLE_ABITYRS + "(" + KEY_ID + " integer primary key," + KEY_FAMIL + " text," + KEY_BALL + " text" + ")"); }
    @Override
    //вызывается при внесении изменений
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        //запрос в базу данных на уничтожение таблицы
        db.execSQL("drop table if exists " + TABLE_ABITYRS);
        onCreate(db);
    }
}


Activiyt_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    >

    <EditText
        android:id="@+id/etFamil"
        android:hint="Фамилия студента"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20pt">
    </EditText>

    <EditText
        android:id="@+id/etBall"
        android:hint="Набранные баллы"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20pt"
        >
    </EditText>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:id="@+id/btnAdd"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Добавить"
            android:layout_marginLeft="8pt"
            android:layout_marginTop="30pt">

        </Button>
        <Button
            android:id="@+id/btnRead"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Просмотр базы"
            android:layout_marginLeft="4pt"
            android:layout_marginTop="30pt">>
        </Button>
        <Button
            android:id="@+id/btnClear"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Отчистить"
            android:layout_marginLeft="4pt"
            android:layout_marginTop="30pt">>
        </Button>
    </LinearLayout>
</LinearLayout>


5ef4f375d182e402494355.png
5ef4f37d0b3b4045182378.png
  • Вопрос задан
  • 203 просмотра
Решения вопроса 1
@WaterSmith
Android-разработчик. Java, Kotlin
Вам нужно изменить макет Activiyt_main.xml
Добавить в него после кнопок, скажем RecyclerView
в коде, где вы выводите данные в logcat заполнять список, и передавать его в RecyclerView.Adapter для отображения.
Подробности тут: https://developer.android.com/guide/topics/ui/layo...
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы