Futuretask异步错误SQlite Android

时间:2013-05-25 18:53:19

标签: android sqlite transactions

我在申请时遇到了交易问题。简而言之,我正在构建一个程序来检索呼叫记录。这在模拟器上工作得很好,但不幸的是,当我在手机上尝试这个有大约300个通话记录时,需要超长时间!我读到创建单个事务会加快速度。但是,当我尝试这个时,我最终得到以下错误。现在我认为这可能只是我放置括号和我的endtransaction命令的问题,但我无法弄清楚这一点。 log cat上的错误似乎没有提供比指向该行更多的信息,并告诉我它是一个null异常。请在下面找到代码和错误日志。如果需要,将公布其他详细信息。

谢谢你!

我的主屏幕。

   @SuppressWarnings({ "deprecation", "deprecation" })

   public class EtiMainScreen extends TabActivity {

CallRecords recdb = new CallRecords(EtiMainScreen.this);

SQLiteDatabase calllog;
Context c = this;
Handler hand = new Handler();

TextView tvnatbun, tvnatrate, tvnatsms, tvintmbun, tvintmrate, tvsmsbun,
        tvsmsrate, tvintsmsrate, tvdatalbun, tvdatalrate, tvpackname,
        tvTotal;
private long mStartRX = 0;
private long mStartTX = 0;

@SuppressWarnings("deprecation")
protected void onCreate(Bundle Bundle) {
    super.onCreate(Bundle);

    setContentView(R.layout.eti_main_screen);
    super.onCreate(Bundle);

    TabHost tabHost = getTabHost();

    TabHost.TabSpec spec = getTabHost().newTabSpec("tag1");
    spec.setContent(R.id.mainmenu);
    spec.setIndicator("Main Menu");
    getTabHost().addTab(spec);

    getTabHost().setCurrentTab(0);

    spec = getTabHost().newTabSpec("tag2");
    spec.setContent(R.id.billhist);
    spec.setIndicator("Billing History");
    getTabHost().addTab(spec);

    for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
        TextView tv = (TextView) tabHost.getTabWidget().getChildAt(i)
                .findViewById(android.R.id.title);
        tv.setTextColor(Color.parseColor("#FFFFFF"));
    }

    TextView tv = (TextView) tabHost.getCurrentTabView().findViewById(
            android.R.id.title);
    tv.setTextColor(Color.parseColor("#FFFFFF"));

    ((Button) findViewById(R.id.alert))
            .setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {

                    Intent localIntent = new 
          Intent(EtiMainScreen.this,
                            Alerts.class);

       EtiMainScreen.this.startActivity(localIntent);
                }
            });

    Uri SMSsentQuery = Uri.parse("content://sms/sent");

    Cursor cursor1 = getContentResolver().query(SMSsentQuery, null, null,
            null, null);

    Cursor managedCursor = getContentResolver().query(
            android.provider.CallLog.Calls.CONTENT_URI, null,   
           null,null,null);

    mStartRX = TrafficStats.getMobileRxBytes();
    mStartTX = TrafficStats.getMobileTxBytes();
    long Totalbytes = mStartRX + mStartTX;

    Log.v("", Long.toString(mStartRX));
    Log.v("", Long.toString(mStartTX));
    Log.v("", Long.toString(Totalbytes));
    // int usage = Long.bitCount(Totalbytes) / 1024;

    calllog.beginTransaction();
    try {

        while (managedCursor.moveToNext()) {

            calllog.yieldIfContendedSafely();
            String callNumber = managedCursor.getString(managedCursor
                    .getColumnIndex(CallLog.Calls.NUMBER));
            String callType = managedCursor.getString(managedCursor
                    .getColumnIndex(CallLog.Calls.TYPE));
            String callDur = managedCursor.getString(managedCursor
                    .getColumnIndex(CallLog.Calls.DURATION));
            int dateId = managedCursor
        .getColumnIndex(android.provider.CallLog.Calls.DATE);

            long callDate = managedCursor.getLong(dateId);
            SimpleDateFormat datePattern = new SimpleDateFormat(
                    "yyyy-MM-dd HH:mm");
            String date_str = datePattern.format(new Date(callDate));

            int dircode = Integer.parseInt(callType);
            float value = Float.parseFloat(callDur);
            float callDuration = value / 60;

            recdb.open();

            ContentValues cv = new ContentValues();

            if (dircode == CallLog.Calls.OUTGOING_TYPE) {
                if (callNumber.startsWith("00971")
                        || callNumber.startsWith("05")
                        || callNumber.startsWith("04")
                        || callNumber.startsWith("03")
                        || callNumber.startsWith("02")) {

                    cv.put("cnatdur", callDuration);
                } else {
                    cv.put("cintdur", callDuration);
                }
            }
            int natsms = 0, intsms = 0;

            while (cursor1.moveToNext()) {
                String address = cursor1.getString(cursor1
                        .getColumnIndex("address"));

                if (address.startsWith("009-71")
                        || address.startsWith("(05")
                        || address.startsWith("05")) {

                    natsms++;
                    cv.put("natsms", natsms);

                } else {
                    intsms++;

                    cv.put("intsms", intsms);
                }

                cv.put("cdate", date_str);
                cv.put("localdata", Totalbytes);

                recdb.insertValues("records", cv);
                recdb.insertCalc();
                recdb.close();
            }
            cursor1.close();
        }

        managedCursor.close();
        calllog.setTransactionSuccessful();
    } catch (Exception e) {
    }
    calllog.endTransaction();

    // alertCheck();9

    tvpackname = (TextView) findViewById(R.id.packname);
    tvnatbun = (TextView) findViewById(R.id.tvnatmbun);
    tvnatrate = (TextView) findViewById(R.id.tvnatmrate);
    tvintmbun = (TextView) findViewById(R.id.tvinmbun);
    tvintmrate = (TextView) findViewById(R.id.tvintmrate);
    tvsmsbun = (TextView) findViewById(R.id.tvnatsmsbun);
    tvsmsrate = (TextView) findViewById(R.id.tvnatsmsrate);
    tvintsmsrate = (TextView) findViewById(R.id.tvintsmsrate);
    tvdatalbun = (TextView) findViewById(R.id.tvdlocbun);
    tvdatalrate = (TextView) findViewById(R.id.tvdlocrate);
    tvTotal = (TextView) findViewById(R.id.tvtotal);

    ArrayList<Object> row;

    row = recdb.callrecord(tvnatrate.getText().toString());

    tvpackname.setText((String) row.get(0));
    tvnatbun.setText((String) row.get(1));
    tvnatrate.setText((String) row.get(2));
    tvintmbun.setText((String) row.get(3));
    tvintmrate.setText((String) row.get(4));
    tvsmsbun.setText((String) row.get(5));
    tvsmsrate.setText((String) row.get(6));
    tvintsmsrate.setText((String) row.get(7));
    tvdatalbun.setText((String) row.get(8));
    tvdatalrate.setText((String) row.get(9));
    tvTotal.setText((String) row.get(10));

    recdb.close();

}

public void alertCheck() {

    Alerts al = new Alerts();

    ArrayList<Object> alertarr;

    alertarr = al.alerttype(toString());

    String a = ((String) alertarr.get(0));
    String b = ((String) alertarr.get(2));

    int aletot = Integer.parseInt(a);
    int allimit = Integer.parseInt(b);

    if (aletot >= (allimit * 50 / 100) && aletot < (allimit * 75 / 100)) {

        AlertDialog.Builder alert1 = new AlertDialog.Builder(this);
        alert1.setTitle("Warning! Usage - 50%");
        alert1.setMessage("Your total usage is now at 50%");
        alert1.show();
        alert1.setPositiveButton("OK", null);
    }

    if (aletot >= (allimit * 75 / 100) && aletot < (allimit * 100 / 100)) {
        AlertDialog.Builder alert2 = new AlertDialog.Builder(this);
        alert2.setTitle("Warning! Usage - 75%");
        alert2.setMessage("Your total usage is now at 75%");
        alert2.show();
        alert2.setPositiveButton("OK", null);
    }
    if (aletot >= (allimit * 100 / 100)) {
        AlertDialog.Builder alert3 = new AlertDialog.Builder(this);
        alert3.setTitle("Critical - Usage - 100%");
        alert3.setMessage("You have now reached your total usage limit!");
        alert3.show();
        alert3.setPositiveButton("OK", null);

    }

}

 }

LogCat:

05-25 18:36:08.715: E/AndroidRuntime(15647): FATAL EXCEPTION: main
05-25 18:36:08.715: E/AndroidRuntime(15647): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mbf/com.example.mobilebillforecaster.EtiMainScreen}: java.lang.NullPointerException
05-25 18:36:08.715: E/AndroidRuntime(15647):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
05-25 18:36:08.715: E/AndroidRuntime(15647):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
05-25 18:36:08.715: E/AndroidRuntime(15647):    at android.app.ActivityThread.access$600(ActivityThread.java:141)
05-25 18:36:08.715: E/AndroidRuntime(15647):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
05-25 18:36:08.715: E/AndroidRuntime(15647):    at android.os.Handler.dispatchMessage(Handler.java:99)
05-25 18:36:08.715: E/AndroidRuntime(15647):    at android.os.Looper.loop(Looper.java:137)
05-25 18:36:08.715: E/AndroidRuntime(15647):    at android.app.ActivityThread.main(ActivityThread.java:5039)
05-25 18:36:08.715: E/AndroidRuntime(15647):    at java.lang.reflect.Method.invokeNative(Native Method)
05-25 18:36:08.715: E/AndroidRuntime(15647):    at java.lang.reflect.Method.invoke(Method.java:511)
05-25 18:36:08.715: E/AndroidRuntime(15647):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-25 18:36:08.715: E/AndroidRuntime(15647):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-25 18:36:08.715: E/AndroidRuntime(15647):    at dalvik.system.NativeStart.main(Native Method)
05-25 18:36:08.715: E/AndroidRuntime(15647): Caused by: java.lang.NullPointerException
05-25 18:36:08.715: E/AndroidRuntime(15647):    at com.example.mobilebillforecaster.EtiMainScreen.onCreate(EtiMainScreen.java:111)
05-25 18:36:08.715: E/AndroidRuntime(15647):    at android.app.Activity.performCreate(Activity.java:5104)
05-25 18:36:08.715: E/AndroidRuntime(15647):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
05-25 18:36:08.715: E/AndroidRuntime(15647):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
05-25 18:36:08.715: E/AndroidRuntime(15647):    ... 11 more

感谢,

跟进上述问题

所以我继续并添加了在Async任务上运行的代码。但是,我在尝试执行时遇到以下错误。

05-30 21:41:10.353: E/AndroidRuntime(7221): FATAL EXCEPTION: AsyncTask #1
05-30 21:41:10.353: E/AndroidRuntime(7221): java.lang.RuntimeException: An error occured while executing doInBackground()
05-30 21:41:10.353: E/AndroidRuntime(7221):     at android.os.AsyncTask$3.done(AsyncTask.java:299)
05-30 21:41:10.353: E/AndroidRuntime(7221):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
05-30 21:41:10.353: E/AndroidRuntime(7221):     at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
05-30 21:41:10.353: E/AndroidRuntime(7221):     at java.util.concurrent.FutureTask.run(FutureTask.java:239)
05-30 21:41:10.353: E/AndroidRuntime(7221):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
05-30 21:41:10.353: E/AndroidRuntime(7221):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
05-30 21:41:10.353: E/AndroidRuntime(7221):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
05-30 21:41:10.353: E/AndroidRuntime(7221):     at java.lang.Thread.run(Thread.java:856)
05-30 21:41:10.353: E/AndroidRuntime(7221): Caused by: java.lang.NullPointerException
05-30 21:41:10.353: E/AndroidRuntime(7221):     at android.content.ContextWrapper.getContentResolver(ContextWrapper.java:99)
05-30 21:41:10.353: E/AndroidRuntime(7221):     at com.example.mobilebillforecaster.EtiMainScreen$callDataThread.doInBackground(EtiMainScreen.java:188)
05-30 21:41:10.353: E/AndroidRuntime(7221):     at com.example.mobilebillforecaster.EtiMainScreen$callDataThread.doInBackground(EtiMainScreen.java:1)
05-30 21:41:10.353: E/AndroidRuntime(7221):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
05-30 21:41:10.353: E/AndroidRuntime(7221):     at java.util.concurrent.FutureTask.run(FutureTask.java:234)
05-30 21:41:10.353: E/AndroidRuntime(7221):     ... 4 more

编码

MainScreen

package com.example.mobilebillforecaster;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.TabActivity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.net.TrafficStats;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.CallLog;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TabHost;
import android.widget.TextView;

import com.example.mbf.R;

@SuppressWarnings({ "deprecation", "deprecation" })
public class EtiMainScreen extends TabActivity {

    CallRecords recdb = new CallRecords(this);
    SQLiteDatabase calls;
    Context c = this;

    private TextView tvnatbun = null;
    private TextView tvnatrate = null;
    private TextView tvnatsms = null;
    private TextView tvintmbun = null;
    private TextView tvintmrate = null;
    private TextView tvsmsbun = null;
    private TextView tvsmsrate = null;
    private TextView tvintsmsrate = null;
    private TextView tvdatalbun = null;
    private TextView tvdatalrate = null;
    private TextView tvpackname = null;
    private TextView tvTotal = null;

    private long mStartRX = 0;
    private long mStartTX = 0;

    @SuppressWarnings("deprecation")
    protected void onCreate(Bundle Bundle) {
        super.onCreate(Bundle);
        setContentView(R.layout.eti_main_screen);



        initWidgets();

        TabHost tabHost = getTabHost();

        TabHost.TabSpec spec = getTabHost().newTabSpec("tag1");
        spec.setContent(R.id.mainmenu);
        spec.setIndicator("Main Menu");
        getTabHost().addTab(spec);

        getTabHost().setCurrentTab(0);

        spec = getTabHost().newTabSpec("tag2");
        spec.setContent(R.id.billhist);
        spec.setIndicator("Billing History");
        getTabHost().addTab(spec);

        for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
            TextView tv = (TextView) tabHost.getTabWidget().getChildAt(i)
                    .findViewById(android.R.id.title);
            tv.setTextColor(Color.parseColor("#FFFFFF"));
        }

        TextView tv = (TextView) tabHost.getCurrentTabView().findViewById(
                android.R.id.title);
        tv.setTextColor(Color.parseColor("#FFFFFF"));

        ((Button) findViewById(R.id.alert))
                .setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {

                        Intent localIntent = new Intent(EtiMainScreen.this,
                                Alerts.class);
                        EtiMainScreen.this.startActivity(localIntent);
                    }
                });


        // alertCheck();
        recdb.open();

        ArrayList<Object> row;

        row = recdb.callrecord(tvnatrate.getText().toString());

        tvpackname.setText((String) row.get(0));
        tvnatbun.setText((String) row.get(1));
        tvnatrate.setText((String) row.get(2));
        tvintmbun.setText((String) row.get(3));
        tvintmrate.setText((String) row.get(4));
        tvsmsbun.setText((String) row.get(5));
        tvsmsrate.setText((String) row.get(6));
        tvintsmsrate.setText((String) row.get(7));
        tvdatalbun.setText((String) row.get(8));
        tvdatalrate.setText((String) row.get(9));
        tvTotal.setText((String) row.get(10));

        recdb.close();

    }

    private void initWidgets() {
        tvpackname = (TextView) findViewById(R.id.packname);
        tvnatbun = (TextView) findViewById(R.id.tvnatmbun);
        tvnatrate = (TextView) findViewById(R.id.tvnatmrate);
        tvintmbun = (TextView) findViewById(R.id.tvinmbun);
        tvintmrate = (TextView) findViewById(R.id.tvintmrate);
        tvsmsbun = (TextView) findViewById(R.id.tvnatsmsbun);
        tvsmsrate = (TextView) findViewById(R.id.tvnatsmsrate);
        tvintsmsrate = (TextView) findViewById(R.id.tvintsmsrate);
        tvdatalbun = (TextView) findViewById(R.id.tvdlocbun);
        tvdatalrate = (TextView) findViewById(R.id.tvdlocrate);
        tvTotal = (TextView) findViewById(R.id.tvtotal);
    }

    public void alertCheck() {

        Alerts al = new Alerts();

        ArrayList<Object> alertarr;

        alertarr = al.alerttype(toString());

        String a = ((String) alertarr.get(0));
        String b = ((String) alertarr.get(2));

        int aletot = Integer.parseInt(a);
        int allimit = Integer.parseInt(b);

        if (aletot >= (allimit * 50 / 100) && aletot < (allimit * 75 / 100)) {

            AlertDialog.Builder alert1 = new AlertDialog.Builder(this);
            alert1.setTitle("Warning! Usage - 50%");
            alert1.setMessage("Your total usage is now at 50%");
            alert1.show();
            alert1.setPositiveButton("OK", null);
        }

        if (aletot >= (allimit * 75 / 100) && aletot < (allimit * 100 / 100)) {
            AlertDialog.Builder alert2 = new AlertDialog.Builder(this);
            alert2.setTitle("Warning! Usage - 75%");
            alert2.setMessage("Your total usage is now at 75%");
            alert2.show();
            alert2.setPositiveButton("OK", null);
        }
        if (aletot >= (allimit * 100 / 100)) {
            AlertDialog.Builder alert3 = new AlertDialog.Builder(this);
            alert3.setTitle("Critical - Usage - 100%");
            alert3.setMessage("You have now reached your total usage limit!");
            alert3.show();
            alert3.setPositiveButton("OK", null);

        }

    }

    public class callDataThread extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        // callRecordsHelper recdb =
        // callRecordsHelper.getDBAdapterInstance(EtiMainScreen.this);
        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub

            Uri SMSsentQuery = Uri.parse("content://sms/sent");

            Cursor cursor1 = getContentResolver().query(SMSsentQuery, null,
                    null, null, null);

            Cursor managedCursor = getContentResolver().query(
                    android.provider.CallLog.Calls.CONTENT_URI, null, null,
                    null, null);

            mStartRX = TrafficStats.getMobileRxBytes();
            mStartTX = TrafficStats.getMobileTxBytes();
            long Totalbytes = mStartRX + mStartTX;

            Log.v("", Long.toString(mStartRX));
            Log.v("", Long.toString(mStartTX));
            Log.v("", Long.toString(Totalbytes));
            int usage = Long.bitCount(Totalbytes) / 1024;

            recdb.open();
            // calls.beginTransaction();
            // try {
            if (managedCursor != null && managedCursor.moveToFirst()) {
                do {

                    String callNumber = managedCursor.getString(managedCursor
                            .getColumnIndex(CallLog.Calls.NUMBER));
                    String callType = managedCursor.getString(managedCursor
                            .getColumnIndex(CallLog.Calls.TYPE));
                    String callDur = managedCursor.getString(managedCursor
                            .getColumnIndex(CallLog.Calls.DURATION));
                    int dateId = managedCursor
                            .getColumnIndex(android.provider.CallLog.Calls.DATE);

                    long callDate = managedCursor.getLong(dateId);
                    SimpleDateFormat datePattern = new SimpleDateFormat(
                            "yyyy-MM-dd HH:mm");
                    String date_str = datePattern.format(new Date(callDate));

                    int dircode = Integer.parseInt(callType);
                    float value = Float.parseFloat(callDur);
                    float callDuration = value / 60;

                    // calls.yieldIfContendedSafely();
                    ContentValues cv = new ContentValues();

                    if (dircode == CallLog.Calls.OUTGOING_TYPE) {
                        if (callNumber.startsWith("00971")
                                || callNumber.startsWith("05")
                                || callNumber.startsWith("04")
                                || callNumber.startsWith("03")
                                || callNumber.startsWith("02")) {

                            cv.put("cnatdur", callDuration);
                        } else {
                            cv.put("cintdur", callDuration);
                        }
                    }
                    int natsms = 0, intsms = 0;
                    if (cursor1 != null && cursor1.moveToFirst()) {
                        do {
                            String address = cursor1.getString(cursor1
                                    .getColumnIndex("address"));

                            if (address.startsWith("009-71")
                                    || address.startsWith("(05")
                                    || address.startsWith("05")) {

                                natsms++;
                                cv.put("natsms", natsms);

                            } else {
                                intsms++;

                                cv.put("intsms", intsms);
                            }

                            cv.put("cdate", date_str);
                            cv.put("localdata", usage);

                            recdb.insertValues("records", cv);
                            recdb.insertCalc();
                            recdb.close();
                        } while (cursor1.moveToNext());
                        cursor1.close();
                    }
                } while (managedCursor.moveToNext());
                managedCursor.close();
            }

            // calls.setTransactionSuccessful();
            // } finally {
            // calls.endTransaction();
            // }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
        }
    }
}

非常感谢任何协助。

感谢

1 个答案:

答案 0 :(得分:0)

我建议将callog.endtransaction()包裹在finally {}块中。

} catch (Exception e) {
} finally {
    calllog.endTransaction();
}

我还建议不要在UI线程上运行这种查询,而是使用AsyncTaskAsyncTaskLoader

http://developer.android.com/reference/android/os/AsyncTask.html http://developer.android.com/reference/android/content/AsyncTaskLoader.html