Buenas, estoy intentando insertar unos datos en una base externa de MySQL, como no los ingresaba, he realizada un seguimiento por log.e de los pasos, el mensaje recibido es el de "IP no válida", cuando intenta hacer la conexión con HttpClient, además me muestra un error de "NetworkOnMainThreadException", no se si he conseguido explicarme bien, os muestro el código:
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;
}}