我有这段代码,当我单击一个按钮时,该函数运行,但是此函数向php发送两个请求,而php在数据库中保存了两个记录...?
public void send()
{
//get message from message box
final String msg = msgTextField.getText().toString();
InputStream is = null;
StringBuilder sb = null;
String result = null;
//check whether the msg empty or not
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
if(msg.length() > 0) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("URL");
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("Type", "MSG"));
nameValuePairs.add(new BasicNameValuePair("Message", msg));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection" + e.toString());
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
sb = new StringBuilder();
sb.append(reader.readLine());
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
result = sb.toString();
LinearLayout Lay = (LinearLayout)findViewById(R.id.MSGes);
TextView MyView = new TextView(this);
MyView.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
MyView.setText(msg);
MyView.setId(Integer.valueOf(result.toString()));
Lay.addView(MyView);
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
} else {
Toast.makeText(getBaseContext(),"Empty",Toast.LENGTH_SHORT).show();
}
和logcat:
09-15 17:50:32.328:W / SingleClientConnManager(3651):无效使用SingleClientConnManager:连接仍被分配。
09-15 17:50:32.328:W / SingleClientConnManager(3651):确保在分配另一个之前释放连接。
09-15 17:50:32.758:E / log_tag(3651):转换结果java.lang.ArrayIndexOutOfBoundsException时出错:length = 1;索引= 1
09-15 17:50:35.188:W / SingleClientConnManager(3651):无效使用SingleClientConnManager:连接仍被分配。
09-15 17:50:35.188:W / SingleClientConnManager(3651):确保在分配另一个之前释放连接。
09-15 17:50:38.168:W / SingleClientConnManager(3651):无效使用SingleClientConnManager:仍分配了连接。
09-15 17:50:38.168:W / SingleClientConnManager(3651):确保在分配另一个之前释放连接。
09-15 17:50:38.538:E / log_tag(3651):转换结果java.lang.ArrayIndexOutOfBoundsException时出错:length = 1;索引= 1
最佳答案
我认为您在这里输入错误:
httpclient.execute(httppost);
HttpResponse response = httpclient.execute(httppost);
排除第一行,您就可以了。