我有这个代码,当我点击一个按钮时这个函数运行但是这个函数向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
答案 0 :(得分:0)
您应该关注的错误是
E / log_tag(3651):转换结果时出错java.lang.ArrayIndexOutOfBoundsException:length = 1;索引= 1
您需要确定为什么在您期望更多时,列表中只有一个元素。我建议您打印出堆栈跟踪以便追踪问题。
更好的是,捕获特定的异常而不是每个异常。 catch (Exception e)
被认为是一种不好的做法,因为您可能会在代码中压制严重错误。
答案 1 :(得分:0)
我认为你在这里犯了错字:
httpclient.execute(httppost);
HttpResponse response = httpclient.execute(httppost);
排除第一行,你应该没事。