How to stop the process if name exists in the database android - android

I have one page by this page new user can register in my app to his can use my app.
I have two fields in this page one for phone number and second for his password.
Also I have one button if his press this button his will move to another page.
What I try to do I need in this page if user click this button to continue to another page before move I try to check if this phone number or his ID of device in my db already. So if his phone number or ID devices already exists in my db. user will show message like "phone number already available" and stop continue to another page or stop this process. In this case button of continue will be not work. That what I try to do.
Now the code in button like that:
findViewById(R.id.buttonContinue).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code = CountryData.countryAreaCodes[spinner.getSelectedItemPosition()];
if (number.isEmpty() || number.length() < 6) {
editText.setError("Valid number is required");
editText.requestFocus();
return;
}
String phoneNumber = "+" + code + number;
String UserCountry = spinner.getSelectedItem().toString();
Intent intent = new Intent(RegistrationPage.this, VerifyPhoneActivity.class);
intent.putExtra("phonenumber",phoneNumber);
intent.putExtra("phone", "+"+code+ phone);
startActivity(intent);
}
});
how I try to do it like that. I make one connection by volley and php file to see if this phone number available in db or no.
private void Regist(){
String URL_REGIST = "https://xxxxxxxxxxxxx/registers.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_REGIST,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String Response = jsonObject.getString("response");
Toast.makeText(RegistrationPage.this,"Test"+ Response, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(RegistrationPage.this,"This device already exists", Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(RegistrationPage.this, "Register Error! " + error.toString(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("deviceID",deviceID);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
And add this method in button before intent:
findViewById(R.id.buttonContinue).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Regist();//================here like that
String code = CountryData.countryAreaCodes[spinner.getSelectedItemPosition()];
if (number.isEmpty() || number.length() < 6) {
editText.setError("Valid number is required");
editText.requestFocus();
return;
}
String phoneNumber = "+" + code + number;
String UserCountry = spinner.getSelectedItem().toString();
Intent intent = new Intent(RegistrationPage.this, VerifyPhoneActivity.class);
intent.putExtra("phonenumber",phoneNumber);
intent.putExtra("phone", "+"+code+ phone);
startActivity(intent);
}
});
Now like that my code is working I can see message of "This device already exists". But still the user move to another page so how I can make it stop if this message come?
PHP CODE
<?php
include 'connt.php';
$deviceID = $_POST['deviceID'];
$CheckSQL = "SELECT * FROM user WHERE deviceID='$deviceID'";
$check = mysqli_fetch_array(mysqli_query($con,$CheckSQL));
if(isset($check)){
echo 'phone Already Exist';
}
mysqli_close($con);
?>

The problem is after you've checked, you still have the code to proceed no matter what, so create a new method called continue then put the continue code inside like:
String code = CountryData.countryAreaCodes[spinner.getSelectedItemPosition()];
if (number.isEmpty() || number.length() < 6) {
editText.setError("Valid number is required");
editText.requestFocus();
return;
}
String phoneNumber = "+" + code + number;
String UserCountry =
spinner.getSelectedItem().toString();
Intent intent = new Intent(RegistrationPage.this,
VerifyPhoneActivity.class);
intent.putExtra("phonenumber",phoneNumber);
intent.putExtra("phone", "+"+code+ phone);
startActivity(intent);
delete it from the button onClicklistener. Then in the Regist(); inside the try function put the new continue method after the toast. It should work

Related

Login using Json with shared Preferences

Login using JSON with shared Preferences When user Enter their Phone Number then user got success from API and go to new activity and after resume app, users state will log in
When user Enter their Phone Number then user got success from API and go to new activity and after resume app, users state will log in
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView3);
usr_number = findViewById(R.id.usr_pass);
go = findViewById(R.id.button);
signup = findViewById(R.id.signup_signup);
go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getjsondata();
String hhh = usr_number.getText().toString();
url = "http://readnow.flatdeal4u.com/Api/Register.aspx?mobile=" + hhh + "&choice=2";
//Toast.makeText(MainActivity.this, ""+hhh, Toast.LENGTH_SHORT).show();
if (usr_number.getText().toString().isEmpty()) {
usr_number.setError("Enter Phone Number");
Toast.makeText(MainActivity.this, "Enter Details", Toast.LENGTH_SHORT).show();
} else {
if (usr_number.getText().toString().equals("" + hhh)) {
Intent intent = new Intent(MainActivity.this, select_your_exams.class);
startActivity(intent);
pref = PreferenceManager
.getDefaultSharedPreferences(MainActivity.this);
pref.getString("mobilenumber", hhh);
pref.getString("nameofuser", "");
}
}
}
});
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Signup.class);
startActivity(intent);
}
});
}
Here are my JSON method codes:
public void get JSON data) {
final StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener < String > () {
#Override
public void onResponse(String response) {
try {
JSONObject jobj = new JSONObject(response);
JSONArray array = jobj.getJSONArray("userInfos");
//Toast.makeText(MainActivity.this, "data found"+array, Toast.LENGTH_LONG).show();
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
final Phn_modal mo = new Phn_modal();
final String mobile = obj.getString("mobileNumber");
final String name = obj.getString("fullName");
final String email = obj.getString("emailId");
Toast.makeText(MainActivity.this, "Welcome You-" + name, Toast.LENGTH_LONG).show();
mo.setMobile(mobile);
mo.setName(name);
mo.setEmailId(email);
mo.getMobile(mobile);
mo.getMobile(name);
editor.putString("mobilenumber", mobile);
editor.putString("nameofuser", name);
editor.apply();
editor.commit();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "" + error.toString(), Toast.LENGTH_SHORT).show();
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(request);
}
i think your question is , you login first time, and next time you again visit application that time directly go to the activity withouth asking login,
then you can try this.
public void storeString(SharedPreferences sharedPreferences, String key, String value) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
above function is used to store the specific value in our shared prefrence, with given key.
Now when we hint the login button that time if login is success then store the login success value in our prefrence.
this one is usefull for again visit in your application
storeString(mPreferences, "Login_flag", "true");
-> Now, when we again visit application check the our prefrence is true or false.
if our prefrence is true then user already login, not required to login again
Check like this,
if(mPreferences.getString(PreferenceList.LOGIN_FLAG, "false").equals("true")){
//if alredy login then access this
}else{
//if not login then access this
}
if you want to create a login session in your app then you should create an preference class in your project and save data in that class and match the data where you want to use follow this answer to maintain the login session in your app:- Preventing users to login again after closing the app

Volley not working, Android

I am building an android app and I am trying to send basic info on a phpmyadmin DB. I wrote a script (working, tested it with postman) and I used volley in my andorid app to send params to script. Here is my code.
public class Info extends AppCompatActivity {
EditText e_mail, age, group_size;
Button next;
static final String insertURL = "http://www.studenti.famnit.upr.si/~89161009/IGIPAN/insertUser.php";
static final String insertGroupURL = "http://www.studenti.famnit.upr.si/~89161009/IGIPAN/insertGroupUser.php";
String id_user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.info);
next = (Button) findViewById(R.id.next);
e_mail = (EditText) findViewById(R.id.e_mail);
age = (EditText) findViewById(R.id.age);
group_size = (EditText) findViewById(R.id.group_size);
Intent intent = getIntent();
id_user = intent.getStringExtra("id");
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
insertUser();
Intent intent = new Intent(getApplicationContext(), LocationSearch.class);
startActivity(intent);
}
});
}
public void insertUser() {
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
StringRequest request = new StringRequest(Request.Method.POST, insertURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("", "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parametar = new HashMap<String, String>();
parametar.put("id_user", id_user);
parametar.put("age", String.valueOf(age.getText()));
parametar.put("email", String.valueOf(e_mail.getText()));
return parametar;
}
};
requestQueue.add(request);
}
}
The problem is that I don't get any errors. And I did a previous project that was very similar, and did it exactly like this and it worked. Now I can't figure out why it won't work.
Every answer is appreciated. Thank you!
EDIT
My script is:
<?php
if($_SERVER["REQUEST_METHOD"] == "POST"){
require 'connection.php';
insertUser();
}
function insertUser(){
global $connect;
$id_user = $_POST["id_user"];
$age = $_POST["age"];
$email = $_POST["email"];
$query = "INSERT INTO user ( id_user, age, email)
VALUES ( '$id_user', '$age', '$email');";
mysqli_query($connect, $query) or die (mysqli_error($connect));
mysqli_close($connect);
}
?>
I figured it out thanks to Nabil Mohammed Nalakath's suggestion to use log in onResponse(). Which gave me an value to long for column error.
Since I used uniqueID = UUID.randomUUID().toString(); i got an id of length 36 and in my table i only set varchar(35). So I changed that and it worked!
I think whenever you get success response then you want to open LocationSearch screen for that you need to keep this code:
Intent intent = new Intent(getApplicationContext(), LocationSearch.class);
startActivity(intent);
Inside onResponse() method and there you need to check have you got success response or not.If success then above code should be executed.
I think you should use requestQueue.enque(request);
Its important to configure AndroidMenifest.xml file
by
and
android:usesCleartextTraffic="true"

The app works on emulator but not on actual device

I just wanted help in my android app actually scene is like ,I have made an android app that stores and fetch data from mysql database,so the twist is whenever I run app on android emulator it runs fine but as soon as I try to run it on actual device there seem to be nothing is happening however the login and register buttons seem to be doing nothing they don't call the api,I am using wamp as local server and my device and laptop is on same wifi network router so I am not getting it,btw the logcat shows no error at all and it also runs perfectly on emulator
my register activity to add user into database
public class Register extends AppCompatActivity {
private static final String TAG = Register.class.getSimpleName();
ProgressDialog progressDialog;
private EditText signupInputName, signupInputEmail, signupInputPassword;
public Button btnSignUp;
public Button btnLinkLogin;
private SQLiteHandler db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
SessionManager session = new SessionManager(getApplicationContext());
db = new SQLiteHandler(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(Register.this,
Matchboard.class);
startActivity(intent);
finish();
}
signupInputName = (EditText) findViewById(R.id.name);
signupInputEmail = (EditText) findViewById(R.id.email);
signupInputPassword = (EditText) findViewById(R.id.password);
btnSignUp = (Button) findViewById(R.id.btnRegister);
btnLinkLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = signupInputName.getText().toString().trim();
String email = signupInputEmail.getText().toString().trim();
String password = signupInputPassword.getText().toString().trim();
if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty()) {
registerUser(name, email, password);
} else {
Toast.makeText(getApplicationContext(),
"Please enter your details!", Toast.LENGTH_SHORT).show();
}
}
});
btnLinkLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),Login.class);
startActivity(i);
finish();
}
});
}
private void registerUser(final String name, final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_register";
progressDialog.setMessage("Adding you ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String email = user.getString("email");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUser(name, email, uid, created_at);
Toast.makeText(getApplicationContext(), "Hi "+name+",You are successfully Added!", Toast.LENGTH_SHORT).show();
// Launch login activity
Intent intent = new Intent(
Register.this,
Login.class);
startActivity(intent);
finish();
} else {
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("name", name);
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!progressDialog.isShowing())
progressDialog.show();
}
private void hideDialog() {
if (progressDialog.isShowing())
progressDialog.dismiss();
}
}
I believe when you are on your local machine the call to made to the localhost but when the app is on your actual device there might be some IP issue.You might be accessing it wrongly.
The thing is that your actual device and the system should be on the same network.
Check your IP using ipconfig command and then retry on same network.

My Button always sends me to else even i have the right details

I have my database and my php code working and on the Android Monitor results when i put the right details it logs in successfully. But this code always sends me to the else statement which is Failed login.
#Override
public void onClick(View v) {
HashMap postData = new HashMap();
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
postData.put("username",username);
postData.put("password",password);
PostResponseAsyncTask task1 = new PostResponseAsyncTask(MainActivity.this, postData,
new AsyncResponse() {
#Override
public void processFinish(String s) {
Log.d(LOG, s);
if (s.contains("success")) {
Toast.makeText(MainActivity.this, "Successful Login!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Failed Login",Toast.LENGTH_LONG).show();
}
}
});
task1.execute("http://10.0.2.2/*******/");
}
you should replace s.contains("success") with s.contains("Success")
as #Victor Ribeiro da Silva Eloy pointed contains function is "case sensitive", and in the other hand you pointed that you see "Login Successful" in your logs that it's "Successful" has capital "S".
If you are sure enough that s is success then try to replace with :-
this
s.contains("Success")

Unable to navigate to Activity after successful login - Android volley

Issue
After successful login verification from the server, unable to open New activity. Activity stays at Login Activity
Background
What I am trying to achieve here is open "Welcome" activity after successful User login. The server correctly validates the user login and displays the Toast, but not opening the activity
Code
private static final String LOGIN_URL = "<myURL>/login.php";
public static final String KEY_LOGUSERNAME = "loUname";
public static final String KEY_LOGPASSWORD = "loPass";
EditText LogUser, LogPass;
Button btnsLogin;
String loUser, loPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
initalizevars();
btnsLogin.setOnClickListener(this);
}
public void initalizevars() {
LogUser = (EditText) findViewById(R.id.etLogUser);
LogPass = (EditText) findViewById(R.id.etLogPass);
btnsLogin = (Button) findViewById(R.id.btnLogin);
}
private void login() {
loUser = LogUser.getText().toString().trim();
loPassword = LogPass.getText().toString().trim();
StringRequest stringRequest1 = new StringRequest(Request.Method.POST, LOGIN_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(response.trim().equals("Success"))
{
Toast.makeText(Login.this,response,Toast.LENGTH_LONG).show();
openProfile();
}else
{
Toast.makeText(Login.this,response,Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Login.this,error.toString(),Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<String, String>();
map.put(KEY_LOGUSERNAME, loUser);
map.put(KEY_LOGPASSWORD, loPassword);
return map;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest1);
}
private void openProfile() {
Intent i = new Intent(this,Welcome.class);
startActivity(i);
}
#Override
public void onClick(View v) {
if (v == btnsLogin) {
login();
}
}
The Toast is being displayed from the server response on successful verification
What i tried
I tried changing the Intent to below
Intent i = new Intent(Login.this,Welcome.class);
startActivity(i);
But no luck. Am stuck and unable to figure out where and what went wrong.
Requesting your help in putting me in the right direction.
Thanks
EDIT
i modified the if condition to be more meaningful and to debug as well
if (response.trim().equals("Success")) {
Toast.makeText(Login.this, response + " Right", Toast.LENGTH_LONG).show();
openProfile();
} else {
Toast.makeText(Login.this, response + " Wrong", Toast.LENGTH_LONG).show();
openProfile();
}
As suggested by user #user1232726, the else part is being considered and the activity is opened which should not be the case.
My login.php outputs
Success
<!-- Hosting24 Analytics Code -->
<script type="text/javascript" src="http://stats.hosting24.com/count.php"></script>
<!-- End Of Analytics Code -->
Basically the issue was with the server response as it did return some javascript along with the success message. Guidance from #cricket_007, #IshitaSinha actually help me fix the issue.
Solution : Additional javascript/ or messages can be added When using free hosting sites. Check the entire response before comparing it with the actual response

Categories

Resources