Reputation: 11
I am new to android development. As part of a bigger project I want to insert data from an android device to a web-server. So I did some research and articles like The article from androidhive and this article from codeproject were really helpful in trying to develop a test-app which inserts in to a mysql db, which is residing at a remote web-server.
Here is my android code
ConnectivityManager connMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xxxxxxxx.in/installment.php");
try{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name", editTextCustomer.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("amount", editTextAmount.getText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
Log.i("postData", response.getStatusLine().toString());
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
}
else {
Toast.makeText(PayBillActivity.this, "Internet Access, Denied!!", Toast.LENGTH_LONG).show();
}
Here is the php code
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['name']) && isset($_POST['amount'])) {
$name = $_POST['name'];
$amount = $_POST['amount'];
$con=mysqli_connect("localhost","db_user","passwd","db_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO installment (name, amount) VALUES ('$_POST[name]','$_POST[amount]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
// check if row inserted or not
if ($sql) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Installment made successfully";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
echo $result;
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
//$amount = 1000;
//echo $amount;
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
when I run the app, I am getting this "NetworkOnMainThreadException" exception and as a result no rows are being added. But its working perfect with HTML POST.
Can anyone tell me where the problem is in my code? Thanks in advance!:)
Upvotes: 1
Views: 1905
Reputation: 539
I think you should not use that strict or take it manually out of main..
Just use a smart premade lib and it is making all for you !
Download : http://loopj.com/android-async-http/
Note: And this lib is even using gzip to compress requests :)
Upvotes: 0
Reputation: 1803
I think if you spent the time you did on posting this question into google you may have got some good answers... Just to complete this question
There are two options available with you, either you can add a line of code and allow network operation on main thread, but its very very bad for your app and also as a coding style.
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
The longer option is to redesign the code to have the network operations performed in a separate thread. This is both good for the app and you will learn how to work on a multi-threaded program.
Upvotes: 2