我正在创建一个 android 应用程序,它将使用下面的代码将一些数据上传到数据库。我已经能够将其他信息添加到数据库中(当 api 调用不同的东西时),但是在这里我得到了以下错误(代码如下)。先感谢您!
05-27 20:35:51.144: E/content(8749): array(1) { [0]=> array(2) { ["value"]=> string(5) "18-24" ["question_id"]=> string(2) "14" }}{"success":0,"error":"Query: INSERT INTO client_question_answers (client_form_id, question_id, value) VALUES ('4', '14', '18-24')\nDatabase error message: Cannot add or update a child row: a foreign key constraint fails (`mypsych`.`client_question_answers`, CONSTRAINT `client_question_answers_ibfk_2` FOREIGN KEY (`client_form_id`) REFERENCES `client_forms` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)\nDatabase error number: 1452"}
在这里拨打电话:
NetworkUtility.sendForm("4", "14","18-24", key);
这是 sendForm 方法:
public static void sendForm(String client_form_id, String question_id, String value, String key) throws ClientProtocolException, JSONException, IOException
{
List<BasicNameValuePair> parameters=new ArrayList<BasicNameValuePair>();
JSONObject answers = new JSONObject();
answers.put("question_id", question_id);
answers.put("value", value);
JSONArray answers1 = new JSONArray();
answers1.put(answers);
String answers2 = answers1.toString();
parameters.add(new BasicNameValuePair("answers", answers2));
parameters.add(new BasicNameValuePair("key", key));
StringBuilder url=new StringBuilder();
url.append("https://myurl.com/api/forms/answers/create/");
url.append(client_form_id);
JSONObject root = new JSONObject(getJSONContent(parameters, url.toString()));
Log.e("goal", root.toString());
}
最后是处理实际 HTTP 命令的方法
private static String getJSONContent(List<BasicNameValuePair> parameters, String url) throws ClientProtocolException, IOException, JSONException {
HttpClient client=new DefaultHttpClient();
HttpPost request=new HttpPost(url);
if (cookieStore == null) {
cookieStore = new BasicCookieStore();
httpContext = new BasicHttpContext();
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
}
UrlEncodedFormEntity formEntity=new UrlEncodedFormEntity(parameters);
request.setEntity(formEntity);
HttpResponse response=client.execute(request, httpContext);
InputStream is=response.getEntity().getContent();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String line=null;
StringBuilder content=new StringBuilder();
while ((line=br.readLine())!=null) {
content.append(line);
}
Log.e("content", content.toString());
return content.toString();
}
}