I'm trying to send some data to my website. When the button is clicked, data need to be sent to the web site
but I got some errors when I am running the program
when I clicked the button this message appears "unfortunately app has stopped" then it exit my application.
public class testInput extends Activity {
Button Setbutton;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.test_input_page);
Setbutton=(Button)findViewById(R.id.setbtn);
Setbutton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
testInput ti=new testInput();
//Create the intent
ti.postData("Sent Data");
});
}
public void postData(String toPost) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://mysite.com/index.php");
//This is the data to send
String MyName = toPost; //any data to send
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("action", MyName));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpclient.execute(httppost, responseHandler);
//This is the response from a php application
String reverseString = response;
Toast.makeText(this, "response" + reverseString, Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
Toast.makeText(this, "CPE response " + e.toString(), Toast.LENGTH_LONG).show();
// TODO Auto-generated catch block
} catch (IOException e) {
Toast.makeText(this, "IOE response " + e.toString(), Toast.LENGTH_LONG).show();
// TODO Auto-generated catch block
}
}//end postData()
This is my PHP code.
<?php
//code to reverse the string
$reversed = strrev($_POST["action"]);
echo $reversed;
?>
I got permission also for use internet in my app.
Since Android 3.x you can't perform network operations in main thread. You need to use AsyncTask or separate thread where you can call your postData method.
http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html
}
Here is an code snippet , hoping it will help you.
1)An function which carries the http get service
2) An Class which extends AsyncTask
3) Inside your onCreate method
The code snippet provided by me works in the following way,
1)Android device send the URL+data to server
2)Server [say PHP used] receive the data and gives an acknowledgement
Now the Code which should be written at client side (Android) is provided to you, the later part of receiving that data at server is
Use the following code