Android app can't insert data into MySQL DB - java

I'm fairly new to Android coding and I'm trying to create app that inserts some info into my MySQL DB. I've found a lot of tutorials and tips on web and created lite app to try procedures. Everything compiles OK, app runs and it seems to send data successfully. But in fact, no data appears in my table.
Here's my PHP code android_add.php:
<?php
$con = mysqli_connect(localhost, user, psswd, name); //those works
mysqli_set_charset($con, "utf8"); //working with special symbols
$name = $_POST['name']; //get name & author from App
$author = $_POST['author'];
$sql = "insert into kniha_test (k_autor_pr,k_nazev) values ('$name','$address')";
if(mysqli_query($con,$sql)){
echo 'success';
} else {
echo 'failure';
}
mysqli_close($con);
?>
And here's my MainActivity.java:
import android.content.ContentValues;
import android.os.AsyncTask;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private EditText editTextName;
private EditText editTextAuthor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextName = (EditText) findViewById(R.id.editTextName);
editTextAuthor = (EditText) findViewById(R.id.editTextAuthor);
}
public void insert (View view){
String name = editTextName.getText().toString();
String author = editTextAuthor.getText().toString();
insertToDatabase(name,author);
}
protected void insertToDatabase(String name, String author){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
String name;
String author;
public void saveNameAut(String name, String author){
this.name = name;
this.author = author;
name = editTextName.getText().toString();
author = editTextAuthor.getText().toString();
}
#Override
protected String doInBackground(String... params){
String paramName = params[0];
String paramAuthor = params[1];
ContentValues values = new ContentValues();
values.put("name", this.name);
values.put("author", this.author);
String addUrl = "http://glaserproject.com/knihovna_kyber/android/android_add.php";
try {URL url = new URL(addUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
System.out.println("Response Code: " + conn.getResponseCode());
} catch (IOException e){};
return "Succes";
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
TextView textViewResult = (TextView) findViewById(R.id.textViewResult);
textViewResult.setText("inserted");
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(name, author);
}
}
As I said, I'm just beginner, so there may be something really stupid, but I can't figure out what. And there can be some trash lines from different tries. PHP code should be OK, I'm using practically the same to insert from HTML, so I'm guessing, there is problem in my Java code.
I will be really thankful for advices/responses.
Thanks!
PS: Response code I'm getting is 200.

You are sending null values through AsyncTask
Have you printed the values that you are sending through
try this
protected void insertToDatabase(String name, String author){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
String cName=name;
String cAuthor=author;
#Override
protected String doInBackground(String... params){
ContentValues values = new ContentValues();
values.put("name", cName);
values.put("author", cAuthor);
String addUrl = "http://glaserproject.com/knihovna_kyber/android/android_add.php";
try {URL url = new URL(addUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
System.out.println("Response Code: " + conn.getResponseCode());
} catch (IOException e){};
return "Succes";
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
TextView textViewResult = (TextView) findViewById(R.id.textViewResult);
textViewResult.setText("inserted");
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(name, author);
}
try again and let me know if it solves your problems....

Related

OkHttp not posting to mysql

I have a problem here ..My app is supposed to send 3 values to the database, from text box etName,etEmailand etPassword
but instead, it is not send anything ...I'm new in android and I don't know some of the things I wrote in my code as I am following some tutorials
this in my code for register
package com.xulucreatives.taxisiyaya;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class RegisterActivity extends AppCompatActivity {
EditText etName,etEmail,etPassword;
Button btnReg;
final String url_Register ="http://taxinote.000webhostapp.com/register_user.php";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
etName = findViewById(R.id.RM);
etEmail = findViewById(R.id.et_email);
etPassword = findViewById(R.id.et_password);
btnReg = findViewById(R.id.btn_reg);
btnReg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String Name = etName.getText().toString();
String Email = etEmail.getText().toString();
String Password = etPassword.getText().toString();
new RegisterUser().execute(Name,Email,Password);
// Toast.makeText(RegisterActivity.this,"Im working you bitch",Toast.LENGTH_LONG).show();
}
});
}
public class RegisterUser extends AsyncTask<String,Void,String>{
#Override
protected String doInBackground(String... strings) {
String Name = strings[0];
String Email = strings[1];
String Password = strings[2];
String finalURL = url_Register + "?user_name" + Name +
"&user_id"+ Email +
"&user_password"+ Password;
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(finalURL)
.build();
Response response = null;
try{
response = okHttpClient.newCall(request).execute();
if(response.isSuccessful())
{
String result = response.body().string();
if(result.equalsIgnoreCase("uaser registered successfully"))
{
Toast.makeText(RegisterActivity.this,"Registered Successfully",Toast.LENGTH_LONG).show();
Intent i = new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(i);
finish();
}
else if(result.equalsIgnoreCase("user already exists")){
Toast.makeText(RegisterActivity.this,"User Already Exists",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(RegisterActivity.this,"Ooops ! Ran into a problem , try again",Toast.LENGTH_LONG).show();
}
}
else{
Toast.makeText(RegisterActivity.this,"response not successful!! :/",Toast.LENGTH_LONG).show();
}
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
}
public void showToast(final String Text){
this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(RegisterActivity.this,Text,Toast.LENGTH_LONG).show();
}
});
}
}
user_name, user_id and user_password are from my php file in the server
<?php
require_once('connect.php');
$userName = $_GET['user_name'];
$userID = $_GET['user_id'];
$userPassword = $_GET['user_password'];
$query = "select * from users where email = '$userID'";
$recordExists = mysqli_fetch_array(mysqli_query($conn, $query));
if(isset($recordExists)){
echo 'User already exists';
}else{
$query = "INSERT INTO users (name, email, password) VALUES ('$userName', '$userID', '$userPassword')";
if(mysqli_query($conn, $query)){
echo 'User registered successfully';
}else{
echo 'oops! please try again!';
}
}
?>
but its not working i dont know why
You are creating an invalid url
which is
String finalURL = url_Register + "?user_name" + Name +
"&user_id"+ Email +
"&user_password"+ Password;
and should be like this
String finalURL = url_Register + "?user_name=" + Name +
"&user_id="+ Email +
"&user_password="+ Password;

my php code to connect with database for android

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 {
//...

Android studio connecting to remote database

I am trying to get an Android Studio app to connect to a remote server hosted on "hostbuddy". Here is the code (when sending data the error is "Connection goes wrong 2") making me guess there is something wrong with the DB_URL. I tried changing the url in many ways, none worked. If it would help I could also post the logcat.
EDIT : I fixed it, i forgot to add the module for the connector for MySQl, works like a charm now ^_^
package com.example.battl.qr2;
import android.content.Intent;
import android.os.AsyncTask;
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;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class Register extends AppCompatActivity {
TextView textView;
Button button;
EditText editText;
private static final String DB_URL= "jdbc:mysql://mysql6002.site4now.net/db_a37d85_mydb:3306";
private static final String USER = "X";
private static final String PASS = "X";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
textView=(TextView) findViewById(R.id.textView);
editText=(EditText) findViewById(R.id.editText);
}
public void btnConn(View view)
{
Send objsend = new Send();
objsend.execute("");
}
private class Send extends AsyncTask<String,String,String>
{
String msg = "";
String text = editText.getText().toString();
#Override
protected void onPreExecute() {textView.setText("Please Wait Inserting");}
#Override
protected String doInBackground(String... strings)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(DB_URL,USER,PASS);
if(conn == null) {
msg="Connection goes wrong";
} else {
String query = "INSERT INTO ex (col1) VALUES ('"+text+"') ";
Statement stmt = conn.createStatement();
stmt.executeUpdate(query);
msg = "Inserted successfully";
}
conn.close();
}
catch (Exception e)
{
msg="Connection goes wrong 2";
e.printStackTrace();
}
return msg;
}
#Override
protected void onPostExecute(String msg) {textView.setText(msg);}
}
}

Sending data from Android to SQL database using PHP

I was following this tutorial in which I was building login and registration app:
https://www.youtube.com/watch?v=T7Z4GVFaT4A
I've changed PHP and tested it by passing some arguments through address field, but when I'm clicking register button nothing happens.
There are some things in OnResponse function that should be doing something, something should be added to database, but nothing happens.
I was wondering if maybe anything at all is being send from app if I'm not getting any response.
Also, what's troubling me, function OnResponse is never called, but it should be.
Instead of using some ASP I create server using WAMP. Below there are Java and PHP files that are crucial to this problem.
RegisterRequest.java
package com.example.dominik.praca;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Dominik on 28.12.2016.
*/
public class RegisterRequest extends StringRequest {
//private static final String REGISTER_REQUEST_URL = "http://kulturnik.ugu.pl/Register.php";
//private static final String REGISTER_REQUEST_URL = "http://kulturnik.byethost3.com/Register2.php";
private static final String REGISTER_REQUEST_URL = "http://127.0.0.1/kulturnik/Register.php";
private Map<String, String> params;
public RegisterRequest(String name, String username, String password, Response.Listener<String> listener){
super(Method.POST, REGISTER_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("name", name);
params.put("username", username);
params.put("password", password);
}
#Override
public Map<String, String> getParams() {
return params;
}
}
RegisterActivity.java
package com.example.dominik.praca;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class RegisterActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
final EditText etUsername = (EditText) findViewById(R.id.etUsername);
final EditText etPassword = (EditText) findViewById(R.id.etPassword);
final EditText etName = (EditText) findViewById(R.id.etName);
final Button bRegister = (Button) findViewById(R.id.bRegister);
bRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String name = etName.getText().toString();
final String username = etUsername.getText().toString();
final String password = etPassword.getText().toString();
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
RegisterActivity.this.startActivity(intent);
AlertDialog.Builder builderSuccess = new AlertDialog.Builder(RegisterActivity.this);
builderSuccess.setMessage("Rejestracja zakończona powodzeniem")
.create()
.show();
}
else {
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
builder.setMessage("Błąd rejestracji")
.setNegativeButton("Ponów", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(name, username, password, responseListener);
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
queue.add(registerRequest);
}
});
}
}
And Register.php
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
$con = mysqli_connect("localhost", "root", "", "kulturnik");
$name = $_POST["name"];
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "INSERT INTO user (name, username, password) VALUES (?, ?, ?)");
mysqli_stmt_bind_param($statement, "sss", $name, $username, $password);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = true;
print_r(json_encode($response));
?>
Use Async task for faster send & retrieval to/fro server. Just create an object of the class and use execute function to pass parameters and start asynchronous sending and retrieval to/fro the server.
eg:- SendtoPhp stp = new SendtoPhp();
stp.execute(tname, phone)
public class SendtoPhp extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String tname = params[0]; //parameters you need to send to server
String phone = params[1];
String data = "";
int tmp;
try {
URL url = new URL("http://your.server.com/"); //url to php code
String urlParams = "tname=" + tname + "&tphone=" + phone;
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
OutputStream os = httpURLConnection.getOutputStream();
os.write(urlParams.getBytes());
os.flush();
os.close();
InputStream is = httpURLConnection.getInputStream();
while ((tmp = is.read()) != -1) {
data += (char) tmp;
//System.out.println(data);
}
is.close();
httpURLConnection.disconnect();
return data;
} catch (MalformedURLException e) {
e.printStackTrace();
return "Exception: " + e.getMessage();
} catch (IOException e) {
e.printStackTrace();
return "Exception: " + e.getMessage();
}
}
#Override
protected void onPostExecute(String s) {
try {
//You might receive something on server code execution using JSON object
} catch (JSONException e) {
e.printStackTrace();
}
}
}

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);
}
}
}

Categories