I am new to android I know this question asked before many times but I can not find suitable solutions for my case. I want to send password
and username
to server and check it. It returns JSON object and I check on value of object if it is zero or one. The problem is getting message in catch
requested failed:android.os.networkonmainthreadException
that's my code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loginpage);
editTextUserName = (EditText) findViewById(R.id.user);
editTextPassword = (EditText) findViewById(R.id.password);
message=(TextView) findViewById(R.id.mess);
String username = editTextUserName.getText().toString();
String password = editTextPassword.getText().toString();
Button send =(Button)findViewById(R.id.send);
send.setOnClickListener(
new View.OnClickListener(){
@Override
public void onClick(View view) {
// invokeLogin();
clickbuttonRecieve();
}
}
);
}
public void clickbuttonRecieve() {
try {
JSONObject json = new JSONObject();
String username = editTextUserName.getText().toString();
String password = editTextPassword.getText().toString();
json.put("userName",username);
json.put("password", password);
int timeconnection=3000;
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
timeconnection);
HttpConnectionParams.setSoTimeout(httpParams, timeconnection);
HttpClient client = new DefaultHttpClient(httpParams);
//
//String url = "http://10.0.2.2:8080/sample1/webservice2.php?" +
// "json={\"UserName\":1,\"FullName\":2}";
String url = "http://phone.tmsline.com/checkuser";
HttpPost request = new HttpPost(url);
request.setEntity(new ByteArrayEntity(json.toString().getBytes(
"UTF8")));
request.setHeader("json", json.toString());
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
if (entity != null) {
JSONObject jsonget = new JSONObject();
String login = jsonget.getString("msg");
if (login.toString().equalsIgnoreCase("1")){
Toast.makeText(this, "Request success: " + login,
Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(this, "Request failed: " + login,
Toast.LENGTH_LONG).show();
}
}
} catch (Throwable t) {
Toast.makeText(this, "Request failed: " + t.toString(),
Toast.LENGTH_LONG).show();
}
}
php code(note : i didn't write php code , another one is responsible or that)
public function check_user(Request $request){
$username = $request->username;
$password = $request->password;
if (Auth::attempt(['username' => $username, 'password' => $password])) {
// return view('test',['user'=>$username]);
return response()->json(['msg','1']);
}
return response()->json(['msg','0']);
}