Android数据库应用程序冻结,然后在设备上运行时崩溃

时间:2015-08-18 18:50:48

标签: android sqlite

这是一个简单的数据库应用程序,它将某些内容存储在表格中(按钮点击)并删除(按钮点击)。在设备(棒棒糖)上安装应用程序时,会弹出主要活动,但只要我在文本字段中输入一些文本并单击按钮将其保存到数据库,应用程序会冻结并在一段时间后强制关闭。如果我尝试再次运行应用程序,然后主活动无法启动,应用程序强制关闭。

这是主要活动,

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



public class MainActivity extends ActionBarActivity {

    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("");
    }

}

这是数据库处理程序类

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;

    }



}

这是我用来设置和获取名字的产品类

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

App冻结,

  08-19 00:46:24.567  24251-24251/com.example.vashisht.sqliteapp I/art﹕ Late-enabling -Xcheck:jni
08-19 00:46:24.567  24251-24251/com.example.vashisht.sqliteapp I/art﹕ VMHOOK: rlim_cur : 0 pid:24251
08-19 00:46:24.887  24251-24251/com.example.vashisht.sqliteapp D/Atlas﹕ Validating map...
08-19 00:46:24.937  24251-24300/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 00:46:25.077  24251-24251/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 00:46:31.627  24251-24261/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 7.228ms
08-19 00:46:34.287  24251-24266/com.example.vashisht.sqliteapp I/art﹕ Background sticky concurrent mark sweep GC freed 143(4KB) AllocSpace objects, 84(4MB) LOS objects, 8% free, 5MB/5MB, paused 5.643ms total 24.844ms
08-19 00:46:34.987  24251-24265/com.example.vashisht.sqliteapp I/art﹕ WaitForGcToComplete blocked for 9.670ms for cause HeapTrim
08-19 00:46:36.647  24251-24261/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 5.596ms

我杀了应用

08-19 00:49:09.147    1196-1196/? D/NetworkController﹕ [WifiActivity] Connectd: 3
08-19 00:49:09.177     963-1155/? E/WifiStateMachine﹕ handleMessage: E msg.what=131155
08-19 00:49:09.177     963-1155/? E/WifiStateMachine﹕ processMsg: ConnectedState
08-19 00:49:09.177     963-1155/? E/WifiStateMachine﹕ ConnectedState !CMD_RSSI_POLL 888 0 "unbreakable_13_90" 3c:1e:04:5b:2f:2d rssi=-40 f=2412 sc=60 link=150 tx=13.0, 0.0, 0.0  rx=12.5 bcn=0 [on:0 tx:0 rx:0 period:816] from screen [on:0 period:1111505026] gl hn u24 rssi=-35 ag=0 hr ticks 4,88,362 ls-=0 [56,56,60,60,65] brc=0 lrc=0
08-19 00:49:09.177     963-1155/? E/WifiStateMachine﹕ processMsg: L2ConnectedState
08-19 00:49:09.177     963-1155/? E/WifiStateMachine﹕ L2ConnectedState !CMD_RSSI_POLL 888 0 "unbreakable_13_90" 3c:1e:04:5b:2f:2d rssi=-40 f=2412 sc=60 link=150 tx=13.0, 0.0, 0.0  rx=12.5 bcn=0 [on:0 tx:0 rx:0 period:3] from screen [on:0 period:1111505029] gl hn u24 rssi=-35 ag=0 hr ticks 4,88,362 ls-=0 [56,56,60,60,65] brc=0 lrc=0
08-19 00:49:09.187     963-1155/? E/WifiStateMachine﹕ get link layer stats 0
08-19 00:49:09.187     963-1155/? W/WifiHW﹕ QCOM Debug wifi_send_command "IFNAME=wlan0 SIGNAL_POLL"
08-19 00:49:09.187      763-763/? D/wpa_supplicant﹕ wlan0: Control interface command 'SIGNAL_POLL'
08-19 00:49:09.197      763-763/? I/wpa_supplicant﹕ environment dirty rate=0 [6][0][0]
08-19 00:49:09.197     963-1155/? E/WifiStateMachine﹕ fetchRssiLinkSpeedAndFrequencyNative RSSI = -39 abnormalRssiCnt = 0 newLinkSpeed = 150
08-19 00:49:09.197     963-1155/? E/WifiStateMachine﹕ fetchRssiLinkSpeedAndFrequencyNative rssi=-39 linkspeed=150
08-19 00:49:09.197     963-1155/? E/WifiConfigStore﹕ updateConfiguration freq=2412 BSSID=3c:1e:04:5b:2f:2d RSSI=-39 "unbreakable_13_90"WPA_PSK
08-19 00:49:09.197     963-1155/? E/WifiStateMachine﹕ calculateWifiScore freq=2412 speed=150 score=60 highRSSI  -> txbadrate=0.00 txgoodrate=9.52 txretriesrate=0.00 rxrate=9.23 userTriggerdPenalty0
08-19 00:49:09.197     963-1155/? E/WifiStateMachine﹕ good link -> stuck count =0
08-19 00:49:09.197     963-1155/? E/WifiStateMachine﹕ badRSSI count0 lowRSSI count0 --> score 60
08-19 00:49:09.197     963-1155/? E/WifiStateMachine﹕ isHighRSSI       ---> score=65
08-19 00:49:09.207     963-1173/? D/WifiWatchdogStateMachine﹕ RSSI current: 3 new: -39, 3
08-19 00:49:09.207    1196-1196/? D/NetworkController﹕ updateWifiState: newRssi=-39 newLevel=3 lastWifiLevel=3 offload=false numLevels=4
08-19 00:49:09.207     963-1155/? E/WifiStateMachine﹕ handleMessage: X
08-19 00:49:09.747     963-1589/? W/ActivityManager﹕ getTasks: caller 10254 does not hold GET_TASKS; limiting output
08-19 00:49:10.157      963-963/? E/WifiTrafficPoller﹕ TRAFFIC_STATS_POLL true Token 2500 num clients 11
08-19 00:49:10.157      963-963/? E/WifiTrafficPoller﹕ packet count Tx=764946 Rx=977505
08-19 00:49:10.157      963-963/? E/WifiTrafficPoller﹕ notifying of data activity 1
08-19 00:49:10.167    1196-1196/? D/NetworkController﹕ [WifiActivity] Connectd: 1
08-19 00:49:10.197      963-963/? D/HtcWifiControlRoamOffload:﹕ Receive mPhoneStateListener
08-19 00:49:10.197      963-963/? D/HtcWifiControlRoamOffload:﹕ Receive mPhoneStateListener, getGsmSignalStrength7
08-19 00:49:10.207    1196-1196/? D/NetworkController﹕ [Strength][1][GSM] SignalStrength: 7 99 -120 -160 -120 -1 -1 99 2147483647 2147483647 2147483647 -1 -1 gsm|lte
08-19 00:49:10.217    1196-1196/? D/NetworkController﹕ [SYSTEMUI_UPDATE_SIGNAL_STRENGTH] level1=0 level2=2
08-19 00:49:10.707     963-1590/? I/art﹕ Explicit concurrent mark sweep GC freed 39093(2MB) AllocSpace objects, 2(296KB) LOS objects, 33% free, 29MB/44MB, paused 1.617ms total 199.088ms
08-19 00:49:10.787     963-1479/? W/ActivityManager﹕ getTasks: caller 10254 does not hold GET_TASKS; limiting output
08-19 00:49:11.187      963-963/? E/WifiTrafficPoller﹕ TRAFFIC_STATS_POLL true Token 2500 num clients 11
08-19 00:49:11.187      963-963/? E/WifiTrafficPoller﹕ packet count Tx=764947 Rx=977505
08-19 00:49:11.187      963-963/? E/WifiTrafficPoller﹕ notifying of data activity 2
08-19 00:49:11.197    1196-1196/? D/NetworkController﹕ [WifiActivity] Connectd: 2
08-19 00:49:11.827     963-1622/? W/ActivityManager﹕ getTasks: caller 10254 does not hold GET_TASKS; limiting output
08-19 00:49:12.197    1196-1431/? I/IntentController﹕ receive(android.provider.Telephony.SPN_STRINGS_UPDATED,1,false)
08-19 00:49:12.197    1441-1441/? D/WifiManager﹕ setCountryCode: Base Package Name=com.android.phone, uid=1001
08-19 00:49:12.197    1441-1441/? D/MccTable﹕ updateMccMncConfiguration mccmnc='null' fromServiceState=true
08-19 00:49:12.197     963-1141/? E/WifiStateMachine﹕ Ignoring resetting of country code

我猜应用程序代码不会抛出异常。

还有一些gradle sync问题,我应该在这做什么?

Warning:The project encoding (windows-1252) does not match the encoding specified in the Gradle build files (UTF-8).
This can lead to serious bugs.
<a href="http://tools.android.com/knownissues/encoding">More Info...</a><br><a href="open.encodings.settings">Open File Encoding Settings</a>

我应该更改项目编码还是gradle构建文件? 我该如何纠正这个?

logcat堆栈跟踪

08-19 01:11:27.257    5372-5384/? E/AndroidHttpClient﹕ Leak found
    java.lang.IllegalStateException: AndroidHttpClient created and never closed
            at com.google.android.volley.AndroidHttpClient.<init>(AndroidHttpClient.java:202)
            at com.google.android.volley.AndroidHttpClient.newInstance(AndroidHttpClient.java:170)
            at com.google.android.volley.GoogleHttpClient.<init>(GoogleHttpClient.java:146)
            at com.google.android.volley.GoogleHttpClient.<init>(GoogleHttpClient.java:113)
            at com.google.android.finsky.FinskyApp.onCreate(FinskyApp.java:366)
            at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1024)
            at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4947)
            at android.app.ActivityThread.access$1500(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1424)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:155)
            at android.app.ActivityThread.main(ActivityThread.java:5696)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1029)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:824)

当我按下按钮向数据库添加内容时,会发生这种情况

08-19 01:30:25.477  17029-17029/? I/art﹕ Late-enabling -Xcheck:jni
08-19 01:30:25.477  17029-17029/? I/art﹕ VMHOOK: rlim_cur : 0 pid:17029
08-19 01:30:25.517  17029-17039/? I/art﹕ Debugger is no longer active
08-19 01:30:25.687  17029-17029/? D/Atlas﹕ Validating map...
08-19 01:30:25.737  17029-17048/? 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 01:30:25.857  17029-17029/? 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 01:30:36.817  17029-17039/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 5.739ms
08-19 01:30:41.217  17029-17044/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 9.796ms
08-19 01:30:42.817  17029-17039/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 6.697ms
08-19 01:30:44.907  17029-17044/com.example.vashisht.sqliteapp I/art﹕ Background partial concurrent mark sweep GC freed 98(3KB) AllocSpace objects, 58(6MB) LOS objects, 44% free, 4MB/8MB, paused 9.494ms total 18.435ms
08-19 01:30:46.327  17029-17039/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 6.438ms
08-19 01:30:47.017  17029-17044/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 6.799ms
08-19 01:30:47.967  17029-17044/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 9.295ms
08-19 01:30:47.967  17029-17044/com.example.vashisht.sqliteapp I/art﹕ Background partial concurrent mark sweep GC freed 80(2768B) AllocSpace objects, 46(5MB) LOS objects, 54% free, 3MB/7MB, paused 10.332ms total 23.127ms
08-19 01:30:51.697  17029-17044/com.example.vashisht.sqliteapp I/art﹕ Background partial concurrent mark sweep GC freed 72(2496B) AllocSpace objects, 42(6MB) LOS objects, 68% free, 1847KB/5MB, paused 7.996ms total 21.588ms
08-19 01:30:57.847  17029-17039/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 5.385ms
08-19 01:31:03.587  17029-17044/com.example.vashisht.sqliteapp W/art﹕ Suspending all threads took: 8.907ms

logcat显示这些暂停线程消息,应用程序仍然冻结,然后我必须杀死应用程序!!

2 个答案:

答案 0 :(得分:1)

while循环中缺少moveToNext()方法调用:

while(!c.isAfterLast()) {

    if (c.getString(c.getColumnIndex("productname")) != null) {

            dbString += c.getString(c.getColumnIndex("productname"));
            dbString += "\n";
    }

    c.moveToNext();
}

答案 1 :(得分:0)

您是否缺少SQLLite游标工厂?

在上面的活动中执行此操作:onCreate:

private SQLiteDatabase.CursorFactory cursorFactory = new SQLiteDatabase.CursorFactory() {

            @Override
            public Cursor newCursor(SQLiteDatabase db, SQLiteCursorDriver masterQuery, String editTable, SQLiteQuery query) {
                // TODO handle cursor creation from passed in query
                return null;
            }
        };

然后修改您的数据库创建:

dbhandler= new MyDBHandler(this, null, cursorFactory, 1);