为什么我在 IntentService class 中使用 AsyncTask 时从我的 doInBackground 得到一个空值?

Why am i getting an empty value from my doInBackground when using AsyncTask in an IntentService class?

我正在尝试将一些点插入到数据库中的 table 中。为此,我使用了 IntentService,但我从 onPostExecute 得到了一个空值(我使用调试进行了检查)。我怀疑这是否是实现此目标的好方法?-问题是我无法找出为什么返回的值为空?-非常感谢您的帮助。谢谢,卡尔。 这是我的 class 扩展 IntetService:

public class ExampleClass extends IntentService {

    final String file = "text.txt";
    final File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
    HttpClient httpClient = new DefaultHttpClient();

    public ExampleClass() {super("ExampleClass");}

    protected String ReadFile() {
        File file = new File(path, file);
        String line = "";
        StringBuilder text = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            while ((line = br.readLine()) != null) {
                text.append(line + '\n');
            }
            br.close();
        } catch (IOException e) {
            e.getMessage()
        }
        return text.toString();
    }
    @Override
    protected void onHandleIntent(Intent intent) {
            String[] points = ReadFile().replace("\n", ",").split(",");
            List<String> latitude = new ArrayList<>(); 
            List<String> longitude = new ArrayList<>(); 
            for (int i = 0; i < points.length; i++) {
                if (i % 2 == 0) {
                    latitude.add(points[i]);
                } else {
                    longitude.add(points[i]); 
                }
            }
            List<Koordinate> koord = new ArrayList<>();
            for (int i = 0; i < latitude.size() && i < longitude.size(); i++) {
                Koordinate koordinate = new Koordinate(latitude.get(i), longitude.get(i));
                koord.add(koordinate);
            }
            Gson gson = new Gson();
            String json = gson.toJson(koordArray);  
            List<NameValuePair> nameValuePairs = new ArrayList<>(1);
            nameValuePairs.add(new BasicNameValuePair("toJson", json));
            new AsyncTask(this).execute(new Pair<>(nameValuePairs, httpClient));
    }
}

我的AsyncTaskclass:

public class AsyncTask extends AsyncTask<Pair<List<NameValuePair>, HttpClient>, Void, String> {

    private Context context = null;

    public AsyncTaskTilPos(Context context) {this.context = context;}

    @Override
    protected String doInBackground(Pair<List<NameValuePair>, HttpClient>... params) {

        Pair pair = params[0];
        List<NameValuePair> urlParams = (List<NameValuePair>) pair.first;
        HttpClient httpClient = (HttpClient) pair.second;
        try {
            String serverURL = MainActivity.address + MainActivity.stringCommands
                    [MainActivity.TO_TABLE];
            HttpPost httpPost = new HttpPost(serverURL);
            httpPost.setEntity(new UrlEncodedFormEntity(urlParams));
            HttpResponse response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                return EntityUtils.toString(response.getEntity());
            }
            return "Wrong: " + response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase();
        } catch (ClientProtocolException e) {
            return e.getMessage();
        } catch (IOException e) {
            return e.getMessage();
        }
    }
    @Override
    protected void onPostExecute(String result) {
        Intent i = new Intent("fileToTable").putExtra("theResultOfSendingFileToTable", result);
        LocalBroadcastManager.getInstance(context).sendBroadcast(i);
    }
}

和我的 Servlet class:

public class Servlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public final static String NOT_LOGGED_IN = "You're not logged in";

    public SendingTilPosServlet() {super();}

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        handleRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse
            response) throws ServletException, IOException {
        handleRequest(request, response);
    }

    private void handleRequest(HttpServletRequest req, HttpServletResponse
            resp) throws ServletException, IOException {

        String message = "";
        PrintWriter out = resp.getWriter();
        resp.setContentType("text/plain");
        resp.setContentLength(message.length());
        HttpSession session = req.getSession();
        String loggedIn = (String)session.getAttribute("logIn");
        try {
            if (loggedIn != null || loggedIn.equalsIgnoreCase("User is logged in")) {
                Gson gson = new Gson();
                String koordinates = req.getParameter("toJson");
                List<Koordinate> arrayKoord = gson.fromJson(koordinates, new TypeToken<ArrayList<Koordinate>>(){}.getType());
                DataBase dbh = new DataBase();
                boolean result = dbh.insertValuesToTable(arrayKoord);
                if(result) {
                    message = "Storage is successful";
                } else {
                    message = "Storage is unsuccessful";
                }
                out.println(message);
            } else {
                message = "You're not logged in";
                out.println(message);
            }
        } catch (NullPointerException e) {
            e.getMessage();
        }
    }
}

下面的代码必须 运行 在主线程上而不是在工作线程上 (onHandleIntent)

new AsyncTask(this).execute(new Pair<>(nameValuePairs, httpClient));

只需删除它并复制并粘贴所有 doInBackgroundonPostExecute 代码而不是它,或者如果您想在工作线程中创建另一个线程,请使用线程 class.