在IntentService类中使用AsyncTask时,为什么我从doInBackground获取空值?

时间:2022-04-16 22:50:58

I am trying to insert some points into a table in a database. For this i am using an IntentService, but i am getting an empty value from onPostExecute(i checked using debug). I am in doubt whether this is a good way to achieve this?- The problem is i can not find out why the value returned is empty?-Any help is very appreciated. Thanks, Carl. Here is my class who extends IntetService:

我试图在数据库的表中插入一些点。为此我使用的是IntentService,但是我从onPostExecute获取一个空值(我使用debug检查)。我怀疑这是否是实现这一目标的好方法? - 问题是我无法找出为什么返回的值是空的? - 非常感谢任何帮助。谢谢,卡尔。这是我的扩展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));
    }
}

My AsyncTask class:

我的AsyncTask类:

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

and my Servlet class:

和我的Servlet课程:

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

1 个解决方案

#1


below code must run on main thread not on worker thread(onHandleIntent)

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

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

simply remove that and copy and past all of doInBackgroundand onPostExecute code instead of it or if you want to create another thread inside worker thread use thread class.

只需删除它并复制并过去所有的doInBackground和onPostExecute代码而不是它或者如果你想在工作线程中创建另一个线程使用线程类。

#1


below code must run on main thread not on worker thread(onHandleIntent)

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

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

simply remove that and copy and past all of doInBackgroundand onPostExecute code instead of it or if you want to create another thread inside worker thread use thread class.

只需删除它并复制并过去所有的doInBackground和onPostExecute代码而不是它或者如果你想在工作线程中创建另一个线程使用线程类。