2014-02-09 2 views
0

У меня возникла проблема, когда я разрабатывал приложение для 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. Любая помощь по этой проблеме приветствуется.

ответ

0

Это хороший учебник по SQLite базы данных на Android: 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; 
} 

так и для вашего приложения, вы могли бы :

общественный список getAllComments() { Список клиентов = новый 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: Вам нужно создать свой собственный класс «Клиент» для хранения данных, показанные здесь

+0

Можете ли вы сказать мне, где именно поставить эти exercepts в моем приложении? – Rohodude

+0

Где у вас есть deleteAllCustomers(), searchCustomer (String inputText) и т. Д. ... В моем примере я использую класс example Comment, чтобы показать вам, как это сделать .. вам нужно изменить значения курсора и все на подойдет вашей заявке – nunoh123

+0

Я отредактировал свой ответ, надеюсь, что этого достаточно Кстати, ссылка в начале моего ответа довольно всеобъемлющая в базах данных в android .. если вам не по себе, вы обязательно должны прочитать ее, она может сэкономить у вас есть некоторые головные боли в будущем. Ad вы должны подумать о том, чтобы отделить DatabaseHelper от источника данных, намного чище. – nunoh123

Смежные вопросы