Java android studio 从Sqlite数据库中检索数据并将其显示到textview中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44876568/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 01:46:38  来源:igfitidea点击:

android studio retrieve data from Sqlite database and display it into textview

javaandroiddatabasesqlite

提问by Ra Isse

Hi guys please I need your help. I create SQLite Database in my app and I insert the data into it. And now I want to retrieve data from it but I want just insert one data and retrieve it then display it into a TextView.

嗨,伙计们,我需要你们的帮助。我在我的应用程序中创建了 SQLite 数据库并将数据插入其中。现在我想从中检索数据,但我只想插入一个数据并检索它,然后将其显示到 TextView 中。

please help me guys this is my first time I use SQLite Database.

请帮助我这是我第一次使用 SQLite 数据库。

public class Db_sqlit extends SQLiteOpenHelper{

    String TABLE_NAME = "BallsTable";

    public final static String name = "db_data";

    public Db_sqlit(Context context) {
        super(context, name, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table "+TABLE_NAME+" (id INTEGER PRIMARY KEY AUTOINCREMENT, ball TEXT)");

    }

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

    public boolean insertData(String balls){
      SQLiteDatabase db = this.getWritableDatabase();
      ContentValues contentValues = new ContentValues();

      contentValues.put("ball",balls);

      long result = db.insert(TABLE_NAME,null,contentValues);
      if(result == -1){
          return false;
      }
      else
          return true;
    }

    public void list_balls(TextView textView) {

        Cursor res = this.getReadableDatabase().rawQuery("select ball from "+TABLE_NAME+"",null);
        textView.setText("");
        while (res.moveToNext()){
            textView.append(res.getString(1));
        }  
    }
}

采纳答案by HB.

Here is an example of how I achieved this.

这是我如何实现这一目标的示例。

In this example I will store, retrieve, updateand deletea students name and age.

在这个例子中,我将storeretrieveupdatedelete一个学生的名字和年龄。



First create a class, I called mine

首先创建一个类,我叫我的

DBManager.java

数据库管理器

public class DBManager {
    private Context context;
    private SQLiteDatabase database;
    private SQLiteHelper dbHelper;

    public DBManager(Context c) {
        this.context = c;
    }

    public DBManager open() throws SQLException {
        this.dbHelper = new SQLiteHelper(this.context);
        this.database = this.dbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        this.dbHelper.close();
    }

    public void insert(String name, String desc) {
        ContentValues contentValue = new ContentValues();
        contentValue.put(SQLiteHelper.NAME, name);
        contentValue.put(SQLiteHelper.AGE, desc);
        this.database.insert(SQLiteHelper.TABLE_NAME_STUDENT, null, contentValue);
    }


    public Cursor fetch() {
        Cursor cursor = this.database.query(SQLiteHelper.TABLE_NAME_STUDENT, new String[]{SQLiteHelper._ID, SQLiteHelper.NAME, SQLiteHelper.AGE}, null, null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
        }
        return cursor;
    }

    public int update(long _id, String name, String desc) {
        ContentValues contentValues = new ContentValues();
        contentValues.put(SQLiteHelper.NAME, name);
        contentValues.put(SQLiteHelper.AGE, desc);
        return this.database.update(SQLiteHelper.TABLE_NAME_STUDENT, contentValues, "_id = " + _id, null);
    }

    public void delete(long _id) {
        this.database.delete(SQLiteHelper.TABLE_NAME_STUDENT, "_id=" + _id, null);
    }
}

Then create a SQLiteOpenHelperI called mine

然后创建一个SQLiteOpenHelper我称之为我的

SQLiteHelper.java

SQLiteHelper.java

public class SQLiteHelper extends SQLiteOpenHelper {
    public static final String AGE = "age";
    private static final String CREATE_TABLE_STUDENT = " create table STUDENTS ( _id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL , age TEXT );";
    private static final String DB_NAME = "STUDENTS.DB";
    private static final int DB_VERSION = 1;
    public static final String NAME = "name";
    public static final String TABLE_NAME_STUDENT = "STUDENTS";
    public static final String _ID = "_id";

    public SQLiteHelper(Context context) {
        super(context, DB_NAME, null, 1);
    }

    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_STUDENT);
    }

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


TO ADD:

加上:

In this example I take the text from EditTextand when the button is clicked I check if the EditTextis empty or not. If it is not empty and the student doesn't already exist I insert the students name and age into the database. I display a Toast, letting the user know of the status:

在这个例子中,我从中获取文本EditText,当单击按钮时,我检查它是否EditText为空。如果它不为空并且学生不存在,我会将学生的姓名和年龄插入数据库。我显示一个Toast,让用户知道状态:

btnAdd.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if (edtName.getText().toString().trim().length() == 0) {
            Toast.makeText(getApplicationContext(), "Please provide your students name", Toast.LENGTH_SHORT).show();
        } else{
            try {
                if (edtAge.getText().toString().trim().length() != 0) {
                    String name = edtName.getText().toString().trim();
                    String age = edtAge.getText().toString().trim();
                    String query = "Select * From STUDENTS where name = '"+name+"'";
                    if(dbManager.fetch().getCount()>0){
                        Toast.makeText(getApplicationContext(), "Already Exist!", Toast.LENGTH_SHORT).show();
                    }else{
                        dbManager.insert(name, age);
                        Toast.makeText(getApplicationContext(), "Added successfully!", Toast.LENGTH_SHORT).show();                           
                    }

                } else {
                    Toast.makeText(getApplicationContext(), "please provide student age!", Toast.LENGTH_SHORT).show();                           
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }  
});


TO UPDATE:

Here I take the Text in EditTextand update the student when the button is clicked. You can also place the following in a try/catchto make sure it is updated successfully.

更新:

在这里,我将文本输入EditText并在单击按钮时更新学生。您还可以将以下内容放在 a 中try/catch以确保它已成功更新。

btnupdate.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        String name = nameText.getText().toString();
        String age = ageText.getText().toString();
        dbManager.update(_id, name, age);
        Toast.makeText(getApplicationContext(), "Updated successfully!", Toast.LENGTH_SHORT).show();
    }
});


TO DELETE:

删除:

dbManager.delete(_id);
Toast.makeText(getApplicationContext(), "Deleted successfully!", Toast.LENGTH_SHORT).show();


TO GET:

要得到:

Here I get the name of the student and display it in a TextView

在这里,我获取学生的姓名并将其显示在 TextView

DBManager dbManager = new DBManager(getActivity());
dbManager.open();

Cursor cursor = dbManager.fetch();
cursor.moveToFirst();
final TextView studentName = (TextView) getActivity().findViewById(R.id.nameOfStudent);
studentName.settext(cursor.getString(0));