In this example we will learn how to make Get request to server in android.
Always call server with the use of thread and handlers, if not using request with thread then server request will lock activity to complete request , if user will interact with activity before server request complete then activity will give ANR ( FORCE CLOSE ERROR ) problem.
public class HttpGetAndroidExample extends Activity {
TextView content;
EditText fname,email,login,pass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_http_get_android_example);
content = (TextView)findViewById(R.id.content);
fname = (EditText)findViewById(R.id.name);
email = (EditText)findViewById(R.id.email);
login = (EditText)findViewById(R.id.loginname);
pass = (EditText)findViewById(R.id.password);
Button saveme=(Button)findViewById(R.id.save);
saveme.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v)
{
//ALERT MESSAGE
Toast.makeText(getBaseContext(),"Please wait, connecting to server.",Toast.LENGTH_LONG).show();
try{
// URLEncode user defined data
String loginValue = URLEncoder.encode(login.getText().toString(), "UTF-8");
String fnameValue = URLEncoder.encode(fname.getText().toString(), "UTF-8");
String emailValue = URLEncoder.encode(email.getText().toString(), "UTF-8");
String passValue = URLEncoder.encode(pass.getText().toString(), "UTF-8");
// Create http cliient object to send request to server
HttpClient Client = new DefaultHttpClient();
// Create URL string
String URL = "/media/webservice/httpget.php?user="+loginValue+"&name="+fnameValue+"&email="+emailValue+"&pass="+passValue;
//Log.i("httpget", URL);
try
{
String SetServerString = "";
// Create Request to server and get response
HttpGet httpget = new HttpGet(URL);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
SetServerString = Client.execute(httpget, responseHandler);
// Show response on activity
content.setText(SetServerString);
}
catch(Exception ex)
{
content.setText("Fail!");
}
}
catch(UnsupportedEncodingException ex)
{
content.setText("Fail");
}
}
});
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidexample.httpgetexample"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.androidexample.httpgetexample.HttpGetAndroidExample"
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>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>
This file will get request and send response.