显示从数据库到listView Android的数据

时间:2014-04-29 15:01:39

标签: java android database android-listview

我试图将我的数据库中的所有数据显示到listview

创建数据库的代码:

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

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;
    }

}

我有两个按钮saveload。我已成功实施保存按钮以保存用户名和电子邮件。但是,我真的不知道将数据加载到listview中。怎么做?

1 个答案:

答案 0 :(得分:2)

在listview中,您可以使用不同类型的适配器。对于数据库,最合适的方法是使用cursorAdapter来指出要使用的游标。您也可以手动遍历数据库中的元素并将它们保存在数组中的其他对象中,然后您可以使用arrayAddapter来传递对象数组。在每种情况下,您必须在onCreateView上设置binder或override方法,您可以在哪里告诉哪个参数进入哪个子项。

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