本文介绍了AsyncTask的RuntimeException的和在doInBackground的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当它调用了两个函数connecttask和connecttaskproperty发生错误。如果只召唤connecttask它的作品。谁能帮助?

私有类DelayedTask的扩展的TimerTask
    {

  @覆盖
    公共无效的run(){
        字符串URL =...;
        Log.i(变量,定时任务执行);        // code更新SQLite数据库
        尝试{            INT K = db.getReportsCount();
            Log.d(send0,getReports);
            的for(int i = 1; I< K + 1;我++){
                Log.d(send2,getReports);
                报告报告=新报告();
                报告= db.getReport(I)
                Log.d(SEND1,getReport);
                INT公布;
                张贴= report.getPosted();
                Log.d(发送,将String.valueOf(转贴));
                如果(贴== 0){
                    // asynTaskParam =新AsyncTaskParam(报告,URL);
                    // asynTaskParam
                    地图<整数,报告> HashMap的=新的HashMap<整数,报告>();                    hashmap.put(I,报告);
                    新ConnectTask()执行(HashMap的);
                    Log.d(发送,将String.valueOf(HashMap中));
                    //新ConnectTaskProperty()执行(HashMap中)。
                    // Log.d(发送,物业);
                 / *新ConnectTaskRental()执行(HashMap中)。
                    Log.d(送,租赁);
                    新ConnectTaskCar()执行(HashMap的);
                    Log.d(送,汽车);
                    新ConnectTaskOtherAsset()执行(HashMap的);
                    Log.d(送,办公自动化);
                    新ConnectTaskBussinessAsset()执行(HashMap的);
                    Log.d(发送,企业资产);
                    新ConnectTaskDebt()执行(HashMap的);
                    Log.d(送,债); * /                    db.getIdPosted(ⅰ);
                    Log.d(Odebrałem,CZY zmieniono);
                }
            }
        }赶上(例外五){
            e.printStackTrace();
        }
        Log.d(选择,测试);
    }
}    私有类ConnectTask扩展的AsyncTask< / * * AsyncTaskParam /地图<整数,报告>中太虚,字符串> {

私有类ConnectTask延伸AsyncTask的,无效的字符串> {

  @覆盖
    保护字符串doInBackground(地图<整数,报告与GT; / * AsyncTaskParam * / ... PARAMS){
        地图<整数,报告> localHashmap =参数[0];
        字符串结果;
        checkConnectivity(上下文);
        结果=的doPost(localHashmap);
        返回结果;
    }    @覆盖
    保护无效onPostExecute(字符串结果){
        如果(结果!= NULL){
            Toast.makeText(ReportMainScreen.this,资讯recuperada:[+结果+],
                    Toast.LENGTH_LONG).show();
        }其他{
            Toast.makeText(ReportMainScreen.this,错误人tratar德conectar CON EL servidor。
                    Toast.LENGTH_LONG).show();
        }
    }
}公共字符串的doPost(地图<整数,报告> localHashmap){
    //的HttpParams httpParameters =新BasicHttpParams();
    //硒ponen 3 segundos德超时。
    // HttpConnectionParams.setConnectionTimeout(httpParameters,30000);
    // localHashmap.get(1);
    //的for(int i = 0; I< localHashmap.size()+ 1;我++)
    // {
    整数reportId = NULL;
    报告reportRecord = NULL;    迭代它= localHashmap.entrySet()迭代器()。
    而(it.hasNext()){
        Map.Entry对=(Map.Entry的)it.next();
        reportId =(整数)pairs.getKey();
        reportRecord =(报告)pairs.getValue();        //的System.out.println(pairs.getKey()+=+ pairs.getValue());
        it.remove(); //避免了ConcurrentModificationException的
    }
    //}
    整数EncounterId = reportRecord.getEncounter_id();
    遇到encounterLocal = db.getEncounter(EncounterId);
    整数ReportId = reportRecord.getId();
    个人personalLocal = db.getPersonal(ReportId);
    字符串URL =...;    HttpClient的客户端=新DefaultHttpClient(/ * * httpParameters /);
    HttpPost httpPost =新HttpPost(URL);    尝试{        //构建JSON对象来传递参数
        JSONObject的jsonObj =新的JSONObject();
        jsonObj.put(KEY1,reportRecord.getEncounter_id());
        jsonObj.put(KEY2,encounterLocal.getEncounterFee());
        jsonObj.put(KEY3,encounterLocal.getEncounterTax());
        jsonObj.put(KEY4,encounterLocal.getEncounterSettlement());
        jsonObj.put(KEY5,encounterLocal.getEncounterMetWith());
        jsonObj.put(key6,encounterLocal.getEncounterProxy());
        jsonObj.put(KEY7,reportRecord.getTax_excess());
        jsonObj.put(key8,reportRecord.getOutlays());
        jsonObj.put(key9,personalLocal.getReg_number());
        jsonObj.put(key10,personalLocal.getTelephone());
        jsonObj.put(key11,personalLocal.getMartial_status());
        jsonObj.put(key12,personalLocal.getChildren());
        jsonObj.put(key13,personalLocal.getOc​​cupation());
        jsonObj.put(key14,personalLocal.getIncome());
        jsonObj.put(key15,personalLocal.getSpouse_income());
        jsonObj.put(key16,personalLocal.getDisposable_income());
        jsonObj.put(key17,reportRecord.getInstallments());
        日期格式DATEFORMAT =新的SimpleDateFormat(EEE MMM DD HH:MM:SS ZZZ YYYY,Locale.US);
        Log.d(测试,将String.valueOf(reportRecord.getInstallments_from()));
        日期convertedDate =(日期)dateFormat.parse(将String.valueOf(reportRecord.getInstallments_from()));
        Log.d(testx2,testx2);
        SimpleDateFormat的SDF =新的SimpleDateFormat(DD-MM-YYYYKL .-HH:MM);
        字符串strDate = sdf.format(convertedDate);
        jsonObj.put(key18,strDate);
        jsonObj.put(key19,reportRecord.getInsolvency());
        jsonObj.put(key20,reportRecord.getCredibility());
        jsonObj.put(key21,encounterLocal.getEncounterEncounterNotes());
        //创建POST对象,并添加参数
        StringEntity实体=新StringEntity(jsonObj.toString(),HTTP.UTF_8);
        entity.setContentType(应用/ JSON);
        httpPost.setEntity(实体);
        HTT presponse响应= client.execute(httpPost);
        返回convertHtt presponseToString(响应);
    }赶上(例外五){
        Log.e(HTTP,错误的HTTP连接+ e.toString());
        返回null;    }
}私有类ConnectTaskProperty扩展的AsyncTask<地图<整数,报告>中太虚,字符串> {
    //公共AsyncTaskParam asyncTaskParam;
    @覆盖
    保护字符串doInBackground(地图<整数,报告> ... PARAMS){
        地图<整数,报告> localHashmap =参数[0];        字符串结果;
        checkConnectivity(上下文);
        结果= doPostProperty(localHashmap);
        返回结果;
    }    @覆盖
    保护无效onPostExecute(字符串结果){
        如果(结果!= NULL){
            Toast.makeText(ReportMainScreen.this,资讯recuperada:[+结果+],
                    Toast.LENGTH_LONG).show();
        }其他{
            Toast.makeText(ReportMainScreen.this,错误人tratar德conectar CON EL servidor。
                    Toast.LENGTH_LONG).show();
        }
    }
}公共字符串doPostProperty(地图<整数,报告> localHashmap){    Log.d(测试,测试属性);
    整数reportId = NULL;
    报告reportRecord = NULL;    迭代它= localHashmap.entrySet()迭代器()。
    而(it.hasNext()){
        Map.Entry对=(Map.Entry的)it.next();
        reportId =(整数)pairs.getKey();
        reportRecord =(报告)pairs.getValue();
        Log.d(reportRecord,将String.valueOf(reportRecord.getId()));
        it.remove();
    }    字符串URL =...;
    HttpClient的客户端=新DefaultHttpClient();
    HttpPost httpPost =新HttpPost(URL);    Log.d(reportid,将String.valueOf(reportId));
    整数ReportId = reportRecord.getId();
    INT K = db.getPropertyCount();
    的for(int i = 1; I< K + 1;我++){
        物业propertyLocal =新的属性();
        尝试{
            propertyLocal = db.getProperty(ⅰ);
        }赶上(例外五){
            e.printStackTrace();
        }
        INT REPORT_ID;
        REPORT_ID = propertyLocal.getReport_id();
        如果(REPORT_ID == ReportId){
            INT公布;            张贴= propertyLocal.getPosted();
            Log.d(贴,将String.valueOf(转贴));
            如果(贴== 0){
                Log.d(测试,getposted财产);
                尝试{
                    //构建JSON对象来传递参数
                    JSONObject的jsonObj =新的JSONObject();
                    jsonObj.put(KEY1,propertyLocal.getAddress());
                    jsonObj.put(KEY2,propertyLocal.getValue());
                    jsonObj.put(KEY3,propertyLocal.getDebt());
                    jsonObj.put(KEY4,propertyLocal.getNotes());
                    jsonObj.put(KEY5,propertyLocal.getReport_id());
                    StringEntity实体=新StringEntity(jsonObj.toString(),HTTP.UTF_8);
                    entity.setContentType(应用/ JSON);
                    httpPost.setEntity(实体);
                    HTT presponse响应= client.execute(httpPost);
                    返回convertHtt presponseToString(响应);
                }赶上(例外五){
                    Log.e(HTTP,错误的HTTP连接+ e.toString());
                    返回null;
                }
            }
        }
    }
    返回null;
}

和记录错误

 致命异常:AsyncTask的#4
    了java.lang.RuntimeException:执行doInBackground发生错误()
            在android.os.AsyncTask $ 3.done(AsyncTask.java:299)
            在java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
            在java.util.concurrent.FutureTask.setException(FutureTask.java:219)
            在java.util.concurrent.FutureTask.run(FutureTask.java:239)
            在android.os.AsyncTask $ SerialExecutor $ 1.run(AsyncTask.java:230)
            在java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
            在java.util.concurrent.ThreadPoolExecutor中的$ Worker.run(ThreadPoolExecutor.java:573)
            在java.lang.Thread.run(Thread.java:838)
     显示java.lang.NullPointerException:产生的原因
            在.app.view.ReportMainScreen.doPostProperty(ReportMainScreen.java:538)
            在.app.view.ReportMainScreen $ ConnectTaskProperty.doInBackground(ReportMainScreen.java:502)
            在app.view.ReportMainScreen $ ConnectTaskProperty.doInBackground(ReportMainScreen.java:494)
            在android.os.AsyncTask $ 2.call(AsyncTask.java:287)


解决方案

  doPostProperty(地图<整数,报告> localHashmap){     字符串URL =...;
}

如果u传递无效URL值,怎么你会得到的结果?

Error occurs when it calls two functions connecttask and connecttaskproperty. If only conjure connecttask it works. Can anyone help?

private class DelayedTask extends TimerTask {

    @Override
    public void run() {
        String url = "...";
        Log.i("Tag","Timer Task executing");

        // code for updating sqlite database
        try {

            int k = db.getReportsCount();
            Log.d("send0","getReports");
            for(int i = 1; i < k+1; i++ ){
                Log.d("send2","getReports");
                Report report = new Report();
                report = db.getReport(i);
                Log.d("send1","getReport");
                int posted;
                posted = report.getPosted();
                Log.d("send", String.valueOf(posted));
                if(posted == 0){
                    // asynTaskParam = new AsyncTaskParam(report, url);
                    //asynTaskParam
                    Map<Integer, Report> hashmap = new HashMap<Integer, Report>();

                    hashmap.put(i, report);
                    new ConnectTask().execute(hashmap);
                    Log.d("send", String.valueOf(hashmap));
                    //   new ConnectTaskProperty().execute(hashmap);
                    //  Log.d("send", "property");
                 /*   new ConnectTaskRental().execute(hashmap);
                    Log.d("send", "rental");
                    new ConnectTaskCar().execute(hashmap);
                    Log.d("send", "car");
                    new ConnectTaskOtherAsset().execute(hashmap);
                    Log.d("send", "Oa");
                    new ConnectTaskBussinessAsset().execute(hashmap);
                    Log.d("send", "Business Asset");
                    new ConnectTaskDebt().execute(hashmap);
                    Log.d("send", "Debt");*/

                    db.getIdPosted(i);
                    Log.d("Odebrałem", "czy zmieniono");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.d("select", "test");
    }
}



    private class ConnectTask extends AsyncTask</*AsyncTaskParam*/Map<Integer, Report>, Void, String> {

private class ConnectTask extends AsyncTask, Void, String> {

    @Override
    protected String doInBackground(Map<Integer,Report>/*AsyncTaskParam*/... params) {
        Map<Integer,Report> localHashmap = params[0];


        String result;
        checkConnectivity(context);
        result = doPost(localHashmap);
        return result;
    }

    @Override
    protected void onPostExecute(String result) {
        if (result != null) {
            Toast.makeText(ReportMainScreen.this, "Información recuperada: [" + result + "]",
                    Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(ReportMainScreen.this, "Error al tratar de conectar con el servidor.",
                    Toast.LENGTH_LONG).show();
        }
    }
}

public String doPost(Map<Integer,Report> localHashmap) {
    // HttpParams httpParameters = new BasicHttpParams();
    // Se ponen 3 segundos de timeout.
    //  HttpConnectionParams.setConnectionTimeout(httpParameters, 30000);
    //  localHashmap.get(1);
    // for(int i = 0; i < localHashmap.size()+1;i++)
    // {
    Integer reportId = null;
    Report reportRecord = null;

    Iterator it = localHashmap.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pairs = (Map.Entry)it.next();
        reportId = (Integer) pairs.getKey();
        reportRecord = (Report) pairs.getValue();

        // System.out.println(pairs.getKey() + " = " + pairs.getValue());
        it.remove(); // avoids a ConcurrentModificationException
    }
    //}
    Integer EncounterId = reportRecord.getEncounter_id();
    Encounter encounterLocal = db.getEncounter(EncounterId);


    Integer ReportId = reportRecord.getId();
    Personal personalLocal = db.getPersonal(ReportId);
    String url = "...";

    HttpClient client = new DefaultHttpClient(/*httpParameters*/);
    HttpPost httpPost = new HttpPost(url);

    try {

        // Build the JSON object to pass parameters
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("key1", reportRecord.getEncounter_id());
        jsonObj.put("key2", encounterLocal.getEncounterFee());
        jsonObj.put("key3", encounterLocal.getEncounterTax());
        jsonObj.put("key4", encounterLocal.getEncounterSettlement());
        jsonObj.put("key5", encounterLocal.getEncounterMetWith());
        jsonObj.put("key6", encounterLocal.getEncounterProxy());
        jsonObj.put("key7", reportRecord.getTax_excess());
        jsonObj.put("key8", reportRecord.getOutlays());
        jsonObj.put("key9", personalLocal.getReg_number());
        jsonObj.put("key10", personalLocal.getTelephone());
        jsonObj.put("key11", personalLocal.getMartial_status());
        jsonObj.put("key12", personalLocal.getChildren());
        jsonObj.put("key13", personalLocal.getOccupation());
        jsonObj.put("key14", personalLocal.getIncome());
        jsonObj.put("key15", personalLocal.getSpouse_income());
        jsonObj.put("key16", personalLocal.getDisposable_income());
        jsonObj.put("key17", reportRecord.getInstallments());
        DateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
        Log.d("test", String.valueOf(reportRecord.getInstallments_from()));
        Date convertedDate = (Date) dateFormat.parse(String.valueOf(reportRecord.getInstallments_from()));
        Log.d("testx2","testx2");
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy 'kl.-'HH:mm");
        String strDate = sdf.format(convertedDate);
        jsonObj.put("key18", strDate);
        jsonObj.put("key19", reportRecord.getInsolvency());
        jsonObj.put("key20", reportRecord.getCredibility());
        jsonObj.put("key21", encounterLocal.getEncounterEncounterNotes());
        // Create the POST object and add the parameters
        StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        HttpResponse response = client.execute(httpPost);
        return convertHttpResponseToString(response);
    } catch (Exception e) {
        Log.e("HTTP", "Error in http connection " + e.toString());
        return null;

    }
}

private class ConnectTaskProperty extends AsyncTask<Map<Integer, Report>, Void, String> {
    //   public AsyncTaskParam asyncTaskParam;
    @Override
    protected String doInBackground(Map<Integer,Report>... params) {
        Map<Integer,Report> localHashmap = params[0];

        String result;
        checkConnectivity(context);
        result = doPostProperty(localHashmap);
        return result;
    }

    @Override
    protected void onPostExecute(String result) {
        if (result != null) {
            Toast.makeText(ReportMainScreen.this, "Información recuperada: [" + result + "]",
                    Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(ReportMainScreen.this, "Error al tratar de conectar con el servidor.",
                    Toast.LENGTH_LONG).show();
        }
    }
}

public String doPostProperty(Map<Integer,Report> localHashmap) {

    Log.d("test"," test property");
    Integer reportId = null;
    Report reportRecord = null;

    Iterator it = localHashmap.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pairs = (Map.Entry)it.next();
        reportId = (Integer) pairs.getKey();
        reportRecord = (Report) pairs.getValue();
        Log.d("reportRecord", String.valueOf(reportRecord.getId()));
        it.remove();
    }

    String url = "...";
    HttpClient client = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);

    Log.d("reportid", String.valueOf(reportId));
    Integer ReportId = reportRecord.getId();
    int k = db.getPropertyCount();
    for(int i = 1; i < k+1; i++ ) {
        Property propertyLocal = new Property();
        try {
            propertyLocal = db.getProperty(i);
        } catch (Exception e) {
            e.printStackTrace();
        }
        int report_id;
        report_id = propertyLocal.getReport_id();
        if (report_id == ReportId) {
            int posted;

            posted = propertyLocal.getPosted();
            Log.d("posted", String.valueOf(posted));
            if (posted == 0) {
                Log.d("test","getposted property");
                try {
                    // Build the JSON object to pass parameters
                    JSONObject jsonObj = new JSONObject();
                    jsonObj.put("key1", propertyLocal.getAddress());
                    jsonObj.put("key2", propertyLocal.getValue());
                    jsonObj.put("key3", propertyLocal.getDebt());
                    jsonObj.put("key4", propertyLocal.getNotes());
                    jsonObj.put("key5", propertyLocal.getReport_id());
                    StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
                    entity.setContentType("application/json");
                    httpPost.setEntity(entity);
                    HttpResponse response = client.execute(httpPost);
                    return convertHttpResponseToString(response);
                } catch (Exception e) {
                    Log.e("HTTP", "Error in http connection " + e.toString());
                    return null;
                }
            }
        }
    }
    return null;
}

and Log error

FATAL EXCEPTION: AsyncTask #4
    java.lang.RuntimeException: An error occured while executing doInBackground()
            at android.os.AsyncTask$3.done(AsyncTask.java:299)
            at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
            at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
            at java.util.concurrent.FutureTask.run(FutureTask.java:239)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
            at java.lang.Thread.run(Thread.java:838)
     Caused by: java.lang.NullPointerException
            at .app.view.ReportMainScreen.doPostProperty(ReportMainScreen.java:538)
            at .app.view.ReportMainScreen$ConnectTaskProperty.doInBackground(ReportMainScreen.java:502)
            at app.view.ReportMainScreen$ConnectTaskProperty.doInBackground(ReportMainScreen.java:494)
            at android.os.AsyncTask$2.call(AsyncTask.java:287)
解决方案
    doPostProperty(Map<Integer,Report> localHashmap){

     String url = "...";
}

if u pass invalid url value, how you will get result ?

这篇关于AsyncTask的RuntimeException的和在doInBackground的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-05 12:24