show data from database to listView Android

纵饮孤独 提交于 2019-12-10 10:30:51

问题


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

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 save and 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?


回答1:


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.

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



来源:https://stackoverflow.com/questions/23368375/show-data-from-database-to-listview-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!