PHP and AlertDialog not in sync on Android - java

I'm currently building a simple login Android app using a tutorial on YouTube that fetches data from a database and lets the user login. However, when I click the login button, regardless of what the input is, it tells me that the login has been successful. Below is the Java code where the data is entered and the PHP code to connect to the database, every time login is clicked the AlertDialog will pop up saying 'Login successful'. I want it to display 'Login not successful' if the data the user enters is incorrect, can somebody show me how? Thanks
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 = "";
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();
}
}
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);
alertDialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
====
<?php
require "conn.php";
$userName = $_POST["userName"];
$password = $_POST["password"];
$mysql_qry = "select * from database where userName like '$userName' and password like '$password';";
$result = mysqli_query($conn, $mysql_qry);
if(mysqli_num_rows($result) > 0) {
echo "Successful login";
}
else{
echo "Login not successful";
}

In your conn.php file
$dbname = "";
$username = "";
$password = "";
$server = "";
This should not be empty.
Fill it with appropriate data

Related

Why still cannot go to next page?

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.

HttpURLconnection connection failure with non .com website

I have been trying to connect my android app to php server.I made a php server echo "Connection success" so that I could retrieve the same text and display it in Alertbox in my android application.I have a website with a .cf and the app shuts down every time I connect.
I checked my code found nothing wrong, then I tried a .com website, and the app was successfully able to retrieve the html form of whatever was displayed on the page.So is there something that prevents HttpURLconnection form connecting to non .com websites.
Here is the code.
public class BackgroundWorker extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker (Context ctx) {
context = ctx;
}//takes context as an argument
#Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "http://www.thejoint.cf/test.php";
if(type.equals("login")) {
try {
String user_name = params[1];
String password = params[2];
URL url = new URL(login_url);//what does the url object have
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("user_name","UTF-8")+"="+URLEncoder.encode(user_name,"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.setMessage(result);
Log.i("info",result);
alertDialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
So is there something that prevents HttpURLconnection form connecting to non .com websites ?
you create a regex :
String expression = "[^"]+\.com" ;
and test if your url matches with it :
if(your_url.matches(expression)){
// your url end with .com , do what you want
}else{
// your url doesn't end with .com , do what you want
}

Can't connect to php in Android Application

Now I'm working on RESTful API with php and try to connect to it from Android
But I can't connect because it's always catch IOException
here's my Android Code (OnReg is the method when clicked Register Button)
public void OnReg(View view)
{
str_email = et_email.getText().toString();
str_password = et_password.getText().toString();
str_fname = et_fname.getText().toString();
str_lname = et_lname.getText().toString();
type = "register";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type, str_email, str_password, str_fname, str_lname);
}
Here's the BackgroundWorker class
public class BackgroundWorker extends AsyncTask<String, Void, String>
{
Context context;
AlertDialog alertDialog;
BackgroundWorker(Context ctx)
{
context = ctx;
}
#Override
protected String doInBackground(String... params)
{
StringBuilder result = new StringBuilder();
String type = params[0];
BufferedWriter bufferedWriter = null;
BufferedReader bufferedReader = null;
String register_url = "http://192.168.1.9/register.php";
if(type.equals("register"))
{
try
{
//Create data to send to server
JSONObject dataToSend = new JSONObject();
dataToSend.put("email", params[1]);
dataToSend.put("password", params[2]);
dataToSend.put("fname", params[3]);
dataToSend.put("lname", params[4]);
//Initialize and config request, then connect to server
URL url = new URL(register_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true); //enable output (body data)
httpURLConnection.setRequestProperty("Content-Type", "application/json"); //set header
httpURLConnection.connect();
//Write data into server
OutputStream outputStream = httpURLConnection.getOutputStream();
bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
bufferedWriter.write(dataToSend.toString());
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
//Read data response from server
InputStream inputStream = httpURLConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bufferedReader.readLine()) != null)
{
result.append(line).append("\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
}
catch (IOException e)
{
return "Network Error";
}
catch (JSONException e)
{
e.printStackTrace();
}
}
return result.toString();
}
#Override
protected void onPreExecute()
{
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Status");
}
#Override
protected void onPostExecute(String result)
{
alertDialog.setMessage(result);
alertDialog.show();
}
Here's my PHP Code
<?php
$m = new MongoClient();
$db = $m -> ETESS;
$collection = $db -> members;
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$data = json_decode(file_get_contents("php://input"));
$email = $data->email;
$password = $data->password;
$fname = $data->fname;
$lname = $data->lname;
$encrypted_password = md5($password);
$document = array(
"email" => $email,
"password" => $encrypted_password,
"fname" => $fname,
"lname" => $lname
);
if($collection -> insert($document))
{
echo "Registered Successfully !";
$response["result"] = "success";
$response["message"] = "Registered Successfully !";
return json_encode($response);
}
else
{
$response["result"] = "failure";
$response["message"] = "Registered Failed";
return json_encode($response);
}
}
?>
I already added this in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
with all of these code I always get "Network Error" when I clicked Register Button (I assume that it's catch IOException) but when I tried to send POST request by Advanced REST client, everything work perfectly.
Please kindly check my code if there are any mistake.
Thanks
Now I try to connect 192.168.1.9/register.php in browser in my mobile, and it's said
You don't have permission to access /register.php on this server.
I use wamp as web server
Thanks

If we are typing wrong field in the username & pass. It shows a login failure alert, but its calling the next Activity. Tow to fix this?

This code is for my login Activity.
I have used an Intent to call the next page in the onPostExecute() method, but it could not work properly.
If we are typing a wrong value in the username & pass, it shows the login failure alert but it calls the next Activity.
How to fix this?
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://techblog.96.lt/login.php";
if (type.equals("Login")) {
try {
String username = params[1];
String pass = 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("pass", "UTF-8") + "=" + URLEncoder.encode(pass, "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 Success");
}
#Override
protected void onPostExecute(String result) {
Intent i = new Intent(context, NewActivity.class);
context.startActivity(i);
alertDialog.setMessage(result);
alertDialog.show();
}
#Override
protected void onProgressUpdate (Void...values)
{
super.onProgressUpdate(values);
}
}
onPostExecute will always start the next Activity regardless of the value of the String result.
You need to check that value for whatever determines if you've successfully logged in. Also check it for null since that is also being returned by doInBackground
You should use onPostExecute method. You need to check response code inside your doInBackground method and depending on the result you need to return an appropriate String. Then inside onPostExecute check that response from doInBackground and take appropriate actions.

Login not successful on MySQL database from android app

I have created an android app that logins into a MySQL database but I don't receive any results. The 'result' variable in the alert dialog box in backgroundWorker.java (function "onPostExecute") returns null, can anyone solve this problem?
BackgroundWorker.java`
public class BackgroundWorker extends
AsyncTask<String,String,String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker(Context ctx)
{
context =ctx;
}
#Override
protected String doInBackground(String... params) {
String type=params[0];
String login_url="192.168.10.9/login.php";
if(type.equals("login"))
{
try {
String user_name = 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("user_name","UTF-8")+"="+URLEncoder.encode(user_name,"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) {
Log.i("ok", "Result " + Result);
alertDialog.setMessage(Result);
alertDialog.show();
}
CheckConn.java
public class CheckConn extends AppCompatActivity {
EditText user;
EditText pass;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.check_conn);
user = (EditText) findViewById(R.id.et_u);
pass = (EditText) findViewById(R.id.et_p);
Button press = (Button) findViewById(R.id.btn_login);
press.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onLogin();
}
});
}
public void onLogin()
{
String username= user.getText().toString();
String password=pass.getText().toString();
String type="login";
BackgroundWorker backgroundWorker=new BackgroundWorker(this);
backgroundWorker.execute(type,username,password);
}
}
connection.php
<?php
$mysql_usernmae="root";
$mysql_password="*****";
$db="map";
$db= new mysqli('localhost',$mysql_usernmae,$mysql_password,$db);
?>
login.php
<?php
require "connection.php";
$user_name=$_POST["user_name"];
$user_pass=$_POST["password"];
$mysql_qry="select * from user_info where user_name like
'$user_name' and user_password like 'user_pass';";
$result=mysqli_query($db,$mysql_qry);
if (mysqli_num_rows($result) > 0)
{
echo "login Successsss";
}
else
{
echo "faileddddd Booooo";
}
?>
`
why you don't ejecute first your login.php file in the browser, harcode the values for user_name and user_pass, and check if the connection is working on server side,
after that you can check if your user and pass are coming from android app, I must assume you have a database with some data in the table you are making the query, also check if the name of database, table, query are correct, you can check with MySQL workbench if the query works and is returning some result.

Categories