doInBackground中的AsyncTask和RuntimeException

时间:2014-09-14 17:29:44

标签: android

调用两个函数connecttask和connecttaskproperty时发生错误。如果只是召唤connecttask它的工作原理。有人可以帮忙吗?

私有类DelayedTask扩展了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> {

私有类ConnectTask扩展了AsyncTask,Void,String&gt; {

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

并记录错误

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)

1 个答案:

答案 0 :(得分:0)

    doPostProperty(Map<Integer,Report> localHashmap){

     String url = "...";
}

如果您传递了无效的网址值,您将如何获得结果?