MY PROBLEMS :
1. No error on it.
2. Cannot go to next page but I already put if else statement for login at onPostExecute.
3. It is true my if else statement?
Below is a prove my button clickable but not go to the next page :
Below is my onPostExecute code snippet :
Below is : Background.java for connection mysql database.
public class Background extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
Background(Context ctx) {
context = ctx;
}
#Override
protected String doInBackground(String... params)
{
String type = params[0];
String login_url = "http://172.20.10.4/LoginLab3.php";
String reg_url = "http://172.20.10.4/RegisterLab3.php";
if (type.equals("login")) {
try {
String username = params[1];
String password = params[2];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8") + "&"
+ URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "ISO-8859-1"));
String result = "";
String line = "";
while ((line = bufferedReader.readLine()) != null)
{
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
else if(type.equals("register"))
{
try {
String name = params[1];
String surname = params[2];
String age = params[3];
String username = params[4];
String password = params[5];
URL url = new URL(reg_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("name","UTF-8")+"="+URLEncoder.encode(name,"UTF-8")+"&"
+URLEncoder.encode("surname","UTF-8")+"="+URLEncoder.encode(surname,"UTF-8")+"&"
+URLEncoder.encode("age","UTF-8")+"="+URLEncoder.encode(age,"UTF-8")+"&"
+URLEncoder.encode("username","UTF-8")+"="+URLEncoder.encode(username,"UTF-8")+"&"
+URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"ISO-8859-1"));
String result="";
String line="";
while((line = bufferedReader.readLine())!= null)
{
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute()
{
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
#Override
protected void onPostExecute(final String result)
{
final AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setTitle("Login Status");
dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialogInterface, int i)
{
Boolean login = (context.equals("login"));
if(login==true)
{
Intent in = new Intent(context, Welcome.class);
context.startActivity(in);
((Activity)context).finish();
}
else
{
dialog.setMessage("Wrong username and password");
}
}
});
dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
dialog.create().show();
}
#Override
protected void onProgressUpdate(Void... values)
{
super.onProgressUpdate(values);
}
}
Below is : Login.java
public class Login extends AppCompatActivity
{
EditText username, password;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
username = findViewById(R.id.etUsername);
password = findViewById(R.id.etPassword);
}
public void OnLog(View view)
{
String Username = username.getText().toString();
String Password = password.getText().toString();
String type = "login";
if(Username.equals("") || Password.equals(""))
{
Toast.makeText(getApplicationContext(), "Username and Password are required!", Toast.LENGTH_LONG).show();
}
else {
Background bg = new Background(this);
bg.execute(type, Username, Password);
}
}
public void OnReg(View view) {
startActivity(new Intent(getApplicationContext(), Register.class));
}
}
The condition on your if statement is never true.
context of type Context can never equal to a string of login. So the if clause is never run.
The yellow highlighted inspection is probably complaining about that.
I think the login result will be in the string result passed in as a parameter. You'll probably have to parse the result and see if the login is successful.
Related
I have a login form which verifies whether the username or password matches the ones in my database but i coded the verification in another java class which looks like this:
AlertDialog dialog;
Context context;
public background (Context context){
this.context = context;
}
#Override
protected void onPreExecute() {
dialog = new AlertDialog.Builder(context).create();
dialog.setTitle("Login Status");
}
#Override
protected void onPostExecute(String s) {
dialog.setMessage(s);
dialog.show();
}
#Override
protected String doInBackground(String... voids) {
String result = "";
String user = voids[0];
String pass = voids[1];
String connStr = "http://xzylrey1.heliohost.org/loginandroid.php";
try {
URL url = new URL(connStr);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setRequestMethod("POST");
http.setDoInput(true);
http.setDoOutput(true);
OutputStream ops = http.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(ops, "UTF-8"));
String data = URLEncoder.encode("user", "UTF-8") + "=" + URLEncoder.encode(user, "UTF-8")
+ "&&" + URLEncoder.encode("pass", "UTF-8") + "=" + URLEncoder.encode(pass, "UTF-8");
writer.write(data);
writer.flush();
writer.close();
ops.close();
InputStream ips = http .getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(ips, "ISO-8859-1"));
String line = "";
while((line = reader.readLine()) != null){
result += line;
}
reader.close();
ips.close();
http.disconnect();
return result;
} catch (MalformedURLException e) {
result = e.getMessage();
} catch (IOException e) {
result = e.getMessage();
}
return result;
This is the main class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_username = findViewById(R.id.et_username);
etPassword = findViewById(R.id.et_Password);
btnLogin = findViewById(R.id.btn_Login);
}
public void moveToActivityTwo(){
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
startActivity(intent);
}
public void loginBtn(View view) {
String user = et_username.getText().toString();
String pass = etPassword.getText().toString();
background bg = new background(this);
bg.execute(user, pass);
moveToActivityTwo();
I tried putting the method below the bg.execute line, but then it would just automatically redirect to the other activity is there another way to do this?
You need to move the moveToActivityTwo() method to the end of the onPostExecute() method.
It will look like this:
protected void onPostExecute(String s) {
dialog.setMessage(s);
dialog.show();
context.moveToActivityTwo();
}
It calls callback pattern.
My problems :
1. I have error on it.
2. Why cannot go to the next page when I use startActivity?
3. How to solve?
4. I already use startActivity by using Intent method
Below is prove 1 :
Below is prove 2 :
Below is prove 3 :
Below is code snippet :
public void OnLog(View view)
{
String Username = username.getText().toString();
String Password = password.getText().toString();
String type = "login";
if(Username.equals("") || Password.equals(""))
{
Toast.makeText(getApplicationContext(), "Please fill the Username and Password!", Toast.LENGTH_LONG).show();
}
else {
Background bg = new Background(Context, act);
bg.execute(type, Username, Password);
}
}
Below is coding for Background.java :
public class Background extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
Background(Context ctx) {
context = ctx;
}
#Override
protected String doInBackground(String... params)
{
String type = params[0];
String login_url = "http://172.20.10.4/LoginLab3.php";
String reg_url = "http://172.20.10.4/RegisterLab3.php";
if (type.equals("login")) {
try {
String username = params[1];
String password = params[2];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8") + "&"
+ URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "ISO-8859-1"));
String result = "";
String line = "";
while ((line = bufferedReader.readLine()) != null)
{
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
else if(type.equals("register"))
{
try {
String name = params[1];
String surname = params[2];
String age = params[3];
String username = params[4];
String password = params[5];
URL url = new URL(reg_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("name","UTF-8")+"="+URLEncoder.encode(name,"UTF-8")+"&"
+URLEncoder.encode("surname","UTF-8")+"="+URLEncoder.encode(surname,"UTF-8")+"&"
+URLEncoder.encode("age","UTF-8")+"="+URLEncoder.encode(age,"UTF-8")+"&"
+URLEncoder.encode("username","UTF-8")+"="+URLEncoder.encode(username,"UTF-8")+"&"
+URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"ISO-8859-1"));
String result="";
String line="";
while((line = bufferedReader.readLine())!= null)
{
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute()
{
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
#Override
protected void onPostExecute(String result)
{
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setTitle("Login Status");
dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
startActivity(new Intent(Login.this, Welcome.class));
}
});
dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
dialog.create().show();
}
#Override
protected void onProgressUpdate(Void... values)
{
super.onProgressUpdate(values);
}
}
Help me! i have some problem on it. I already use almost all method, but cannot go to the next page. Why ?
Activity OnCreate Code
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Pass activity to Async Task
new Background(this).execute();
}
Async Task
public class Background extends AsyncTask<Void,Void,Void> {
private Context context;
public Background(Context context){
this.context=context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Intent intent = new Intent(context, TargetActivity.class);
context.startActivity(intent);
((Activity)context).finish();
}
}
Try context.startActivity() because AsyncTask class don't have startActivity() method inherited.
Also, pass the activity in the constructor and assign it to a variable and use that variable while creating intent
Context context;
Activity activity;
AlertDialog alertDialog;
Background(Context ctx, Activity act) {
context = ctx;
activity = act;
}
inside onClick()
context.startActivity(new Intent(activity, Welcome.class));
I would like to include a code such that, when a user registers a username that has already been used in my app, he/she will get a toast saying "Username is already taken".
Register.java
public class Register extends AppCompatActivity {
EditText regEmail, regPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
regEmail = (EditText)findViewById(R.id.reg_email);
regPassword = (EditText)findViewById(R.id.reg_password);
}
public void OnReg(View view) {
String strEmail = regEmail.getText().toString();
String strPassword = regPassword.getText().toString();
String type = "register";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type, strEmail, strPassword);
}}
BackgroundWorker.java
public class BackgroundWorker extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker (Context ctx){
context = ctx;
}
#Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "http://10.93.22.231/login.php";
String register_url = "http://10.93.22.231/register.php";
if (type.equals("login")){
try {
String email = params[1];
String password = params[2];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("email","UTF-8")+"="+URLEncoder.encode(email,"UTF-8")+"&"
+URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String result = "";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else if (type.equals("register")){
try {
String regEmail = params[1];
String regPassword = params[2];
URL url = new URL(register_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("email","UTF-8")+"="+URLEncoder.encode(regEmail,"UTF-8")+"&"
+URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(regPassword,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String result = "";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
#Override
protected void onPostExecute(String result) {
alertDialog.setMessage(result);
if (result.contains("success")) {
Intent intent = new Intent(context, MainActivity.class);
context.startActivity(intent);
} else {
alertDialog.show();
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
Register.php
<?php
require "conn.php";
$email = $_POST["email"];
$password = $_POST["password"];
$mysql_qry = "INSERT INTO users (email, password) VALUES ('$email','$password')";
if($conn->query($mysql_qry) === TRUE){
echo "Insert successful";
} else {
echo "Insert failed, please try again.";
}
$conn->close();
?>
Toast.makeText(YourActivtyOrContext,"Username Taken", Toast.LENGTH_LONG).show();
on Post execute you can do some thing like this
also at the server level if the username already exists you should not save the record instead of that you should pass the value that username already exists
#Override
protected void onPostExecute(String result) {
if (result.contains("success")) {
Intent intent = new Intent(context, MainActivity.class);
context.startActivity(intent);
} else {
Toast.makeText(context,result, Toast.LENGTH_LONG).show();
}
}
Hey please check this code, maybe it can solve your problem. This is simple code.
if (ConnectivityDetector.isConnectingToInternet(RegisterActivity.this)) {
JSONObject jsonObjectInput = new JSONObject();
jsonObjectInput.put(WebField.REGISTER_USER.REQUEST_USER_NAME,
edtUserName.getText().toString());
String mode = "RegisterUser";
new GetJsonWithCallBack(RegisterActivity.this, jsonObjectInput,
1, mode, new OnUpdateListener() {
#Override
public void onUpdateComplete(JSONObject jsonObject,
boolean isSuccess) {
if (isSuccess) {
try {
if (jsonObject != null) {
if (jsonObject.has("userDetail")) {
JSONObject jsonUserDetails = jsonObject.getJSONObject("userDetail");
RegisterData regData = new RegisterData();
regData.setUserName(jsonUserDetails.getString(WebField.REGISTER_USER.RESPONSE_USER_NAME));
SessionManager.saveData(RegisterActivity.this, regData);
finish();
}
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
if (jsonObject != null) {
try {
String Status = jsonObject.getString("status");
String message = jsonObject.getString("message");
if (message.equalsIgnoreCase("User already Exists")) {
GlobalMethod.showAlert(RegisterActivity.this, "User name already exists..!!");
} else if (message.equalsIgnoreCase("Email id already Exists")) {
GlobalMethod.showAlert(RegisterActivity.this, "Email id already exists..!!");
} else if (message.equalsIgnoreCase("Mobile no already Exists")) {
GlobalMethod.showAlert(RegisterActivity.this, "Mobile no already exists..!!");
} else {
GlobalMethod.showAlert(RegisterActivity.this, jsonObject.getString("message"));
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
}
}
}
}).execute();
} else {
AlertDialogUtility.showInternetAlert(RegisterActivity.this);
}
} catch (Exception e) {
e.printStackTrace();
}
try this way
#Override
protected void onPostExecute(String result) {
alertDialog.setMessage(result);
if (result.contains("success")) {
JSONObject json= new JSONObject(result);
if(json.has("message"){
String message=json.getString("message");
Toast.makeText(ctx,message,Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(context, MainActivity.class);
context.startActivity(intent);
} else {
alertDialog.show();
}
}
UPDATE
User validation query
$mysql_qry="SELECT * FROM users WHERE email='$email'";
if($conn->query($mysql_qry) === TRUE){
}else{}
In Logcat It Displays : Attempted to finish an input event but the input event receiver has already been disposed
In Catch Block Message Box I am Having An Error Like println needs a message. Please Help Me.
I Use Android Studio 2.0
Here is LOGCAT :
"12-13 03:48:40.598 2129-2129/com.mysqlapp.bug.mysqlapp
W/InputEventReceiver: Attempted to finish an input event but the input
event receiver has already been disposed."
public class MainActivity extends AppCompatActivity {
EditText etUserName,etPassword;
String userName,password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etUserName = (EditText) findViewById(R.id.etUserName);
etPassword = (EditText) findViewById(R.id.etPassword);
}
public void btnLoginClick(View v)
{
try
{
userName = etUserName.getText().toString();
password = etPassword.getText().toString();
Log.d("Hello","Here");
MySqlDatabaseHelper sqlCls = new MySqlDatabaseHelper(this);
sqlCls.doInBackground("login",userName,password);
}
catch (Exception ex)
{
AlertDialog alert = new AlertDialog.Builder(this).create();
alert.setTitle("Something Went Wrong");
alert.setMessage("-"+ex.getMessage()+"-");
alert.show();
}
}
}
Here is Second Class :
public class MySqlDatabaseHelper extends AsyncTask<String,Void,String> {
Context ctx;
String method,userID,userName,password,postData,result;
MySqlDatabaseHelper(Context _ctx)
{
ctx = _ctx;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
method = params[0].toString();
if(method.equals("login"))
{
userName = params[1].toString();
password = params[2].toString();
URL url = new URL("http://10.0.2.2/Android/login.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoInput(true);
OutputStream os = conn.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os,"UTF-8");
BufferedWriter bw = new BufferedWriter(osw);
postData = URLEncoder.encode("uname","UTF-8") + "=" + URLEncoder.encode(userName,"UTF-8") + "&" +
URLEncoder.encode("password","UTF-8") + "=" + URLEncoder.encode(password,"UTF-8");
bw.write(postData);
bw.flush();
bw.close();
osw.close();
os.close();
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is,"UTF-8");
BufferedReader br = new BufferedReader(isr);
String line = "";
while ((line = br.readLine()) != null)
{
result += line;
}
br.close();
isr.close();
is.close();
conn.disconnect();
return result;
}
else
{
return "NONE";
}
}
catch (Exception ex)
{
String err = (ex.getMessage() == null) ? "Error occured" : ex.getMessage();
Log.e("Err",err);
AlertDialog alert = new AlertDialog.Builder(ctx).create();
alert.setTitle("Something Went Wrong1");
alert.setMessage("-"+ex.getMessage()+"-");
alert.show();
return "ERR";
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
AlertDialog alert = new AlertDialog.Builder(ctx).create();
alert.setTitle("Successfully Worked");
alert.setMessage("-"+result+"-");
alert.show();
}
}
Everything on the server side end of things is working as it should. My problem here is that I'm not sure how to go back to login page if the HTTP response is "Registration success!"
Both my Login and Register classes are relying on BackgroundTask to handle the asynchronous operations.
Here is the code for BackgroundTask.
public class BackgroundTask extends AsyncTask<String, Void, String> {
AlertDialog mAlertDialog;
Context context;
private CheckTask mCheckTask;
BackgroundTask(Context context, Boolean login, Boolean register) {
this.context = context;
mCheckTask = new CheckTask(login, register);
}
#Override
protected String doInBackground(String... params) {
String reg_url = "http://www.myegotest.com/register.php";
String login_url = "http://www.myegotest.com/login.php";
////////////////////////REGISTER SCRIPT/////////////////////////////
if (mCheckTask.getIsRegisterTask()) {
String first_name = params[0];
String last_name = params[1];
String username = params[2];
String password = params[3];
try {
//Set the URL we are working with
URL url = new URL(reg_url);
//Open a url connection and set params for the url connection
HttpURLConnection LucasHttpURLConnection = (HttpURLConnection) url.openConnection();
LucasHttpURLConnection.setRequestMethod("POST");
LucasHttpURLConnection.setDoOutput(true);
LucasHttpURLConnection.setDoInput(true);
//Retrieve the output stream
OutputStream os = LucasHttpURLConnection.getOutputStream();
//Create a buffered writer to write the data to the output stream output stream.
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
//Encode Data we are sending on the output stream
String data = URLEncoder.encode("first_name", "UTF-8") + "=" + URLEncoder.encode(first_name, "UTF-8") + "&" +
URLEncoder.encode("last_name", "UTF-8") + "=" + URLEncoder.encode(last_name, "UTF-8") + "&" +
URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8") + "&" +
URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
//Write the data to the output stream, and close buffered writer
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
//Close output stream
os.close();
//InputStream to get response
InputStream IS = LucasHttpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(IS, "iso-8859-1"));
String response = "";
String line;
while ((line = bufferedReader.readLine()) != null) {
response += line;
}
bufferedReader.close();
IS.close();
//LucasHttpURLConnection.disconnect();
return response;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//////////////////////////////////LOGIN SCRIPT/////////////////////////////////////////
} else if (mCheckTask.getIsLoginTask()) {
String username = params[0];
String password = params[1];
try {
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8") + "&" +
URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
//InputStream to get response
InputStream IS = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(IS, "iso-8859-1"));
String response = "";
String line;
while ((line = bufferedReader.readLine()) != null) {
response += line;
}
bufferedReader.close();
IS.close();
httpURLConnection.disconnect();
return response;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
if (mCheckTask.getIsLoginTask()) {
mAlertDialog = new AlertDialog.Builder(context).create();
mAlertDialog.setTitle("Login Information... ");
} else {
mAlertDialog = new AlertDialog.Builder(context).create();
mAlertDialog.setTitle("Register Information... ");
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
if (result.equals("Please choose another username")) {
mAlertDialog.setMessage(result);
mAlertDialog.setButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
mAlertDialog.show();
} else if (result.equals("Registration success!")) {
mAlertDialog.setMessage(result);
mAlertDialog.setButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
mAlertDialog.show();
} else {
mAlertDialog.setMessage(result);
mAlertDialog.show();
}
}
}
If the context reference you are holding from the constructor parameter is an activity you might consider changing the constructor signature and field type to Activity. From there you can call mActivity.finish(); inside the dialog click listener. This will cause the activity to close and step back by one on the back stack.
You might also investigate using Activity.setResult(int, Intent) to deliver information back to the previous activity using onActivityResult(int, int, Intent)
This can be handy for pre filling the login form when the registration activity closes.
http://developer.android.com/training/basics/intents/result.html
You can create a dispatch method where you check the currentuser with your database. I am using Parse, However you can use preferenceManager same as in example here Preference manager example here
Public class Dispatch extends ActionBarActivity {
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
// Check if there is current user info
if (ParseUser.getCurrentUser() != null) {
// Start an intent for the logged in activity
startActivity(new Intent(this, Home.class));
} else {
// Start and intent for the logged out activity
startActivity(new Intent(this, login.class));
}
}
}