Search code examples
androidbuttonhttp-postbasicnamevaluepair

How to send a value or string from android application to a server when a button is clicked


I want to store an integer to a button. Upon clicking the button, the application sends the integer value to the server.

For the storing of integers I thought of using

nameValuePairs.add(new BasicNameValuePair("gender",Integer.toString(1)));    

and making use of HttpPost to send to localhost. However, I have no idea how to invoke this function on to a button. Main.java

Main.xml

public class Main extends Activity implements OnClickListener{

private Button cnfrm;
private Button absnt;
private Button ntfy;
private ProgressBar pb_cnfrm;
private ProgressBar pb_absnt;
private ProgressBar pb_ntfy;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
cnfrm =(Button)findViewById(R.id.button1);
absnt =(Button)findViewById(R.id.button2);
ntfy =(Button)findViewById(R.id.button3);
pb_cnfrm=(ProgressBar)findViewById(R.id.progressBar1);
pb_absnt=(ProgressBar)findViewById(R.id.progressBar2);
pb_ntfy=(ProgressBar)findViewById(R.id.progressBar3);
pb_cnfrm.setVisibility(View.GONE);
cnfrm.setOnClickListener(this);
pb_absnt.setVisibility(View.GONE);
absnt.setOnClickListener(this);
pb_ntfy.setVisibility(View.GONE);
ntfy.setOnClickListener(this);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
return true;
}

public void onClick(View v) {
    // TODO Auto-generated method stub
    pb_cnfrm.setVisibility(View.VISIBLE);
    pb_absnt.setVisibility(View.VISIBLE);
    pb_ntfy.setVisibility(View.VISIBLE);
    new MyAsyncTask().execute(toString());  


}

private class MyAsyncTask extends AsyncTask<String, Integer, Double>{

@Override
protected Double doInBackground(String... params) {
    // TODO Auto-generated method stub
    postData(params[0]);
return null;
}

protected void onPostExecute(Double result){
    pb_cnfrm.setVisibility(View.GONE);
    Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
    pb_absnt.setVisibility(View.GONE);
    Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
    pb_ntfy.setVisibility(View.GONE);
    Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
    }
    protected void onProgressUpdate(Integer... progress){
    pb_cnfrm.setProgress(progress[0]);
    pb_absnt.setProgress(progress[1]);
    pb_ntfy.setProgress(progress[2]);
}

public void postData(String valueIWantToSend) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.56.1/http.php");

    try {
    // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("confirm",Integer.toString(1)));
        nameValuePairs.add(new BasicNameValuePair("absent",Integer.toString(2)));
        nameValuePairs.add(new BasicNameValuePair("notify",Integer.toString(3)));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);

    } catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
    } catch (IOException e) {
    // TODO Auto-generated catch block
    }
}

}

}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android_post_request"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="14"
    android:targetSdkVersion="20" />
 <uses-permission android:name="android.permission.INTERNET" />

 <application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".Main"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>

Solution

  • If you have a button you can use OnClickLister and OnClick. You can try something like this

    private callServer(){..}

    Button myButton = new Button(getApplicationContext());
    myButton.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        callServer();
      }
    });
    

    Also keep in mind that you should NOT be doing a call to the server in the UI thread, you will need to make the call using a different thread.