如何从不同的线程或意图服务调用getWritableDatabase(),App在主线程中调用它时崩溃

时间:2015-08-19 11:48:06

标签: android multithreading sqlite android-intent intentservice

这是主要活动

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;



public class MainActivity extends AppCompatActivity {

    EditText myinput;
    TextView mytext;
    MyDBHandler dbhandler;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);




        myinput =(EditText) findViewById(R.id.myinput);
        mytext =(TextView) findViewById(R.id.mytext);
        dbhandler= new MyDBHandler(this, null, null, 1);
        printDatabase();


    }

    //add product to database

    public void addstuff(View view)
    {
        products product = new products(myinput.getText().toString());
        dbhandler.addProduct(product);
        printDatabase();

    }

    //delete items from database

    public void deletestuff(View view)
    {
        String inputtext= myinput.getText().toString();
        dbhandler.deleteProduct(inputtext);
        printDatabase();


    }

    public void printDatabase()
    {
        String dbString= dbhandler.databaseToString();
        mytext.setText(dbString);
        myinput.setText("");
    }

}

产品类,获取和设置产品

public class products {

    private int _id;
    private String _productname;

    public products()
    {

    }

    public products(String productname) {
        this._productname = productname;
    }

    public void set_id(int _id) {
        this._id = _id;
    }

    public void set_productname(String _productname) {
        this._productname = _productname;
    }

    public int get_id() {
        return _id;
    }

    public String get_productname() {
        return _productname;
    }
}

数据库处理程序类

import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.Cursor;
import android.content.Context;
import android.content.ContentValues;


public class MyDBHandler extends SQLiteOpenHelper{

    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "products.db";
    public static final String TABLE_PRODUCTS = "products";
    public static final String COLUMN_ID ="_id";
    public static final String COLUMN_PRODUCTNAME ="productname";


    public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, DATABASE_NAME, factory, DATABASE_VERSION);
    }


    @Override
    public void onCreate(SQLiteDatabase db) {

        String query= "CREATE TABLE " + TABLE_PRODUCTS + "(" +
                COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT , " +
                COLUMN_PRODUCTNAME + " TEXT " +
                ");";
        db.execSQL(query);

    }

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

    //add a new row to the database
    public void addProduct(products product)
    {
        ContentValues values = new ContentValues();
        values.put(COLUMN_PRODUCTNAME, product.get_productname());
        SQLiteDatabase db= getWritableDatabase();
        db.insert(TABLE_PRODUCTS, null, values);
        db.close();
    }

    //delete product from the database
    public void deleteProduct(String productname)
    {
        SQLiteDatabase db= getWritableDatabase();
        db.execSQL("DELETE FROM "+ TABLE_PRODUCTS + " WHERE " + COLUMN_PRODUCTNAME + " =\"" + productname + "\";" );
    }

    //printing out the database as a string

    public String databaseToString()
    {
        String dbString ="";
        SQLiteDatabase db= getWritableDatabase();
        String query = "SELECT * FROM "+ TABLE_PRODUCTS + " WHERE 1";

        //CURSOR POINTS TO A LOCATION IN THE DATABASE RESULTS
        Cursor c= db.rawQuery(query,null);
        //go to 1st row in your results
        c.moveToFirst();

        while(!c.isAfterLast())
        {
            if(c.getString(c.getColumnIndex("productname"))!=null)
            {
                dbString += c.getString(c.getColumnIndex("productname"));
                dbString += "\n";

            }

        }
        db.close();
        return dbString;

    }



}

我尝试将getwritabledatabase()代码放在runnables中,但是他们可以为databasetostring()方法执行此操作。

如何从Intent Service调用getWritableDatabase()?

我想将此intent服务用于getWritableDatabase()

import android.app.IntentService;
import android.content.Intent;

public class myintent extends IntentService{

    public myintent(String name) {
        super("myintent");
    }

    @Override
    protected void onHandleIntent(Intent intent) {

    }
}

我不知道如何通过INTENT SERVICE

来做到这一点

这是应用启动后的logcat

8-19 17:56:08.848  15523-15523/? I/art﹕ Late-enabling -Xcheck:jni
08-19 17:56:08.848  15523-15523/? I/art﹕ VMHOOK: rlim_cur : 0 pid:15523
08-19 17:56:09.218  15523-15523/com.example.vashisht.sqliteapp D/Atlas﹕ Validating map...
08-19 17:56:09.278  15523-15554/com.example.vashisht.sqliteapp I/Adreno-EGL﹕ <qeglDrvAPI_eglInitialize:410>: EGL 1.4 QUALCOMM build: TEST SBA LA.BF.1.1.1_RB1 AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.00.02.042.012 + c1105519 + c_apilogging ()
    OpenGL ES Shader Compiler Version: E031.25.03.00
    Build Date: 01/23/15 Fri
    Local Branch:
    Remote Branch: refs/tags/AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.00.02.042.012
    Local Patches: NONE
    Reconstruct Branch: NOTHING
08-19 17:56:09.478  15523-15523/com.example.vashisht.sqliteapp I/InputMethodManager﹕ [startInputInner] EditorInfo { packageName=com.example.vashisht.sqliteapp, inputType=0x20001, imeOptions=0x40000006, privateImeOptions=null }, windowGainingFocus=android.view.ViewRootImpl$W@1287b4e7, mServedView=android.support.v7.widget.AppCompatEditText{e909894 VFED..CL .F....I. 90,222-990,335 #7f0c004f app:id/myinput}, mServedInputConnectionWrapper=android.view.inputmethod.InputMethodManager$ControlledInputConnectionWrapper@18863f3d

当我在文本字段中输入文本并点击添加按钮(向数据库表添加条目)时,应用程序冻结,logcat如下所示:

8-19 17:56:09.478  15523-15523/com.example.vashisht.sqliteapp I/InputMethodManager﹕ [startInputInner] EditorInfo { packageName=com.example.vashisht.sqliteapp, inputType=0x20001, imeOptions=0x40000006, privateImeOptions=null }, windowGainingFocus=android.view.ViewRootImpl$W@1287b4e7, mServedView=android.support.v7.widget.AppCompatEditText{e909894 VFED..CL .F....I. 90,222-990,335 #7f0c004f app:id/myinput}, mServedInputConnectionWrapper=android.view.inputmethod.InputMethodManager$ControlledInputConnectionWrapper@18863f3d
08-19 17:57:30.878  15523-15523/com.example.vashisht.sqliteapp I/InputMethodManager﹕ [startInputInner] EditorInfo { packageName=com.example.vashisht.sqliteapp, inputType=0x20001, imeOptions=0x40000006, privateImeOptions=null }, windowGainingFocus=null, mServedView=android.support.v7.widget.AppCompatEditText{e909894 VFED..CL .F...... 90,222-990,335 #7f0c004f app:id/myinput}, mServedInputConnectionWrapper=android.view.inputmethod.InputMethodManager$ControlledInputConnectionWrapper@2072768a
08-19 17:57:30.888  15523-15523/com.example.vashisht.sqliteapp W/IInputConnectionWrapper﹕ performPrivateCommand on inactive InputConnection
08-19 17:57:30.918  15523-15523/com.example.vashisht.sqliteapp W/IInputConnectionWrapper﹕ performPrivateCommand on inactive InputConnection
08-19 17:57:35.338  15523-15523/com.example.vashisht.sqliteapp I/InputMethodManager﹕ [startInputInner] EditorInfo { packageName=com.example.vashisht.sqliteapp, inputType=0x20001, imeOptions=0x40000006, privateImeOptions=null }, windowGainingFocus=android.view.ViewRootImpl$W@1287b4e7, mServedView=android.support.v7.widget.AppCompatEditText{e909894 VFED..CL .F....I. 90,222-990,335 #7f0c004f app:id/myinput}, mServedInputConnectionWrapper=android.view.inputmethod.InputMethodManager$ControlledInputConnectionWrapper@2996b4fb
08-19 17:57:42.158  15523-15533/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 5.091ms
08-19 17:57:42.608  15523-15538/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 9.910ms
08-19 17:57:55.408  15523-15538/com.example.vashisht.sqliteapp I/art﹕ Background partial concurrent mark sweep GC freed 180(6KB) AllocSpace objects, 108(15MB) LOS objects, 43% free, 5MB/9MB, paused 9.448ms total 36.167ms
08-19 17:57:59.468  15523-15538/com.example.vashisht.sqliteapp I/art﹕ Background partial concurrent mark sweep GC freed 43(1488B) AllocSpace objects, 24(4MB) LOS objects, 40% free, 6MB/10MB, paused 10.028ms total 18.813ms
08-19 17:58:00.478  15523-15538/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 9.383ms
08-19 17:58:11.218  15523-15533/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 5.913ms
08-19 17:58:14.328  15523-15537/com.example.vashisht.sqliteapp I/art﹕ WaitForGcToComplete blocked for 5.482ms for cause HeapTrim
08-19 17:58:15.628  15523-15538/com.example.vashisht.sqliteapp I/art﹕ Background partial concurrent mark sweep GC freed 60(2064B) AllocSpace objects, 32(7MB) LOS objects, 39% free, 6MB/10MB, paused 11.181ms total 21.280ms
08-19 17:58:16.248  15523-15533/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 10.318ms
08-19 17:58:26.088  15523-15538/com.example.vashisht.sqliteapp I/art﹕ Background sticky concurrent mark sweep GC freed 19(688B) AllocSpace objects, 9(2MB) LOS objects, 24% free, 5MB/7MB, paused 5.279ms total 10.035ms
08-19 17:58:28.778  15523-15533/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 5.467ms
08-19 17:58:31.278  15523-15533/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 6.368ms
08-19 17:58:34.298  15523-15533/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 6.308ms
08-19 17:58:34.348  15523-15537/com.example.vashisht.sqliteapp I/art﹕ WaitForGcToComplete blocked for 10.169ms for cause HeapTrim
08-19 17:58:36.798  15523-15533/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 5.915ms
08-19 17:58:38.918  15523-15538/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 16.815ms
08-19 17:58:44.538  15523-15538/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 8.032ms
08-19 17:58:44.878  15523-15538/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 5.364ms
08-19 17:58:44.878  15523-15538/com.example.vashisht.sqliteapp I/art﹕ Background partial concurrent mark sweep GC freed 35(1184B) AllocSpace objects, 22(7MB) LOS objects, 54% free, 3MB/7MB, paused 5.855ms total 17.791ms
08-19 17:58:46.248  15523-15538/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 7.053ms
08-19 17:58:46.268  15523-15538/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 9.842ms
08-19 17:58:46.268  15523-15538/com.example.vashisht.sqliteapp I/art﹕ Background sticky concurrent mark sweep GC freed 26(928B) AllocSpace objects, 12(4MB) LOS objects, 21% free, 6MB/7MB, paused 10.751ms total 18.381ms
08-19 17:58:48.828  15523-15533/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 5.178ms
08-19 17:58:48.868  15523-15538/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 7.268ms
08-19 17:58:49.538  15523-15538/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 9.654ms
08-19 17:58:50.838  15523-15533/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 7.434ms
08-19 17:58:54.758  15523-15538/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 8.813ms
08-19 17:58:54.758  15523-15538/com.example.vashisht.sqliteapp I/art﹕ Background sticky concurrent mark sweep GC freed 24(864B) AllocSpace objects, 11(3MB) LOS objects, 27% free, 6MB/8MB, paused 9.415ms total 14.852ms
08-19 17:58:56.798  15523-15538/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 9.198ms
08-19 17:58:56.808  15523-15538/com.example.vashisht.sqliteapp I/art﹕ Background partial concurrent mark sweep GC freed 39(1328B) AllocSpace objects, 23(8MB) LOS objects, 39% free, 6MB/10MB, paused 10.067ms total 19.829ms
08-19 17:59:03.098  15523-15538/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 7.042ms
08-19 17:59:03.108  15523-15538/com.example.vashisht.sqliteapp I/art﹕ Background partial concurrent mark sweep GC freed 23(784B) AllocSpace objects, 14(5MB) LOS objects, 54% free, 3MB/7MB, paused 7.720ms total 22.105ms
08-19 17:59:04.368  15523-15537/com.example.vashisht.sqliteapp I/art﹕ WaitForGcToComplete blocked for 8.374ms for cause HeapTrim
08-19 17:59:18.878  15523-15533/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 8.496ms
08-19 17:59:21.378  15523-15533/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 6.302ms
08-19 17:59:21.658  15523-15538/com.example.vashisht.sqliteapp I/art﹕ Background partial concurrent mark sweep GC freed 35(1184B) AllocSpace objects, 21(8MB) LOS objects, 39% free, 6MB/11MB, paused 5.077ms total 23.084ms
08-19 17:59:24.078  15523-15538/com.example.vashisht.sqliteapp I/art﹕ Background partial concurrent mark sweep GC freed 27(928B) AllocSpace objects, 15(6MB) LOS objects, 52% free, 3MB/7MB, paused 9.533ms total 23.103ms

然后我手动需要杀死应用程序,或者在一段时间后它说不响应!!

我修改了databasetostring()方法以返回一个字符串数组,这样我就可以在listview中显示结果。

 public String[] databaseToString()
    {


        String[] dbString;
        dbString = new String[]{};

        SQLiteDatabase db= getReadableDatabase();
        String query = "SELECT * FROM "+ TABLE_PRODUCTS + " WHERE 1";

        //CURSOR POINTS TO A LOCATION IN THE DATABASE RESULTS
        Cursor c= db.rawQuery(query,null);
        //go to 1st row in your results
        c.moveToFirst();
        int i=0;
        while(!c.isAfterLast())
        {
            if(c.getString(c.getColumnIndex(COLUMN_PRODUCTNAME))!=null)
                dbString[i] = c.getString(c.getColumnIndex(COLUMN_PRODUCTNAME));

            i++;

        }
        db.close();

        return dbString;


    }

但是在这里,dbString[i] = c.getString(c.getColumnIndex(COLUMN_PRODUCTNAME));抛出数组超出范围异常???

2 个答案:

答案 0 :(得分:1)

要从IntentService拨打电话,只需拨打此电话

即可
sqLiteDatabase = getApplicationContext().getWritableDatabase();

getApplicationContext()扩展IntentService

以来,您需要Context

答案 1 :(得分:-1)

        }
        db.close();
        return dbString;

    }



}

问题在这里,我忘了将光标移动到下一个结果,这导致无限循环! oooops!

static  FragmentB f;

public static FragmentB newInstance(String title) {
        FragmentB f = new FragmentB();
        Bundle b = new Bundle();
        b.putString(ARG_STATION_TITLE, title);
        f.setArguments(b);
        return f;
    }