从数据库中检索所有数据

时间:2014-02-09 00:12:23

标签: java android android-sqlite

我在开发Android应用程序时遇到了问题。我试图从我的Android应用程序中检索所有数据,但我不知道如何。这是我的DBAdapter.java类:

package com.example.foodsaver2;

import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.AvoidXfermode;
import android.util.Log;
import com.example.*;

public class DBAdapter {
public static final String KEY_ROWID = "rowid";
public static final String KEY_CUSTOMER = "customer";
public static final String KEY_NAME = "name";
public static final String KEY_ADDRESS = "address";
public static final String KEY_ADDRESS1 = "address1";
public static final String KEY_ADDRESS2 = "address2";
public static final String KEY_CITY = "city";
public static final String KEY_STATE = "state";
public static final String KEY_ZIP = "zipCode";
public static final String KEY_SEARCH = "searchData";
public static final String TOTAL_CARB = "carb";
public static final String FIBER = "fiber";
public static final String SUGAR = "sugar";
public static final String PROTEIN = "protein";
public static final String SODIUM = "salt";
public static final String TOTALCALORIES = "calories";
public static Context contextOfApplication;



private static final String TAG = "DBAdapter";
private DatabaseHelper mDbHelper;
public SQLiteDatabase mDb;

private static final String DATABASE_NAME = "Data";
private static final String FTS_VIRTUAL_TABLE = "Info";
private static final int DATABASE_VERSION = 7;

private static final String DATABASE_CREATE1 =
        "CREATE VIRTUAL TABLE " + FTS_VIRTUAL_TABLE + " USING fts3(" +
                KEY_CUSTOMER + /*"INTEGER," + */ "," +
                KEY_NAME + "," +
                KEY_ADDRESS1 + "," +
                KEY_ADDRESS2 + "," +
                KEY_CITY + "," +
                KEY_STATE + "," +
                KEY_ZIP + "," +
                KEY_SEARCH + "," +
                TOTAL_CARB + "," +
                FIBER + "," +
                SUGAR + "," +
                PROTEIN + "," +
                SODIUM + "," +
                TOTALCALORIES + "," +
                " UNIQUE (" + KEY_CUSTOMER + "));";

private final Context mCtx;

private static class DatabaseHelper extends SQLiteOpenHelper {

    DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }


    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.w(TAG, DATABASE_CREATE1);
        db.execSQL(DATABASE_CREATE1);

    }
    public static Context getContextOfApplication(){
        return contextOfApplication;

    }


    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS " + FTS_VIRTUAL_TABLE);
        onCreate(db);
    }
}

public DBAdapter(Context ctx) {
    this.mCtx = ctx;
}

public DBAdapter open() throws SQLException {
    mDbHelper = new DatabaseHelper(mCtx);
    mDb = mDbHelper.getWritableDatabase();
    return this;
}

public void close() {
    if (mDbHelper != null) {
        mDbHelper.close();
    }
}


public long createCustomer(String customer, String name, String address1, String address2, String city, String state, String zipCode, String carb, String fiber, String sugar, String protein, String sodium, String calories) {

    ContentValues initialValues = new ContentValues();
    String searchValue =     customer + " " +
            name + " " +
            address1 + " " +
            city + " " +
            state + " " +
            zipCode;
    initialValues.put(KEY_CUSTOMER, customer);
    initialValues.put(KEY_NAME, name);
    initialValues.put(KEY_ADDRESS1, address1);
    initialValues.put(KEY_ADDRESS2, address2);
    initialValues.put(KEY_CITY, city);
    initialValues.put(KEY_STATE, state);
    initialValues.put(KEY_ZIP, zipCode);
    initialValues.put(KEY_SEARCH, searchValue);
    initialValues.put(TOTAL_CARB, carb);
    initialValues.put(FIBER, fiber);
    initialValues.put(SUGAR, sugar);
    initialValues.put(PROTEIN, protein);
    initialValues.put(SODIUM, sodium);
    initialValues.put(TOTALCALORIES, calories);

    return mDb.insert(FTS_VIRTUAL_TABLE, null, initialValues);

}


public Cursor searchCustomer(String inputText) throws SQLException {
    Log.w(TAG, inputText);
    String query = "SELECT docid as _id," +
            KEY_CUSTOMER + "," +
            KEY_NAME + "," +
            "(" + KEY_ADDRESS1 + "||" +
            "(case when " + KEY_ADDRESS2 +  "> '' then '\n' || " + KEY_ADDRESS2 + " else '' end)) as " +  KEY_ADDRESS +"," +
            KEY_ADDRESS1 + "," +
            KEY_ADDRESS2 + "," +
            KEY_CITY + "," +
            KEY_STATE + "," +
            KEY_ZIP + "," +
            TOTAL_CARB + "," +
            FIBER + "," +
            SUGAR + "," +
            PROTEIN + "," +
            SODIUM + "," +
            TOTALCALORIES +
            " from " + FTS_VIRTUAL_TABLE +
            " where " +  KEY_SEARCH + " MATCH '" + inputText + "';";
    Log.w(TAG, query);
    Cursor mCursor = mDb.rawQuery(query,null);
    if (mCursor != null) {
        mCursor.moveToFirst();
    }

    return mCursor;

}


public boolean deleteAllCustomers() {

    int doneDelete = 0;
    doneDelete = mDb.delete(FTS_VIRTUAL_TABLE, null , null);
    Log.w(TAG, Integer.toString(doneDelete));
    return doneDelete > 0;

}
}

这是我的SendFeedback.java类,我尝试检索数据。

package com.example.foodsaver2;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

 /**
 * Created by mother on 2/7/14.
 */
public class SendFeedback extends Activity {
private DBAdapter mDbHelper;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.send_feedback);
    mDbHelper = new DBAdapter(this);
    mDbHelper.open();
}
public void send (View v) {
    Cursor c = mDbHelper.getData();
    GmailSender sender = new GmailSender("omitted for privacy", "omitted for privacy");
    try {
    sender.sendMail("This is Subject",
            "This is Body",
            "omitted for privacy",
            "omitted for privacy");
        Toast.makeText(getApplicationContext(), "Sent!", Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        Toast.makeText(getApplicationContext(), "Cannot send message!", Toast.LENGTH_SHORT).show();
    }

}
}

我不知道该怎么做。我已经搜索了互联网和SO一段时间,但我找不到解决方案。我对SQLiteDatabases也没有任何经验。关于这个问题的任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

这是关于android上sqlite数据库的一个很好的教程: http://www.vogella.com/tutorials/AndroidSQLite/article.html

看看这个摘录:

public List<Comment> getAllComments() {
    List<Comment> comments = new ArrayList<Comment>();

    Cursor cursor = database.query(MySQLiteHelper.TABLE_COMMENTS, allColumns, null, null, null, null, null);

    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        Comment comment = cursorToComment(cursor);
        comments.add(comment);
        cursor.moveToNext();
    }
    // make sure to close the cursor
    cursor.close();
    return comments;
}

private Comment cursorToComment(Cursor cursor) {
    Comment comment = new Comment();
    comment.setId(cursor.getLong(0));
    comment.setComment(cursor.getString(1));
    return comment;
}

因此对于您的应用,您可以:

public List getAllComments(){         列出customers = new ArrayList();

    Cursor cursor = database.query(FTS_VIRTUAL_TABLE, new String[]{"KEY_CUSTOMER", "KEY_NAME " , etc..}, null, null, null, null, null);

    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        Customer customer = cursorToCustomer(cursor);
        customers.add(comment);
        cursor.moveToNext();
    }
    // make sure to close the cursor
    cursor.close();
    return customers;
}

private Customer cursorToCustomer(Cursor cursor) {
    Customer customer = new Customer();
    customer.setCustomer(cursor.getString(0));
    customer.setName(cursor.getString(1));
    customer.setAddress1(cursor.getString(2));
    customer.setAddress2(cursor.getString(3));
    customer.setCity(cursor.getString(4));
    customer.setState(cursor.getString(5));
    customer.setZipCode(cursor.getString(6));
    customer.setSearchValue(cursor.getString(7));
    customer.setCarb(cursor.getString(8));
    customer.setFiber(cursor.getString(9));
    customer.setSugar(cursor.getString(10));
    customer.setProtein(cursor.getString(11));
    customer.setSodium(cursor.getString(12));
    customer.setCalories(cursor.getString(13));

    return comment;
}

PS:您需要创建自己的“客户”类来保存此处显示的数据