Java 将数据从数据库显示到 listView Android

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23368375/
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-13 22:18:03  来源:igfitidea点击:

show data from database to listView Android

javaandroiddatabaseandroid-listview

提问by user3553370

I am trying to show all my data from my database into the listview

我正在尝试将我的数据库中的所有数据显示到列表视图中

Code to create database:

创建数据库的代码:

DataHander.java

数据处理程序

package com.example.testingforstack;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DataHandler {
    public static final String NAME = "name";
    public static final String EMAIL = "email";
    public static final String TABLE_NAME = "mytable";
    public static final String DATA_BASE_NAME = "mydatabase";
    public static final int DATABASE_VERSION = 1;
    public static final String TABLE_CREATE = "create table mytable (name text not null, email text not null);";

    DataBaseHelper dbhelper;
    Context ctx;
    SQLiteDatabase db;

    public DataHandler(Context ctx){
        this.ctx = ctx;
        dbhelper = new DataBaseHelper(ctx);
    }

    public static class DataBaseHelper extends SQLiteOpenHelper{

        public DataBaseHelper(Context ctx) {
            super(ctx, DATA_BASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db){
            try{
                db.execSQL(TABLE_CREATE);
            }catch (SQLException e){
                e.printStackTrace();
            }
        }

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

    public DataHandler open(){
        db = dbhelper.getReadableDatabase();
        return this;
    }

    public void close(){
        dbhelper.close();
    }

    public long insertData(String name, String email){
        ContentValues content = new ContentValues();
        content.put(NAME, name);
        content.put(EMAIL, email);
        return db.insertOrThrow(TABLE_NAME, null, content);
    }

    public Cursor returnData(){
        return db.query(TABLE_NAME, new String[] {NAME, EMAIL}, null, null, null, null, null); 
    }

}

mainActivity.java

主活动.java

package com.example.testingforstack;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

    Button save, load;
    EditText name, email;
    DataHandler handler;
    String getName, getEmail;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        save = (Button) findViewById(R.id.save);
        load = (Button) findViewById(R.id.load);
        name = (EditText) findViewById(R.id.name);
        email = (EditText) findViewById(R.id.email);

        save.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                String getName = name.getText().toString();
                String getEmail = email.getText().toString();

                handler = new DataHandler(getBaseContext());
                handler.open();
                long id = handler.insertData(getName, getEmail);
                insertSuccess();
                //Toast.makeText(getBaseContext(), "Data inserted", Toast.LENGTH_LONG).show();
                handler.close();
            }
        });

        load.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                getName = "";
                getEmail = "";
                handler = new DataHandler(getBaseContext());
                handler.open();
                Cursor C = handler.returnData();
                if(C.moveToFirst()){
                    do{
                        getName = C.getString(0);
                        getEmail = C.getString(1);
                    }while(C.moveToNext());
                }
                handler.close();
                loadSuccess();
                //Toast.makeText(getBaseContext(), "Name: "+getName+", Email: "+getEmail, Toast.LENGTH_LONG).show();
            }
        });
    }

    public void insertSuccess()
    {
        AlertDialog.Builder insertData = new AlertDialog.Builder(this);

        insertData.setTitle("Info");
        insertData.setMessage("Data Inserted");
        insertData.setNegativeButton("OK", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int value) {
                // TODO Auto-generated method stub
                arg0.dismiss();
            }
        });
        insertData.show();
    }

    public void loadSuccess()
    {
        AlertDialog.Builder loadData = new AlertDialog.Builder(this);

        loadData.setTitle("Info");
        loadData.setMessage("Name: "+getName+" & your email: "+getEmail);
        loadData.setNegativeButton("OK", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int value) {
                // TODO Auto-generated method stub
                arg0.dismiss();
            }
        });
        loadData.show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

I have two button saveand load. I have successfully implemented the save button to save the user name and email. However, I don't really know to load the data into the listview. How to do that?

我有两个按钮saveload。我已经成功实现了保存按钮来保存用户名和电子邮件。但是,我真的不知道将数据加载到列表视图中。怎么做?

采纳答案by user2704821

In listview you can use different types of adapters. For database, most appropriate is to use cursorAdapter where you tell which cursor to use. You can also manually walk through elements in DB and save them in some other object in array and then you can have arrayAddapter in which you pass your array of object. In each case you must set binder or override method onCreateView where you tell which parameter go in which child.

在列表视图中,您可以使用不同类型的适配器。对于数据库,最合适的是使用 cursorAdapter 来告诉您使用哪个游标。您还可以手动遍历数据库中的元素并将它们保存在数组中的其他对象中,然后您可以使用 arrayAddapter 来传递对象数组。在每种情况下,您都必须在 onCreateView 中设置绑定器或覆盖方法,您可以在其中告诉哪个参数进入哪个子项。

You can look this http://www.mysamplecode.com/2012/07/android-listview-cursoradapter-sqlite.htmlexample for more information.

您可以查看此 http://www.mysamplecode.com/2012/07/android-listview-cursoradapter-sqlite.html示例以获取更多信息。