Hi
I am developing a login form in android using php and mysql each time i try to test in the emulator it shows the following error
in the stack trace
02-02 17:20:05.137 1145-1145/green.gemstouch.com.samplelogin E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: green.gemstouch.com.samplelogin, PID: 1145
android.os.NetworkOnMainThreadException
see the code belowpublic class MyActivity extends ActionBarActivity {
EditText username, password;
Button login;
TextView status;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List nameValuePairs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
setup();
}
private void setup() {
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
login = (Button) findViewById(R.id.login);
status = (TextView) findViewById(R.id.status);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
switch (arg0.getId()){
case R.id.login:
login();
break;
}
}
});
}
private void login() {
try{
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://10.0.2.2/akadalogin/sample.php");
nameValuePairs = new ArrayList(1);
nameValuePairs.add(new BasicNameValuePair("username", username.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("password", password.getText().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
ResponseHandler responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
status.setText(""+response);
if (response.equalsIgnoreCase("User found")){
startActivity(new Intent(MyActivity.this, UserPage.class));
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Kindly help
解决方案Few issue you need to know.
1. You cannot do any network related work from the main thread
to do so you will have to call network related work in separate thread.
The simplest way would be: using AsyncTask class.
And also you are trying to log in with user account. In this case also take a look at HttpContex, provided by Apache. HttpContext will recall your cookies