我试图将一些点插入数据库中的表中。为此,我使用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));
}
}
我的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);
}
}
和我的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();
}
}
}
答案 0 :(得分:2)
下面的代码必须在主线程上运行而不是在工作线程(onHandleIntent)
上运行new AsyncTask(this).execute(new Pair<>(nameValuePairs, httpClient));
只需删除它并复制并过去所有doInBackground
和onPostExecute
代码而不是它或者如果你想在工作线程使用线程类中创建另一个线程。