從android插入6列到PHP MySql顯示這3個錯誤 使用Fragment實現App /代碼,並且此代碼在其中一個片段文件上完成。 添加Internet權限也在清單錯誤:從Android中插入數據到MySql時
登錄貓
06-23 00:52:53.830: E/Fail 1(1512):android.os.NetworkOnMainThreadException
06-23 00:52:53.830: E/Fail 2(1512):java.lang.NullPointerException:lock==null
06-23 00:52:53.830: E/Fail 3(1512):java.lang.NullPointerException
的Android代碼
在同一個文件public void insert() {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("addque", addque));
nameValuePairs.add(new BasicNameValuePair("addc1", addc1));
nameValuePairs.add(new BasicNameValuePair("addc2", addc2));
nameValuePairs.add(new BasicNameValuePair("addc3", addc3));
nameValuePairs.add(new BasicNameValuePair("addanswer", addanswer));
nameValuePairs.add(new BasicNameValuePair("addexplan", addexplan));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost("http://localhost/insert/insert.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
} catch (Exception e) {
Log.e("Fail 1", e.toString());
//Toast.makeText(getApplicationContext(), "Invalid IP
Address ",Toast.LENGTH_LONG).show();
}
try {
BufferedReader reader = new BufferedReader
(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
} catch (Exception e) {
Log.e("Fail 2", e.toString());
}
try {
JSONObject json_data = new JSONObject(result);
code = (json_data.getInt("code"));
if (code == 1) {
Toast.makeText(getActivity(), "Inserted Successfully",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "Sorry, Try Again",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Log.e("Fail 3", e.toString());
}
}
新
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
addque = question.getText().toString();
addc1 = choice1.getText().toString();
addc2 = choice2.getText().toString();
addc3 = choice3.getText().toString();
addanswer = answer.getText().toString();
addexplan = Explanation.getText().toString();
insert();
//Toast.makeText(getActivity(), "Question posted", Toast.LENGTH_SHORT).show();
}
});
插入函數從在MySQL中的數據插入Android Thankyou
移動你在後臺線程插入(),與其說這是在主線程 –