如何将数据库查询放在一个类中

时间:2016-09-06 09:04:45

标签: android sqlite

这是我的问题,我不知道如何在不影响绑定和迭代器的情况下将我的插入查询在单个类中使用SQLiteStatement?这是我到目前为止取得的进展。数据库位于MainActivity中,但我希望将所有查询放在一个类中。

     btnSave = (Button) findViewById(R.id.btnSaveAlbum);
            btnSave.setOnClickListener(new View.OnClickListener() {
                @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
                @Override
                public void onClick(View v) {
                    txtTitle = (EditText) findViewById(R.id.txtAlbumTitle);
                    String title = txtTitle.getText().toString();

                    if (requestCode == 200 && resultCode == Activity.RESULT_OK) {
                        String[] apath = data.getStringArrayExtra("all_path");
                        ArrayList<String> strings = new ArrayList<String>();
                        Iterator iterate = strings.iterator();
                        for (String string : apath) {
                            strings.add(string);
                        }


                        String query = "INSERT INTO " + TBNAME + " VALUES (?,?);";
                        SQLiteStatement statement = timedb.compileStatement(query);
                        timedb.beginTransaction();

                        while (iterate.hasNext()) {
                            statement.clearBindings();
                            statement.bindString(1, title);
                            statement.bindString(2, iterate.next().toString());
                            statement.execute();
                        }

                        timedb.setTransactionSuccessful();
                        timedb.endTransaction();
                        timedb.close();
 Toast.makeText(MainActivity.this, "Successful", Toast.LENGTH_LONG).show();

                    }
                }
            });

2 个答案:

答案 0 :(得分:3)

这样做

import java.text.ParseException;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DbHelper extends SQLiteOpenHelper
{
    private final String TAG = "Database";

    public static final int DATABASE_VERSION = 13;
    public static final String DATABASE_NAME = "assessment.db";



    public static final String FEED_AUDIO_TABLE = "audiTable";
    public static final String FEED_AUDIO_COLUMN_ID = "audioId";
    public static final String FEED_AUDIO_AUDIO = "audio";
    public static final String FEED_AUDIO_ISDOWNLODED = "audioIsdownloaded";


    Context context;    

    public DbHelper(Context context)
    {
        super(context,  DATABASE_NAME , null, DATABASE_VERSION);

        this.context = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db)
    {
    //table
        db.execSQL("create table "+FEED_AUDIO_TABLE+
                "("+FEED_AUDIO_COLUMN_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+FEED_AUDIO_AUDIO+" text NOT NULL UNIQUE, "+FEED_AUDIO_ISDOWNLODED+" text);");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {

        db.execSQL("DROP TABLE IF EXISTS "+FEED_AUDIO_TABLE);
        onCreate(db);
    }




    //insert method
    public boolean insertAudioForDownload(String audioUrl, String isDownloaded)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();

        contentValues.put(FEED_AUDIO_AUDIO, audioUrl);
        contentValues.put(FEED_AUDIO_ISDOWNLODED, isDownloaded);

        long i = db.insertWithOnConflict(FEED_AUDIO_TABLE, null, contentValues, SQLiteDatabase.CONFLICT_REPLACE);

        Log.i(TAG, "insertForBackground Value inserted: "+i +" for audioUrl :"+ audioUrl+ " isDownloaded is : "+ isDownloaded);


        return true;
    }

    //Read method

    public ArrayList<String> getAudioForDownload(String isDownloaded)
    {
        ArrayList<String> arrayList = new ArrayList<String>();
        String gridSelected = "";
        SQLiteDatabase db = getReadableDatabase();

        String where = FEED_AUDIO_ISDOWNLODED+"=?";
        String[] whereArgs = {isDownloaded};

        Cursor cursor = db.query(FEED_AUDIO_TABLE, null, where, whereArgs, null, null, null);
        if(cursor != null && cursor.getCount() > 0)
        {
            Log.d(TAG, "getAudioForDownload cursor count  is: "+cursor.getCount());

            while(cursor.moveToNext())
            {
                gridSelected = cursor.getString(cursor.getColumnIndex(FEED_AUDIO_AUDIO));

                arrayList.add(gridSelected);
            }
        }

        db.close();

        Log.d(TAG, "getAudioForDownload arrayList size  is: "+arrayList.size());

        return arrayList;
    }
}

答案 1 :(得分:1)

创建数据库助手类。像这样:

import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Iterator;

public class DatabaseHelper {

    private static DatabaseHelper instance;
    private static final String TBNAME = "your first table name";
    private static final String OTHER_TB_NAME = "your other table name";

    private Context context;
    private SQLiteDatabase timedb;

    public static DatabaseHelper getInstance(Context context) {
        if (instance == null) {
            instance = new DatabaseHelper(context);
        }
        return instance;
    }

    private DatabaseHelper(Context context) {
        this.context = context;
        timedb = //your initialization
    }

    public void queryA(Intent data, String title) {
        String[] apath = data.getStringArrayExtra("all_path");
        ArrayList<String> strings = new ArrayList<String>();
        Iterator iterate = strings.iterator();
        for (String string : apath) {
            strings.add(string);
        }


        String query = "INSERT INTO " + TBNAME + " VALUES (?,?);";
        SQLiteStatement statement = timedb.compileStatement(query);
        timedb.beginTransaction();

        while (iterate.hasNext()) {
            statement.clearBindings();
            statement.bindString(1, title);
            statement.bindString(2, iterate.next().toString());
            statement.execute();
        }

        timedb.setTransactionSuccessful();
        timedb.endTransaction();
        timedb.close();
        Toast.makeText(context, "Successful", Toast.LENGTH_LONG).show();
    }
}

对于每个查询,您都可以创建一个新方法。获取帮助程序调用的实例:DatabaseHelper.getInstance()