如何从android中的sqlite存储和获取列表视图数据?

时间:2015-01-07 07:03:30

标签: java android sqlite

我创建了一个简单的演示,其中我只是在sqlite中存储了名字和姓氏这两个值,并在列表视图中显示。但是当我尝试两个时添加更多值,如电话no.address,state,国家等。我收到错误。它显示消息,如无法读取行和列数据。 请帮我两个添加9或10个值并在列表视图中显示。这是我的代码。

AddActivity.Java

public class AddActivity extends Activity implements OnClickListener {
private Button btn_save;
private EditText edit_first,edit_last,phoneNo;
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private String id,fname,lname,pno;
private boolean isUpdate;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add);

        btn_save=(Button)findViewById(R.id.save_btn);
        edit_first=(EditText)findViewById(R.id.frst_editTxt);
        edit_last=(EditText)findViewById(R.id.last_editTxt);
        phoneNo=(EditText)findViewById(R.id.phoneNo);

       isUpdate=getIntent().getExtras().getBoolean("update");
        if(isUpdate)
        {
            id=getIntent().getExtras().getString("ID");
            fname=getIntent().getExtras().getString("Fname");
            lname=getIntent().getExtras().getString("Lname");
            pno=getIntent().getExtras().getString("Pno");

            edit_first.setText(fname);
            edit_last.setText(lname);
            phoneNo.setText(pno);

        }

         btn_save.setOnClickListener(this);

         mHelper=new DbHelper(this);

    }


    public void onClick(View v) {
        fname=edit_first.getText().toString().trim();
        lname=edit_last.getText().toString().trim();
        pno=phoneNo.getText().toString().trim();
        if(fname.length()>0 && lname.length()>0)
        {
            saveData();
        }
        else
        {
            AlertDialog.Builder alertBuilder=new AlertDialog.Builder(AddActivity.this);
            alertBuilder.setTitle("Invalid Data");
            alertBuilder.setMessage("Please, Enter valid data");
            alertBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                       dialog.cancel();

                }
            });
            alertBuilder.create().show();
        }

    }


    private void saveData(){
        dataBase=mHelper.getWritableDatabase();
        ContentValues values=new ContentValues();

        values.put(DbHelper.KEY_FNAME,fname);
        values.put(DbHelper.KEY_LNAME,lname );
        values.put(DbHelper.KEY_PHONENO,pno );

        System.out.println("");
        if(isUpdate)
        {    

            dataBase.update(DbHelper.TABLE_NAME, values, DbHelper.KEY_ID+"="+id, null);
        }
        else
        {

            dataBase.insert(DbHelper.TABLE_NAME, null, values);
        }

        dataBase.close();
        finish();


    }

}

DisplayAdapter.java

public class DisplayAdapter extends BaseAdapter {
    private Context mContext;
    private ArrayList<String> id;
    private ArrayList<String> firstName;
    private ArrayList<String> lastName;
    private ArrayList<String> phoneNo;


    public DisplayAdapter(Context c, ArrayList<String> id,ArrayList<String> fname, ArrayList<String> lname,ArrayList<String> pno) {
        this.mContext = c;

        this.id = id;
        this.firstName = fname;
        this.lastName = lname;
        this.phoneNo = pno;
    }



    public int getCount() {
        // TODO Auto-generated method stub
        return id.size();
    }

    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return null;
    }

    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    public View getView(int pos, View child, ViewGroup parent) {
        Holder mHolder;
        LayoutInflater layoutInflater;
        if (child == null) {
            layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            child = layoutInflater.inflate(R.layout.listcell, null);
            mHolder = new Holder();
            mHolder.txt_id = (TextView) child.findViewById(R.id.txt_id);
            mHolder.txt_fName = (TextView) child.findViewById(R.id.txt_fName);
            mHolder.txt_lName = (TextView) child.findViewById(R.id.txt_lName);
            mHolder.phoneTextView = (TextView) child.findViewById(R.id.phoneTextView);
            child.setTag(mHolder);
        } else {
            mHolder = (Holder) child.getTag();
        }
        mHolder.txt_id.setText(id.get(pos));
        mHolder.txt_fName.setText(firstName.get(pos));
        mHolder.txt_lName.setText(lastName.get(pos));
        mHolder.phoneTextView.setText(phoneNo.get(pos));

        return child;
    }

    public class Holder {
        TextView txt_id;
        TextView txt_fName;
        TextView txt_lName;
        TextView phoneTextView;
    }

}

Database Helper.java

public class DbHelper extends SQLiteOpenHelper {
    static String DATABASE_NAME="userdata";
    public static final String TABLE_NAME="user";
    public static final String KEY_FNAME="fname";
    public static final String KEY_LNAME="lname";
    public static final String KEY_PHONENO="pno";
    public static final String KEY_ID="id";
    public DbHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_FNAME+" TEXT, "+KEY_LNAME+" TEXT, "+KEY_PHONENO+" TEXT)";
        db.execSQL(CREATE_TABLE);

    }

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

    }

}

DisplayActivity.java

public class DisplayActivity extends Activity {

    private DbHelper mHelper;
    private SQLiteDatabase dataBase;

    private ArrayList<String> userId = new ArrayList<String>();
    private ArrayList<String> user_fName = new ArrayList<String>();
    private ArrayList<String> user_lName = new ArrayList<String>();
    private ArrayList<String> user_phoneNo = new ArrayList<String>();

    private ListView userList;
    private AlertDialog.Builder build;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.display_activity);

        userList = (ListView) findViewById(R.id.List);

        mHelper = new DbHelper(this);

        //add new record
        findViewById(R.id.btnAdd).setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

                Intent i = new Intent(getApplicationContext(), AddActivity.class);
                i.putExtra("update", false);
                startActivity(i);

            }
        });

        //click to update data
        userList.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

                Intent i = new Intent(getApplicationContext(), AddActivity.class);
                i.putExtra("Fname", user_fName.get(arg2));
                i.putExtra("Lname", user_lName.get(arg2));
                i.putExtra("Lname", user_phoneNo.get(arg2));
                i.putExtra("ID", userId.get(arg2));
                i.putExtra("update", true);
                startActivity(i);

            }
        });

        //long click to delete data
        userList.setOnItemLongClickListener(new OnItemLongClickListener() {

            public boolean onItemLongClick(AdapterView<?> arg0, View arg1, final int arg2, long arg3) {

                build = new AlertDialog.Builder(DisplayActivity.this);
                build.setTitle("Delete " + user_fName.get(arg2) + " " + user_lName.get(arg2));
                build.setMessage("Do you want to delete ?");
                build.setPositiveButton("Yes",new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog, int which) {

                                Toast.makeText( getApplicationContext(),
                                        user_fName.get(arg2) + " "
                                                + user_lName.get(arg2)
                                                +user_phoneNo.get(arg2)
                                                + " is deleted.", 3000).show();

                                dataBase.delete(
                                        DbHelper.TABLE_NAME,
                                        DbHelper.KEY_ID + "="
                                                + userId.get(arg2), null);
                                displayData();
                                dialog.cancel();
                            }
                        });

                build.setNegativeButton("No", new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog, int which) {
                                    dialog.cancel();
                            }
                        });
                AlertDialog alert = build.create();
                alert.show();

                return true;
            }
        });
    }

    @Override
    protected void onResume() {
        displayData();
        super.onResume();
    }

    /**
     * displays data from SQLite
     */
    private void displayData() {
        dataBase = mHelper.getWritableDatabase();
        Cursor mCursor = dataBase.rawQuery("SELECT * FROM " + DbHelper.TABLE_NAME, null);

        userId.clear();
        user_fName.clear();
        user_lName.clear();
        user_phoneNo.clear();
        if (mCursor.moveToFirst()) {
            do {
                userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
                user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
                user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));
                user_phoneNo.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_PHONENO)));

            } while (mCursor.moveToNext());
        }
        DisplayAdapter disadpt = new DisplayAdapter(DisplayActivity.this,userId, user_fName, user_lName,user_phoneNo);
        userList.setAdapter(disadpt);
        mCursor.close();
    }



}

2 个答案:

答案 0 :(得分:1)

以下是从数据库中存储和获取数据的示例。

public class Database extends SQLiteOpenHelper  {


    public static final String KEY_ID= "id";
    public static final String KEY_SURVEY_UPLOAD = "IS_SURVEY_UPLOAD";
    public static final String KEY_SURVEY_COMPLETE = "IS_SURVEY_COMPLETE";
    public static final String KEY_DEVICE_ID = "DEVICE_ID";
    public static final String KEY_LATITUDE = "LATITUDE";
    public static final String KEY_LONGITUDE = "LONGITUDE";
    public static final String KEY_FILE_ID = "FILE_ID";


    public static final String DATABASE_NAME = "DatabaseName";
    public static final String DATABASE_TABLE_one = "Table1";



    private static final String CREATE_TABLE__NUM =   "create table "+DATABASE_TABLE_SURVEY+
            " ("+KEY_SURVEY_COMPLETE+" TEXT,"+KEY_FILE_ID+" INTEGER,"+KEY_DEVICE_ID+" TEXT,"+KEY_LATITUDE+" TEXT, "+KEY_LONGITUDE+" TEXT, "+KEY_SURVEY_UPLOAD+" TEXT, "+KEY_SURVEYID+" INTEGER PRIMARY KEY AUTOINCREMENT )";




    public Database(Context context, String name, CursorFactory factory,
            int version) {
        super(context, name, null, 1);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub

        System.out.println("crteate table");
        db.execSQL(CREATE_TABLE_SURVEY_CONTENT);


    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

        db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_one);

        onCreate(db);

    }



    public boolean insertData(SurveyBean bean)
    {
        System.out.println("insert_SURVEY");
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();


        contentValues.put(KEY_SURVEY_COMPLETE, "false");
        contentValues.put(KEY_SURVEY_UPLOAD, "0");
        contentValues.put(KEY_LATITUDE, bean.getLatitude());
        contentValues.put(KEY_LONGITUDE, bean.getLongitude());
        contentValues.put(KEY_DEVICE_ID, bean.getDeviceId());
        contentValues.put(KEY_FILE_ID, Integer.getInteger(bean.getFileId()));

        long id=db.insert(DATABASE_TABLE_SURVEY, null, contentValues);
        System.out.println("last inserted ID"+id);
        db.close();
        return true;
    }








    public ArrayList<SurveyBean> getAllData(){

        ArrayList<SurveyBean> arrayList = new ArrayList<SurveyBean>();

        SQLiteDatabase db = this.getWritableDatabase();

        Cursor cc = db.rawQuery("SELECT *" + " FROM " + DATABASE_TABLE_SURVEY, null);

        cc.moveToFirst();
        while(cc.isAfterLast() == false){

            SurveyBean bean = new SurveyBean();

            bean.set_isSurveyComplete(cc.getString(cc.getColumnIndex(KEY_SURVEY_COMPLETE)));
            bean.set_isSurveyUpload(cc.getString(cc.getColumnIndex(KEY_SURVEY_UPLOAD)));
            bean.set_surveyId(Integer.parseInt(cc.getString(cc.getColumnIndex(KEY_SURVEYID))));
            bean.setDeviceId(cc.getString(cc.getColumnIndex(KEY_DEVICE_ID)));
            bean.setLatitude(cc.getString(cc.getColumnIndex(KEY_LATITUDE)));
            bean.setLongitude(cc.getString(cc.getColumnIndex(KEY_LONGITUDE)));
            bean.setFileId(String.valueOf(cc.getInt(cc.getColumnIndex(KEY_FILE_ID))));
            arrayList.add(bean);

            cc.moveToNext();
        }
        db.close();

        return arrayList ;

    }





}

答案 1 :(得分:-1)

看,我做了一个简单的应用程序,从android中的sqlite数据库创建一个列表视图。看看它。它可以帮到你。

main.xml中

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

DBHelper.java

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

public class DBHelper extends SQLiteOpenHelper{

    public SQLiteDatabase DB;
    public String DBPath;
    public static String DBName = "testdb";
    public static final int version = '1';
    public static Context currentContext;
    public static String tableName = "tbl_details";


    public DBHelper(Context context) {
        super(context, DBName, null, version);
        currentContext = context;
        DBPath = "/data/data/" + context.getPackageName() + "/databases";
        createDatabase();

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

    }

    private void createDatabase() {
        boolean dbExists = checkDbExists();

        if (dbExists) {
            // do nothing
        } else {
            DB = currentContext.openOrCreateDatabase(DBName, 0, null);
            DB.execSQL("CREATE TABLE IF NOT EXISTS " +
                    tableName +
                    " (LastName VARCHAR, FirstName VARCHAR," +
                    " Country VARCHAR, Age INT(3));");

            DB.execSQL("INSERT INTO " +
                    tableName +
                    " Values ('A','vijay','India',20);");
            DB.execSQL("INSERT INTO " +
                    tableName +
                    " Values ('B','ajay','Pakistan',25);");
            DB.execSQL("INSERT INTO " +
                    tableName +
                    " Values ('C','suraj','Bangladesh',30);");
            DB.execSQL("INSERT INTO " +
                    tableName +
                    " Values ('D','jayesh','China',35);");
            DB.execSQL("INSERT INTO " +
                    tableName +
                    " Values ('E','ramesh','Nepal',40);");
            DB.execSQL("INSERT INTO " +
                    tableName +
                    " Values ('F','suresh','SriLanka',45);");
        }


    }

    private boolean checkDbExists() {
        SQLiteDatabase checkDB = null;

        try {
            String myPath = DBPath + DBName;
            checkDB = SQLiteDatabase.openDatabase(myPath, null,
                    SQLiteDatabase.OPEN_READONLY);

        } catch (SQLiteException e) {

            // database does't exist yet.

        }

        if (checkDB != null) {

            checkDB.close();

        }

        return checkDB != null ? true : false;
    }
}

的manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.example.ListViewFromSQLiteDB"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name="com.example.ListViewFromSQLiteDB.DataListView"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

</manifest>

ListViewFromSQLiteDB.java

import java.util.ArrayList;

import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class DataListView extends ListActivity {

    private ArrayList<String> results = new ArrayList<String>();
    private String tableName = DBHelper.tableName;
    private SQLiteDatabase newDB;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        openAndQueryDatabase();

        displayResultList();


    }
    private void displayResultList() {
        TextView tView = new TextView(this);
        tView.setText("This data is retrieved from the database and only 4 " +
                "of the results are displayed");
        getListView().addHeaderView(tView);

        setListAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, results));
        getListView().setTextFilterEnabled(true);

    }
    private void openAndQueryDatabase() {
        try {
            DBHelper dbHelper = new DBHelper(this.getApplicationContext());
            newDB = dbHelper.getWritableDatabase();
            Cursor c = newDB.rawQuery("SELECT FirstName, Age FROM " +
                    tableName +
                    " where Age > 10 LIMIT 4", null);

            if (c != null ) {
                if  (c.moveToFirst()) {
                    do {
                        String firstName = c.getString(c.getColumnIndex("FirstName"));
                        int age = c.getInt(c.getColumnIndex("Age"));
                        results.add("Name: " + firstName + ",Age: " + age);
                    }while (c.moveToNext());
                } 
            }           
        } catch (SQLiteException se ) {
            Log.e(getClass().getSimpleName(), "Could not create or Open the database");
        } finally {
            if (newDB != null) 
                newDB.execSQL("DELETE FROM " + tableName);
                newDB.close();
        }

    }

}

}