简体   繁体   English

从数据库检索所有数据

[英]Retrieving all data from database

I have encountered a problem while I was developing my Android application. 开发Android应用程序时遇到问题。 I am trying to retrieve all the data from my Android application, but I don't exactly know how. 我正在尝试从我的Android应用程序中检索所有数据,但我不完全知道该怎么做。 Here is my DBAdapter.java class: 这是我的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;

}
}

Here is my SendFeedback.java class, where I try to retrieve the data. 这是我的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();
    }

}
}

I don't know how to do this. 我不知道该怎么做。 I have searched the internet and SO for a while, but I can't find a solution. 我已经在互联网和SO上搜索了一段时间,但找不到解决方案。 I don't have any experience with SQLiteDatabases either. 我也没有使用SQLiteDatabases的经验。 Any help regarding this problem is appreciated. 任何有关此问题的帮助表示赞赏。

This is a good tutorial on sqlite databases on android: http://www.vogella.com/tutorials/AndroidSQLite/article.html 这是关于android上的sqlite数据库的很好的教程: http : //www.vogella.com/tutorials/AndroidSQLite/article.html

take a look a this extract: 看一下这个摘录:

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

And

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

so for your app you could have: 因此对于您的应用程序,您可以:

public List getAllComments() { List customers = new ArrayList(); public List getAllComments(){列出客户= 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;
}

And

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: You need to create your own class "Customer" to hold the data shown here PS:您需要创建自己的类“ Customer”来保存此处显示的数据

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM