我正在尝试将一些数据发送到MySQL数据库,并且不起作用,我已经放置了一些log.e来控制问题。我返回“无效的IP地址”,加上我收到错误“NetworkOnMainThreadException”我看了几个解决方案,但找不到合适的东西。谢谢你的帮助。
public class AgregarPalabra extends Activity {
String palabraIngles;
String palabraSpain;
InputStream is=null;
String result=null;
String line=null;
int code;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.agregar);
final EditText ingles=(EditText) findViewById(R.id.inputIngles);
final EditText spain=(EditText) findViewById(R.id.inputSpain);
Button agregar=(Button) findViewById(R.id.btnAgregar);
agregar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
palabraIngles = ingles.getText().toString();
palabraSpain = spain.getText().toString();
insert();
}
});
}
public void insert() {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("ingles",palabraIngles));
nameValuePairs.add(new BasicNameValuePair("spain",palabraSpain));
String url = "http://localhost/agregar.php";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
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());
Log.e("INFO", palabraIngles);
Log.e("INFO", palabraSpain);
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(getBaseContext(), "Inserted Successfully",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getBaseContext(), "Sorry, Try Again",
Toast.LENGTH_LONG).show();
}
} catch(Exception e){
Log.e("Fail 3", e.toString());
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}}