my php code to connect with database for android - java

im trying to connect my android app with the data base im using for the website but somehow it doesnt want to connect
this is my java code im using for the connect
Android manifest i added
<uses-permission android:name="android.permission.INTERNET"></uses-
permission>
background.java
package com.example.myapplication;
import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
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.0.2.2//android/login.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();
}
}
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);
}
}
login.java
package com.example.myapplication;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class login extends AppCompatActivity implements View.OnClickListener
{
Button liButton;
EditText liEmail, liPassword;
TextView liSignup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
liEmail = (EditText) findViewById(R.id.liEmail);
liPassword = (EditText) findViewById(R.id.liPassword);
liButton =(Button) findViewById(R.id.liButton);
liSignup= (TextView) findViewById(R.id.liSignup);
liButton.setOnClickListener(this);
liSignup.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.liButton:
String Email = liEmail.getText().toString();
String Password = liPassword.getText().toString();
String type = "login";
BackgroundWorker backgroundworker = new BackgroundWorker(this);
backgroundworker.execute(type, Email, Password);
break;
case R.id.liSignup:
startActivity(new Intent(this, signup.class));
break;
}
}
}
this is my php code
<?php
$conn = mysqli_connect('127.0.0.1','root','','signup');
?>
<?php
include('conn.php');
if(!session_id())
session_start();
if (isset($_POST['Email'])
and isset($_POST['Password'])
and !empty($_POST['Email'])
and !empty($_POST['Password'])){
$Email = $_POST['Email'];
$Password= $_POST['Password'];
$getinfo = "SELECT * FROM users WHERE Email ='$Email' LIMIT 1";
$res = mysqli_query($conn,$getinfo);
$row = mysqli_fetch_assoc($res);
if (mysqli_num_rows($res)>0) {
$dbPassword = $row['Password'];
$Password = PASSWORD_VERIFY($Password, $dbPassword);
if ($Email == $row ['Email'] and $Password == $dbPassword) {
$id = $row['id'];
$_SESSION['id'] = $id;
exit();
} else{
echo 'Wrong Email or Password.';
}
} else{
echo 'Wrong Email or Password.';
}
}
?>
i believe my java code is right but im not sure what to do with my php if there is something wrong

this line
if ($Email == $row ['Email'] and $Password == $dbPassword) {
is wrong/the problem. You already password_verified, which returns a boolan, so it should be.
if ($Email == $row ['Email'] and $Password) {
And you don't need to re-check if $Email == $row ['Email'], because you queried for it already.
So you can reduce your code to:
if (mysqli_num_rows($res)>0) {
$dbPassword = $row['Password'];
if (PASSWORD_VERIFY($Password, $dbPassword)) {
$id = $row['id'];
$_SESSION['id'] = $id;
exit();
} else {
//...

Related

Java getter and setter issue

When setting a value in setData the value is OK in String returnDataTab1, but when getId() states it's null. Is the issue staring me in the face.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.widget.Toast;
public class BackgroundTask extends AsyncTask<String,Void,String>
{
Context context;
String dataResponse = "";
String returnDataTab1;
//getter
public String getId()
{
//The system out below shows a value of null although the setData method set it ok.
System.out.println("zzzzzzzzzzzzzzzzzzzzzzzzzzzzz : "+returnDataTab1);
return returnDataTab1;
}
public void setData(String newResult)
{
returnDataTab1=newResult;
System.out.println("zzzzzzzzzzzzzzzzzzzzzzzzzzzzz : "+returnDataTab1);
/// the returnDataTab value is set ok
}
BackgroundTask(Context ctx)
{
this.context = ctx;
}
#Override
protected String doInBackground(String... params)
{
String urlLogin = "";
String task = params[0];
String loginusername="";
String loginpassword="";
if (task.equals("login"))
{
urlLogin = "http://domain/LoginAndRegister-login.php";
loginusername = params[1];
loginpassword = params[2];
//
try
{
URL url = new URL(urlLogin);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
//send the driver number to the database
OutputStream outputStream = httpURLConnection.getOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream,"UTF-8");
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
String myDatalogin = URLEncoder.encode("identifier_loginEmail","UTF-8")+"="+URLEncoder.encode(loginusername,"UTF-8")
+"&"+URLEncoder.encode("identifier_loginPassword","UTF-8")+"="+URLEncoder.encode(loginpassword,"UTF-8");
bufferedWriter.flush();
bufferedWriter.write(myDatalogin);
bufferedWriter.close();
outputStream.close();
//get response from the database
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
//String dataResponse = "";
String inputLine = "";
while((inputLine = bufferedReader.readLine()) != null)
{
dataResponse += inputLine;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return dataResponse;
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}//end if statement
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values)
{
super.onProgressUpdate(values);
}
/// gets value OK from background task
#Override
protected void onPostExecute(String result)
{
this.setData(result);
}
}
Would appreciate if you guys could take a look and point out the obvious mistake.
This is the code called from a tab
BackgroundTask backgroundTaskLogin = new BackgroundTask(Tab1Activity.this);
backgroundTaskLogin.execute(task,username,password);
String x;
x=backgroundTaskLogin.getId();
Toast.makeText(getApplicationContext(), "Data Response : "+x, Toast.LENGTH_SHORT).show();
The values are set from
protected void onPostExecute(String result)
{
this.setData(result);
// gets result value fine
}

reading JSON data from php file in android application

i am just a beginner in developing android applications, i wanted to connect my application to a server so i could get data from MySQL. so i tried to make login part first but i have some problems. my code doesn't work for reading JSON.
my codes are as below:
LoginActivity(MainActivity) :
package ir.naserpour.sportclub;
import android.content.Context;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
public class LoginActivity extends AppCompatActivity {
String link;
String response;
//get values
String username,password;
#Override
protected void attachBaseContext (Context newBase){
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//define things
TextView menu = (TextView) findViewById(R.id.menu);
final EditText login_username = (EditText) findViewById(R.id.login_username);
final EditText login_password = (EditText) findViewById(R.id.login_password);
Button login_login = (Button) findViewById(R.id.login_login);
Button login_register = (Button)findViewById(R.id.login_register);
CheckBox rememberme = (CheckBox)findViewById(R.id.login_remeberme);
//set icon type face
Typeface fonticon = Typeface.createFromAsset(getAssets(), "fonts/icon.ttf");
menu.setTypeface(fonticon);
login_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
username = login_username.getText().toString();
password = login_password.getText().toString();
//check values
if (username.length() <1 || password.length() < 1) {
Toast.makeText(getApplicationContext(), "fields cannot be empty", Toast.LENGTH_SHORT).show();
} else {
//generate link
link = "http://localhost:8080/login.php?username="+username+"&password="+password;
login();
if(response=="true"){
Toast.makeText(getApplicationContext(), "true", Toast.LENGTH_SHORT).show();
}else if(response=="false"){
Toast.makeText(getApplicationContext(), "false", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "response", Toast.LENGTH_SHORT).show();
}
}
}
});
}
#Override
protected void onPause () {
super.onPause();
finish();
}
public String login() {
new JSONParse().execute();
return response;
}
public class JSONParse extends AsyncTask<String, String, JSONObject> {
#Override
public void onPreExecute() {
super.onPreExecute();
Toast.makeText(getApplicationContext(),"getting data ...",Toast.LENGTH_SHORT).show();
}
#Override
public JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(link);
return json;
}
#Override
public void onPostExecute(JSONObject json) {
try {
JSONArray result = json.getJSONArray("result");
JSONObject c = result.getJSONObject(0);
try {
String res = new String(c.getString("response").getBytes("ISO-8859-1"), "UTF-8");
response = res;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
JSONParser.java:
package ir.naserpour.sportclub;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
/**
* Created by Mohammad Naserpour on 9/22/2016.
*/
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httppost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
and also my login.php script:
<?php
define("HOST","localhost");
define("USERNAME","root");
define("PASSWORD","");
define("NAME","users");
$con = mysqli_connect(HOST,USERNAME,PASSWORD,NAME);
$username = $_GET["username"];
$password = $_GET["password"];
$sql = "SELECT * FROM userinfo WHERE username ='$username' AND password='$password'";
$check = mysqli_fetch_array(mysqli_query($con,$sql));
if(isset($check)){
echo '{"result":[{"response":"true"}]}';
}else{
echo '{"result":[{"response":"false"}]}';
}
mysqli_close($con);
?>
i would be so happy if i find out the problem. thank you.
see this tutorial :
its a full tutorial about login process using google volley
First : On device side, Use volley, its simple and easy to use
Second : On server, what is {"result":[{"response":"true"}]}
any problem with {"result":true} ??
Last but not the least : Did you use JSON before or this code is trial and error copy paste from some tutorials?

unable get json from url

i have to create simple login page where after entering username and password we click to submit button. when we click on submit button then it goes to server and check the username and other information if the info matches then it moves to next activity otherwise nothing will happen . below is my code . i dont know how to do after getting response from the server.
package com.example.dev_1.myapplication;
import android.app.DownloadManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.net.Uri
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.ref.ReferenceQueue;
import java.net.HttpURLConnection;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.sql.Connection;
public class MainActivity extends AppCompatActivity {
Button button;
String connectionString, params;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText username = (EditText) findViewById(R.id.editText);
final EditText password = (EditText) findViewById(R.id.editText2);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener((new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == R.id.button1) {
String userNameString = username.getText().toString();
String passwordString = password.getText().toString();
String url = "http://122.160.78.189:82/androidserver/LoginSalesPerson";
String params = null;
try {
params = "user=" + URLEncoder.encode(userNameString, "UTF-8") + "&password=" + URLEncoder.encode(passwordString, "UTF-8") + "&appVersion=1.26";
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
JSONArray dataJsonArr = null;
new Mytask().execute(url, params);
}
}
}));
}
private void checkLogin(String result) throws JSONException {
String url = "http://122.160.78.189:82/androidserver/LoginSalesPerson";
JSONArray user = null;
try{
// Creating new JSON Parser
///JSONParser jParser = new JSONParser();
// Getting JSON from URL
// JSONObject json = jParser.getJSONFromUrl(url);
if (result != null)
{
//JSONObject emp=(new JSONObject(url).getJSONObject("username"));
JSONObject emp = new JSONObject(result.toString());
String username=emp.getString("userName");
//String empspassword=emp.getString("password");
String str="username:"+username;
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
intent.putExtra("username", str);
startActivity(intent);}
}catch (Exception e) {
e.printStackTrace();
}
}
// EditText usernameString = (EditText) findViewById(R.id.editText);
// String str = usernameString.getText().toString();
// if (sharedPreferences.equals(str)) {
// Intent intent = new Intent(MainActivity.this, Main2Activity.class);
// intent.putExtra("username", str);
//startActivity(intent);
// To retrieve value from shared preference in another activity
// sharedPreferences = getApplicationContext().getSharedPreferences(
// "sharedPrefName", 0);
// id = sharedPreferences.getString("key_name", "defaultvalue");
class Mytask extends AsyncTask<String, Void, String> {
// Runs in UI before background thread is called
#Override
protected void onPreExecute() {
setProgressBarVisibility(true);
// Do something like display a progress bar
}
// This is run in a background thread
#Override
protected String doInBackground(String... params) {
return getFromServer(params[0], params[1]);
}
// This runs in UI when background thread finishes
#Override
protected void onPostExecute(String result) {
try {
checkLogin(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
public String getFromServer(String connectionString, String params) {
String response = "";
try {
// android.os.Debug.waitForDebugger();
URL url = new URL(connectionString);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(10 * 1000); //10 Seconds
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Content-Length", "" + Integer.toString(params.getBytes().length));
con.setRequestProperty("Content-Language", "en-US");
con.setUseCaches(false);
con.setDoInput(true);
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(params);
wr.flush();
wr.close();
InputStream is = con.getInputStream();
response = read(is);
} catch (Exception e) {
e.printStackTrace();
} finally {
return response;
}
}
private String read(InputStream in) {
BufferedReader reader;
StringBuilder response = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
return response.toString();
}
}
}
}

How to start an activity in BackgroundTask only after verifing that the username and password is correct?

I am trying to start an activity "Display" which is supposed to start only after the user is authenticated (the usernames and passwords are stored in phpmyadmin database)
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class PatLogin extends Activity {
EditText a,b;
String login_name,login_pass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pat_login);
}
public void patbuttonClick(View v) {
if (v.getId() == R.id.patlogin) {
a = (EditText) findViewById(R.id.TFpusername);
b = (EditText) findViewById(R.id.TFppassword);
login_name = a.getText().toString();
login_pass = b.getText().toString();
String method = "login";
BackgroundTask backgroundTask = new BackgroundTask(this);
backgroundTask.execute(method,login_name,login_pass);
//If possible I would like to call the "Display" activity from here but only when the correct username and password is entered.
//If it's not possible to call from here then I would like to know how to call "Display" activity from "BackgrounTask.java".
}
}
}
The BackgroundTask.java is used to authenticate the user (check if the username and password match) through the phpmyadmin database.
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class BackgroundTask extends AsyncTask<String,Void,String> {
AlertDialog alertDialog;
Context ctx;
BackgroundTask(Context ctx)
{
this.ctx =ctx;
}
int flag=0;
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(ctx).create();
alertDialog.setTitle("Login Information....");
}
#Override
protected String doInBackground(String... params) {
String login_url = "http://10.0.2.2/mobidoc/login.php";
String method = params[0];
if(method.equals("login"))
{
String login_name = params[1];
String login_pass = params[2];
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("login_name","UTF-8")+"="+URLEncoder.encode(login_name,"UTF-8")+"&"+
URLEncoder.encode("login_pass","UTF-8")+"="+URLEncoder.encode(login_pass,"UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String response = "";
String line = "";
while ((line = bufferedReader.readLine())!=null)
{
response+= line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return response;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
if(result.equals("Registration Success..."))
{
Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
}
else
{
alertDialog.setMessage(result);
alertDialog.show();
//When I use the following 2 lines of code, It calls the Display activity even if the wrong password is entered. I need a certain condition to be applied.
Intent myIntent = new Intent(ctx, Display.class);
ctx.startActivity(myIntent);
}
}
}
So what I want to do is call an activity named "Display". This activity should be called only when the correct username and password is entered.
I am attaching the php file too, just for reference.
<?php
require "init.php";
$username = $_POST["login_name"];
$password = $_POST["login_pass"];
$password = md5($password);
$sql_query = "select name from pat_info where username like '$username' and password like '$password';";
$result = mysqli_query($con,$sql_query);
if(mysqli_num_rows($result)>0)
{
$row = mysqli_fetch_assoc($result);
$name = $row["name"];
echo "Login Success... Welcome ".$name;}
else{
echo "Login Failed...Try Again.";
}
Ok I got the solution to it. I had to compare the echo of the php file and compare it with "res" which stores the value of "result". The modified "BackgroundTask.java" is below:
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class BackgroundTask extends AsyncTask<String,Void,String> {
AlertDialog alertDialog;
Context ctx;
String res;
BackgroundTask(Context ctx)
{
this.ctx =ctx;
}
int flag=0;
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(ctx).create();
alertDialog.setTitle("Login Information....");
}
#Override
protected String doInBackground(String... params) {
String login_url = "http://10.0.2.2/mobidoc/login.php";
String method = params[0];
if(method.equals("login"))
{
String login_name = params[1];
String login_pass = params[2];
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("login_name","UTF-8")+"="+URLEncoder.encode(login_name,"UTF-8")+"&"+
URLEncoder.encode("login_pass","UTF-8")+"="+URLEncoder.encode(login_pass,"UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String response = "";
String line = "";
while ((line = bufferedReader.readLine())!=null)
{
response+= line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
//I stored the response in the following String variable (res)
res = response;
return response;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
if(result.equals("Registration Success..."))
{
Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
}
else if(res.equals("Login Failed...Try Again."))
{
alertDialog.setMessage(result);
alertDialog.show();
}
else
{
alertDialog.setMessage(result);
alertDialog.show();
Intent myIntent = new Intent(ctx, Display.class);
ctx.startActivity(myIntent);
}
}
}

how to verify login input with database php MySQL

please help
i'm doing a loging activity for my android application, i checked the email and password with my database using this code
<?php
try
{
// On se connecte à MySQL
$bdd = new PDO('mysql:host=localhost;dbname=application;charset=utf8', 'root', '');
}
catch(Exception $e)
{
// En cas d'erreur, on affiche un message et on arrête tout
die('Erreur : '.$e->getMessage());
echo 'base de donnee n est pas connecte';
}
//Getting values
$username = $_POST['editusername'];
$password = $_POST['editpassword'];
//contact surgat
// On affiche chaque entrée une à une
$reponse = $bdd->query("SELECT * FROM personne WHERE Email='$username' AND Motpass='$password'");
while ($donnees = $reponse->fetch())
{
//if we got some result
if(isset($donnees)){
//displaying success
echo "success";
}else{
//displaying failure
echo "failure";
}
$reponse->closeCursor();
}
?>
and i'm working with android studio this is the loginactivity.java that i used in it AsyncTask to get the result
package com.example.yh.log;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class MainActivity extends Activity {
private EditText TextUserName;
private EditText TextPassword;
public static final String USER_NAME = "USERNAME";
String username;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onLoginClick(View view){
TextUserName = (EditText) findViewById(R.id.editusername);
TextPassword = (EditText) findViewById(R.id.editpassword);
username=TextUserName.getText().toString();
password=TextPassword.getText().toString();
if(username.isEmpty())
Toast.makeText(getBaseContext(),"Entrez votre username",Toast.LENGTH_SHORT).show();
else if(password.isEmpty())
Toast.makeText(getBaseContext(),"Entrez votre mot de passe",Toast.LENGTH_SHORT).show();
else {
String urlString = "http://192.168.173.1/Search/login.php";
LoginTask loginTask = new LoginTask();
loginTask.execute(urlString);
}
}
private class LoginTask extends AsyncTask<String,Void,String>
{
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(MainActivity.this, "Please wait", "Loading...");
}
#Override
protected String doInBackground(String... params) {
HttpURLConnection c=null;
try {
String urlString=params[0];
URL url=new URL(urlString);
c=(HttpURLConnection)url.openConnection();
c.setRequestMethod("POST");
c.setConnectTimeout(15000 /* milliseconds */);
c.setDoInput(true);
c.setDoOutput(true);
c.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
String s = "username="+username+"&password=" + password;
c.setFixedLengthStreamingMode(s.getBytes().length);
PrintWriter out = new PrintWriter(c.getOutputStream());
out.print(s);
out.close();
c.connect();
int mStatusCode = c.getResponseCode();
String result="";
switch (mStatusCode) {
case 200:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
br.close();
result = sb.toString();
}
return result;
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
return "Error connecting to server";
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
}
#Override
protected void onPostExecute(String s) {
//super.onPostExecute(s);
String ss = s;
loadingDialog.dismiss();
if(ss=="success") {
Intent intent = new Intent(MainActivity.this, UserProfile.class);
intent.putExtra(USER_NAME, username);
finish();
startActivity(intent);
}else{
Toast.makeText(getApplicationContext(), "invalide username or password", Toast.LENGTH_LONG).show();
}}
}
}
i keep geting this error in php code "indefined index editusername" when i run the activity and hit the button althought i declared the edit text with same ID in loginactivity.xml i have changed it many times but still not working
  <EditText android:id="#+id/editusername"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
thank you.
The problem is that this in the Java:
String s = "username="+username+"&password=" + password;
Doesn't match up with this in the PHP:
//Getting values
$username = $_POST['editusername'];
$password = $_POST['editpassword'];
Also note that you should use URLEncoder.encode() for values that come from user input:
String charset = "UTF-8";
String s = "editusername=" +
URLEncoder.encode(username, charset) +
"&editpassword=" +
URLEncoder.encode(password, charset);
Also, you can't use == with Strings in Java, you need to use the equals() method:
#Override
protected void onPostExecute(String s) {
//super.onPostExecute(s);
String ss = s;
loadingDialog.dismiss();
//use equals() instead:
if(ss.equals("success")) {
Intent intent = new Intent(MainActivity.this, UserProfile.class);
intent.putExtra(USER_NAME, username);
finish();
startActivity(intent);
}else{
Toast.makeText(getApplicationContext(), "invalide username or password", Toast.LENGTH_LONG).show();
}}
}

Categories