When I insert a sentence from my android phone, the data is not inserted to my database. But when I use my friend's mobile, it works successfully.
It actually does not work when I use space between two words. But, when I use a single word, it works.
I use VARCHAR in my database.
Here is my java code:
EditText cname, location, num, email, pass;
Button submit;
private static final String REGISTER_URL = "https://alex456.000webhostapp.com/Register.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
cname = (EditText)findViewById(R.id.editText8);
location = (EditText)findViewById(R.id.editText9);
num = (EditText)findViewById(R.id.editText10);
email = (EditText)findViewById(R.id.editText11);
pass = (EditText)findViewById(R.id.editText3);
submit = (Button) findViewById(R.id.button6);
submit.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
#Override
public void onClick(View v) {
registerUser();
}
});
}
private void registerUser(){
String CNAME, LOCATION, NUM, PASS ,EMAIL;
CNAME = cname.getText().toString().trim();
LOCATION = location.getText().toString().trim();
NUM = num.getText().toString().trim();
EMAIL = email.getText().toString().trim();
PASS = pass.getText().toString().trim();
register(CNAME, LOCATION, NUM, EMAIL, PASS);
}
private void register(String CNAME,String LOCATION,String NUM,String EMAIL, String PASS ) {
String urlSuffix = "?cnamePHP=" + CNAME + "&locationPHP=" + LOCATION + "&numPHP=" + NUM + "&emailPHP=" + EMAIL + "&passPHP=" + PASS;
class RegisterUser extends AsyncTask<String, Void, String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(RegisterActivity.this, "Please Wait", null, true, true);
}
#Override
protected String doInBackground(String... params) {
String s = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(REGISTER_URL + s);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String result;
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Intent i;
i = new Intent(RegisterActivity.this, RegisterActivity.class);
RegisterActivity.this.startActivity(i);
}
}
RegisterUser ur = new RegisterUser();
ur.execute(urlSuffix);
}
}
Related
MainActivity.java
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
user_name = (EditText) findViewById(R.id.user_name);
password = (EditText)findViewById(R.id.password);
submit_btn = (Button) findViewById(R.id.submit);
submit_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Sender s = new Sender(v.getContext(),urlAddress,user_name,password);
s.execute();
cxt = getApplicationContext();
}
});
}
public void GoUserActivity(){
Intent i = new Intent(MainActivity.this,com.example.prakash.cinihive.UserActivity.class);
startActivity(i);
}
}
Sender.java
package com.example.prakash.cinihive;
public class Sender extends AsyncTask<Void,Void,String> {
Context c;
String urlAddress;
EditText user_name,password;
String UserName,Password;
ProgressDialog pd;
MainActivity main = new MainActivity();
public Sender(Context c, String urlAddress, EditText user_name, EditText password) {
this.c = c;
this.urlAddress = urlAddress;
this.user_name = user_name;
this.password = password;
UserName = user_name.getText().toString();
Password = password.getText().toString();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(c);
pd.setTitle("send");
pd.setMessage("Sending..Please wait");
pd.show();
}
#Override
protected String doInBackground(Void... voids) {
return this.send();
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
pd.dismiss();
if(response !=null){
//Toast.makeText(c,response,Toast.LENGTH_LONG).show();
//Log.d("Response",response);
if(response.equals("false")){
Toast.makeText(c,"Invalid Credentials",Toast.LENGTH_LONG).show();
}
else{
main.GoUserActivity();
//Toast.makeText(c,response,Toast.LENGTH_LONG).show();
}
user_name.setText("");
password.setText("");
}
else{
Toast.makeText(c,"Un succesfullll",Toast.LENGTH_LONG).show();
}
}
public String send(){
HttpURLConnection con = Connector.connect(urlAddress);
//Toast.makeText(c,con.toString(),Toast.LENGTH_LONG).show();
if(con==null){
Toast.makeText(c,"Connection Null",Toast.LENGTH_LONG).show();
return null;
}
try{
// Log.d("Connection status","Connection not null");
OutputStream os = con.getOutputStream();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
bw.write(new DataPack(UserName,Password).Packdata());
bw.flush();
bw.close();
os.close();
int responseCode = con.getResponseCode();
Log.d("MYINT","Response Id :"+responseCode);
if(responseCode==con.HTTP_OK){
Log.d("Response code","Response code success");
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuffer response = new StringBuffer();
String line;
while((line=br.readLine())!=null){
response.append(line);
}
br.close();
return response.toString();
}else{
Log.d("Response code","Failure");
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
This is my code My problem was Intent Statement Not working in GoUserActivity funtion
At the same time Intent Statement Working well in OnCreate function.
When I try to run inside GoUserActivity,it will raise the runtime error(NullPoniterException "Intent i = new Intent(MainActivity.this,com.example.prakash.cinihive.UserActivity.class);")
I think you'll find things work better if you move your AsyncTask inside MainActivity as an inner class. You'll be able to call GoUserActivity() without having to new another instance of MainActivity, which you should never do.
I want to make an android app where google spreadsheet will be my server.I am able to post data to the server(google spreadsheet) via google form but unable to get data from that spreadsheet.
My code is
public class ContactActivity extends ActionBarActivity {
public static final MediaType FORM_DATA_TYPE
= MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");
public static final String URL="https://docs.google.com/forms/d/e/" +
"XXXXXXXXX/formResponse";
public static final String NAME="entry.XXXXXXXX";
public static final String PHONE="entry.XXXXXXXX7";
public static final String EMAIL="entry.XXXXXXXX";
private Context context;
private EditText name;
private EditText ph;
private EditText email;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact);
context =this;
Button sendButton = (Button)findViewById(R.id.submit);
name = (EditText)findViewById(R.id.name);
ph = (EditText)findViewById(R.id.phone);
email = (EditText)findViewById(R.id.email);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(TextUtils.isEmpty(name.getText().toString()) ||
TextUtils.isEmpty(ph.getText().toString()) ||
TextUtils.isEmpty(email.getText().toString()))
{
Toast.makeText(context,"All fields are mandatory.",Toast.LENGTH_LONG).show();
return;
}
if(!android.util.Patterns.EMAIL_ADDRESS.matcher(email.getText().toString()).matches())
{
Toast.makeText(context,"Please enter a valid email.",Toast.LENGTH_LONG).show();
return;
}
PostDataTask postDataTask = new PostDataTask();
postDataTask.execute(URL,name.getText().toString(),ph.getText().toString(),email.getText().toString());
}
});
}
private class PostDataTask extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... contactData) {
Boolean result = true;
String url = contactData[0];
String n = contactData[1];
String p = contactData[2];
String e = contactData[3];
String postBody="";
try {
postBody = NAME+"=" + URLEncoder.encode(n,"UTF-8") +
"&" + PHONE + "=" + URLEncoder.encode(p,"UTF-8") +
"&" + EMAIL + "=" + URLEncoder.encode(e,"UTF-8");
} catch (UnsupportedEncodingException ex) {
result=false;
}
try{
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(FORM_DATA_TYPE, postBody);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
}catch (IOException exception){
result=false;
}
return result;
}
#Override
protected void onPostExecute(Boolean result){
Toast.makeText(context,result?"Message successfully sent!":"There was some error in sending message. Please try again after some time.",Toast.LENGTH_LONG).show();
}
}
}
"User Already Exists !" how to get inner body value like "User Already Exists !" I am using DOM Parser
please post any example
private EditText email, name, mobile, password;
TextView tv;
private Button submit;
// private String Email, Name, Mobile, Password;
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
email = (EditText) findViewById(R.id.email);
name = (EditText) findViewById(R.id.name);
mobile = (EditText) findViewById(R.id.mobile);
password = (EditText) findViewById(R.id.password);
submit = (Button) findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s1 = email.getText().toString().trim();
String s2 = name.getText().toString().trim();
String s3 = mobile.getText().toString().trim();
String s4 = password.getText().toString().trim();
if (s1.length() > 0 && s2.length() > 0) {
new ExecuteTask().execute(s1, s2, s3, s4);
email.setText(s1);
name.setText(s2);
mobile.setText(s3);
password.setText(s4);
} else {
}
}
});
}
public String PostData(String[] valuse) {
String responseText = "";
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet(
"https://www.businessbook4u.com/bbm4u.asmx/XUsrSignup?Email="+valuse[0]+"&Name="+valuse[1]+"&Mobile="+valuse[2]+"&Password="+valuse[3]);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
responseText = EntityUtils.toString(entity);
} catch (Exception e) {
System.out.println(e);
}
return responseText;
}
class ExecuteTask extends AsyncTask<String, String, String> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String res = PostData(params);
return res;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
TextView t=(TextView)findViewById(R.id.message);
t.setText(s);
}
}
}
}
#Override
public void onClick(View view) {
registerUser();
}
private void registerUser() {
if (editTextName.getText().toString().equals("")) {
editTextName.setError("Pleas fill this field");
editTextName.requestFocus();
}
else if(editTextEmail.getText().toString().equals(""))
{
editTextEmail.setError("Enter your email");
editTextEmail.requestFocus();
}
else if (!validateEmail(editTextEmail.getText().toString())) {
editTextEmail.setError("Invalid EmailId");
editTextEmail.requestFocus();
}
else if(editTextPassword.getText().toString().equals(""))
{
editTextPassword.setError("Enter a Password");
}
else if(editTextPhone.getText().toString().equals(""))
{
editTextPhone.setError("Enter your mobile number");
editTextPhone.requestFocus();
}
else if (!validatePhone(editTextPhone.getText().toString())) {
editTextPhone.setError("Invalid Mobile Number");
editTextPhone.requestFocus();
}
else {
String name = editTextName.getText().toString().trim().toLowerCase();
String email = editTextEmail.getText().toString().trim().toLowerCase();
String password = editTextPassword.getText().toString().trim().toLowerCase();
String phone = editTextPhone.getText().toString().trim().toLowerCase();
register(name, email, password, phone);
}
}
private void register(String name, String email, String password, String phone ) {
String urlSuffix = "?name="+name+"&email="+email+"&password="+password+"&phone="+phone;
class RegisterUser extends AsyncTask<String, Void, String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(SignUpActivity.this, "Please Wait",null, true, true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(String... params) {
String s = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(REGISTER_URL+s);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String result;
result = bufferedReader.readLine();
return result;
}catch(Exception e){
return null;
}
}
}
RegisterUser ru = new RegisterUser();
ru.execute(urlSuffix);
}
Here are my 2 doubts:
I need to navigate to login page after the user has successfully registered, else should remain in the same page.
Need to dismiss edit text field when the user is successfully registered. when the user already exist the edit text field should not be dismissed.
try this.
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
You need to add Intent with Flag into onPostExecute() method of AsyncTask as below :
#Override
public void onClick(View view) {
registerUser();
}
private void registerUser() {
if (editTextName.getText().toString().equals("")) {
editTextName.setError("Pleas fill this field");
editTextName.requestFocus();
} else if (editTextEmail.getText().toString().equals("")) {
editTextEmail.setError("Enter your email");
editTextEmail.requestFocus();
} else if (!validateEmail(editTextEmail.getText().toString())) {
editTextEmail.setError("Invalid EmailId");
editTextEmail.requestFocus();
} else if (editTextPassword.getText().toString().equals("")) {
editTextPassword.setError("Enter a Password");
} else if (editTextPhone.getText().toString().equals("")) {
editTextPhone.setError("Enter your mobile number");
editTextPhone.requestFocus();
} else if (!validatePhone(editTextPhone.getText().toString())) {
editTextPhone.setError("Invalid Mobile Number");
editTextPhone.requestFocus();
} else {
String name = editTextName.getText().toString().trim().toLowerCase();
String email = editTextEmail.getText().toString().trim().toLowerCase();
String password = editTextPassword.getText().toString().trim().toLowerCase();
String phone = editTextPhone.getText().toString().trim().toLowerCase();
register(name, email, password, phone);
}
}
private void register(String name, String email, String password, String phone) {
String urlSuffix = "?name=" + name + "&email=" + email + "&password=" + password + "&phone=" + phone;
class RegisterUser extends AsyncTask<String, Void, String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(SignUpActivity.this, "Please Wait", null, true, true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
Intent intLogin = new Intent(getApplicationContext(), LoginActivity.class);
intLogin.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intLogin);
}
#Override
protected String doInBackground(String... params) {
String s = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(REGISTER_URL + s);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String result;
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
return null;
}
}
}
RegisterUser ru = new RegisterUser();
ru.execute(urlSuffix);
}
I'm new in android and i need to make AsyncTask, so my application can work on ICS. But after I read tutorials i still got confuse. Anyone, please help me to fix my code, i don't know what and where i must put in AsyncTask with my code like this. thank you
Login.java
package com.karismaelearning;
public class Login extends Activity {
public Koneksi linkurl;
String SERVER_URL;
private Button login, register, setting;
private EditText username, password;
public ProgressDialog progressDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
setting = (Button)findViewById(R.id.bsetting);
login = (Button) findViewById(R.id.login);
register = (Button) findViewById(R.id.reg);
username = (EditText) findViewById(R.id.uname);
password = (EditText) findViewById(R.id.pass);
setting.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intentSet = new Intent(Login.this, UrlSetting.class);
startActivity(intentSet);
}
});
register.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intentReg = new Intent(Login.this, Register.class);
startActivity(intentReg);
}
});
login.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String response = null;
String mUsername = username.getText().toString();
String mPassword = password.getText().toString();
response = tryLogin(mUsername, mPassword).trim();
Log.d("Check","Here");
Log.d("Response",response);
if(response.toLowerCase().contains("berhasil"))
{
String nama = username.getText().toString();
Intent newIntent = new Intent(Login.this, MainPage.class);
Bundle bundle = new Bundle();
bundle.putString("nama", nama);
newIntent.putExtras(bundle);
startActivityForResult(newIntent, 0);
}
else
{
//Optional
//Kalau bisa dibuat constant untuk menghindari salah penulisan
String RoleError = "ROLE SALAH";
String UserError = "USER SALAH";
createDialog("Maaf", response.equals(RoleError) ? "Role Anda bukan Student!" : "Username Atau Password Salah!");
}
}
});
}
protected String tryLogin(String mUsername, String mPassword)
{
Log.d(" TryLoginCheck ","Here");
HttpURLConnection connection;
OutputStreamWriter request = null;
URL url = null;
String response = null;
String temp=null;
String parameters = "username="+mUsername+"&password="+mPassword;
System.out.println("UserName"+mUsername+"\n"+"password"+mPassword);
Log.d("Parameters",parameters);
try
{
;
linkurl = new Koneksi(this);
SERVER_URL = linkurl.getUrl();
SERVER_URL += "/mobile/Login.php";
url = new URL(SERVER_URL);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
temp=sb.toString();
Log.d("Temp",temp);
response = sb.toString();
Log.d("Response",response);
Log.d("Sb Value",sb.toString());
isr.close();
reader.close();
}
catch(IOException e) {
Toast.makeText(this,e.toString(),Toast.LENGTH_SHORT).show();
}
return response;
}
class LoginTask extends AsyncTask<String, Void, Integer> {
public LoginTask(Login activity, ProgressDialog progressDialog){
}
#Override
protected void onPreExecute(){
progressDialog.show();
}
#Override
protected Integer doInBackground(String... arg0){
}
private void createDialog(String title, String text) {
AlertDialog ad = new AlertDialog.Builder(this)
.setPositiveButton("Ok", null)
.setTitle(title)
.setMessage(text)
.create();
ad.show();
}
}
login.java - edited -> is it like this?
package com.karismaelearning;
public class Login extends Activity {
public Koneksi linkurl;
String SERVER_URL;
private Button login, register, setting;
private EditText username, password;
public ProgressDialog progressDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
setting = (Button)findViewById(R.id.bsetting);
login = (Button) findViewById(R.id.login);
register = (Button) findViewById(R.id.reg);
username = (EditText) findViewById(R.id.uname);
password = (EditText) findViewById(R.id.pass);
setting.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intentSet = new Intent(Login.this, UrlSetting.class);
startActivity(intentSet);
}
});
register.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intentReg = new Intent(Login.this, Register.class);
startActivity(intentReg);
}
});
login.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
new LoginTask().execute();
}
});
}
protected String tryLogin(String mUsername, String mPassword){
Log.d(" TryLoginCheck ","Here");
HttpURLConnection connection;
OutputStreamWriter request = null;
URL url = null;
String response = null;
String temp=null;
String parameters = "username="+mUsername+"&password="+mPassword;
System.out.println("UserName"+mUsername+"\n"+"password"+mPassword);
Log.d("Parameters",parameters);
try{
linkurl = new Koneksi(this);
SERVER_URL = linkurl.getUrl();
SERVER_URL += "/mobile/Login.php";
url = new URL(SERVER_URL);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
temp=sb.toString();
Log.d("Temp",temp);
response = sb.toString();
Log.d("Response",response);
Log.d("Sb Value",sb.toString());
isr.close();
reader.close();
}
catch(IOException e) {
Toast.makeText(this,e.toString(),Toast.LENGTH_SHORT).show();
}
return response;
}
public class LoginTask extends AsyncTask<String, Void, String> {
String response = null;
public LoginTask() {
}
#Override
protected void onPreExecute(){
}
#Override
protected String doInBackground(String... arg0) {
String mUsername = username.getText().toString();
String mPassword = password.getText().toString();
response = tryLogin(mUsername, mPassword).trim();
return response;
}
protected void onPostExecute(String result){
super.onPostExecute(result);
Log.d("Check","Here");
Log.d("Response",response);
if(response.toLowerCase().contains("berhasil")){
String nama = username.getText().toString();
Intent newIntent = new Intent(Login.this, MainPage.class);
Bundle bundle = new Bundle();
bundle.putString("nama", nama);
newIntent.putExtras(bundle);
startActivityForResult(newIntent, 0);
}
else{
//Optional
//Kalau bisa dibuat constant untuk menghindari salah penulisan
String RoleError = "ROLE SALAH";
String UserError = "USER SALAH";
createDialog("Maaf", response.equals(RoleError) ? "Role Anda bukan Student!" : "Username Atau Password Salah!");
}
}
}
private void createDialog(String title, String text) {
AlertDialog ad = new AlertDialog.Builder(this)
.setPositiveButton("Ok", null)
.setTitle(title)
.setMessage(text)
.create();
ad.show();
}
}
use like that
class LoginTask extends AsyncTask<String, Void, Integer> {
private ProgressDialog progressDialog;
#Override
protected void onPreExecute()
{
progressDialog.show();
}
#Override
protected Integer doInBackground(String... arg0)
{
// do all login request here only
}
#Override
protected String onPostExecute(String arg0)
{
progressDialog.dismiss();
// get the response here and show where you want
}
Put in your OnClick method
new LoginTask().execute(stringParam);
to execute your method after clicking element.
In short:
You need to put your tryLogin() code into the doInBackground() method of the AsyncTask.
Incidentally, you should really take a look at your variable naming, the scope of your methods etc. Does tryLogin() really need to be protected? mUsername and mPassword are not member variables of the class, they are local variables.
http://source.android.com/source/code-style.html
Try below code:
public class Login extends Activity {
public Koneksi linkurl;
String SERVER_URL;
private Button login, register, setting;
private EditText username, password;
public ProgressDialog progressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
setting = (Button)findViewById(R.id.bsetting);
login = (Button) findViewById(R.id.login);
register = (Button) findViewById(R.id.reg);
username = (EditText) findViewById(R.id.uname);
password = (EditText) findViewById(R.id.pass);
setting.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intentSet = new Intent(Login.this, UrlSetting.class);
startActivity(intentSet);
}
});
register.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intentReg = new Intent(Login.this, Register.class);
startActivity(intentReg);
}
});
login.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
new LoginTask.execute();
}
});
}
protected String tryLogin(String mUsername, String mPassword)
{
Log.d(" TryLoginCheck ","Here");
HttpURLConnection connection;
OutputStreamWriter request = null;
URL url = null;
String response = null;
String temp=null;
String parameters = "username="+mUsername+"&password="+mPassword;
System.out.println("UserName"+mUsername+"\n"+"password"+mPassword);
Log.d("Parameters",parameters);
try
{
;
linkurl = new Koneksi(this);
SERVER_URL = linkurl.getUrl();
SERVER_URL += "/mobile/Login.php";
url = new URL(SERVER_URL);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
temp=sb.toString();
Log.d("Temp",temp);
response = sb.toString();
Log.d("Response",response);
Log.d("Sb Value",sb.toString());
isr.close();
reader.close();
}
catch(IOException e)
{
Toast.makeText(this,e.toString(),Toast.LENGTH_SHORT).show();
}
return response;
}
class LoginTask extends AsyncTask<String, Void, String> {
private ProgressDialog progressDialog;
private Login activity;
private int id = -1;
public LoginTask(Login activity, ProgressDialog progressDialog)
{
this.activity = activity;
this.progressDialog = progressDialog;
}
#Override
protected void onPreExecute()
{
progressDialog.show();
}
#Override
protected Integer doInBackground(String... arg0)
{
String mUsername = username.getText().toString();
String mPassword = password.getText().toString();
response = tryLogin(mUsername, mPassword).trim();
return response;
}
protected Void onPostExecute(String result){
super.onPostExecute(result);
if(response.toLowerCase().contains("berhasil"))
{
String nama = username.getText().toString();
Intent newIntent = new Intent(Login.this, MainPage.class);
Bundle bundle = new Bundle();
bundle.putString("nama", nama);
newIntent.putExtras(bundle);
startActivityForResult(newIntent, 0);
}
else
{
String RoleError = "ROLE SALAH";
String UserError = "USER SALAH";
createDialog("Maaf", response.equals(RoleError) ? "Role Anda bukan Student!" : "Username Atau Password Salah!");
}
}
}
private void createDialog(String title, String text) {
AlertDialog ad = new AlertDialog.Builder(this)
.setPositiveButton("Ok", null)
.setTitle(title)
.setMessage(text)
.create();
ad.show();
}
}