when I run this code there's no new data in my database. I've already checked my connection and tried it using postman app its working the data entered the database. But when i tried to send data from my xml file to phpmyadmin. there's no new data tht I send in it.
when I checked my userRegister.php there's nothing wrong with it.
but still when I try submit the form there's no data in my database.
and the toast msg appear without any msg just a blank black toast msg.
private EditText editTextUsername, editTextEmail, editTextPassword;
private Button buttonRegister;
private ProgressDialog progressDialog;
private TextView textViewLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextUsername = (EditText) findViewById(R.id.editTextUsername);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
textViewLogin = (TextView) findViewById(R.id.textViewLogin);
buttonRegister = (Button) findViewById(R.id.buttonRegister);
progressDialog = new ProgressDialog(this);
buttonRegister.setOnClickListener(this);
}
private void registerUser() {
final String email = editTextEmail.getText().toString().trim();
final String username = editTextUsername.getText().toString().trim();
final String password = editTextPassword.getText().toString().trim();
progressDialog.setMessage("Registering user...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST,
Constants.URL_REGISTER,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
makeText(getApplicationContext(), jsonObject.getString("message"), Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.hide();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("username", username);
params.put("email", email);
params.put("password", password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
#Override
public void onClick(View view) {
if (view == buttonRegister)
registerUser();
}
registerUser.php
require_once'../includes/DbOperations.php';
$response = array();
if ($_SERVER['REQUEST_METHOD']=='POST'){
//check user give all the info required
if(
isset($_POST['username'])and
isset($_POST['email']) and
isset($_POST['password']))
{
//operate the data further
//create db operation object
$db = new DbOperations();
//call method
if($db-> createUser(
$_POST['username'],
$_POST['password'],
$_POST['email']
)){
$response['error'] = false;
$response['message'] = "User registered successfully";
}else{
$response['error'] = true;
$response['message'] = "Some error occured please try again";
}
}else{
$response['error']= true;
$response['message']= "Required fields are missing";
}
}else{
$response['error'] = true;
$response['message'] = "Invalid Request";
}
//display error in json format
echo json_encode($response);
Related
I am trying to access data sent from stringRequest here:
public class ProductDetailActivity extends AppCompatActivity {
String cart_url = "http://192.168.1.15/AndroidAppDatabaseConnection/add_to_cart.php";
String favorites_url = "http://192.168.1.15/AndroidAppDatabaseConnection/add_to_favorites.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_detail);
Intent intent = getIntent();
String imageUrl = intent.getStringExtra(EXTRA_URL);
String email = intent.getStringExtra("user");
final int product_id = intent.getIntExtra(EXTRA_ID, 0);
String name = intent.getStringExtra(EXTRA_NAME);
Double price = intent.getDoubleExtra(EXTRA_PRICE, 0);
String description = intent.getStringExtra(EXTRA_DESCRIPTION);
ImageView imageView = findViewById(R.id.image_view);
TextView textViewName = findViewById(R.id.text_view_name);
TextView textViewPrice = findViewById(R.id.text_view_price);
TextView textViewDescription = findViewById(R.id.text_view_description);
Button add_cart = findViewById(R.id.add_cart);
Button add_favorites = findViewById(R.id.add_wishlist);
add_cart.setTag(email);
textViewName.setText(name);
textViewPrice.setText(price + "€");
textViewDescription.setText(description);
add_cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = view.getTag().toString();
add_to_cart(email, product_id);
}
});
add_favorites.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
add_to_favorites();
}
});
}
private void add_to_cart(final String e, final int id) {
JSONObject jsonBody = new JSONObject();
try {
jsonBody.put("user", e);
jsonBody.put("product", id);
final String requestBody = jsonBody.toString();
} catch (JSONException ex) {
ex.printStackTrace();
}
StringRequest stringRequest = new StringRequest(Request.Method.POST, cart_url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
Toast.makeText(ProductDetailActivity.this,"successfully Add Into Cart",Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ProductDetailActivity.this, "Could not add item into cart", Toast.LENGTH_SHORT).show();
}
}){
#Override
public Map<String, String> getParams() {
HashMap<String, String> params = new HashMap<String, String>();
params.put("user", e);
params.put("product", String.valueOf(id));
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void add_to_favorites() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, favorites_url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(ProductDetailActivity.this, "Successfully added into Favorites", Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ProductDetailActivity.this, "Could not add item into favorites", Toast.LENGTH_SHORT).show();
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
And here I try to access the data in my PHP file:
<?php
include_once "database_connect.php";
$email = $_POST["user"];
$product_id = $_POST["product"];
$sql = "SELECT * FROM users WHERE email = '$email';";
$result= mysqli_query($conn,$sql);
$row = mysqli_fetch_assoc($result);
$user_id = $row['user_id'];
$count=mysqli_num_rows($result);
if($count>0){ /*if product is already in cart */
echo "Product already in cart";
}
else {
$add_to_cart="INSERT INTO cart (user_id,product_id,quantity) VALUES ('$user_id','$product_id','1')";
if(!mysqli_query($conn,$add_to_cart))
{
echo "Can't add product to cart";
}
else
{
echo "Product successfully added to cart";
}
}
What happens is that the query is successfully run but inserts 0 both on user_id and product_id positions.
What Am I doing wrong?
Thank you in advance!
Beware of SQL injection! Use prepared statements to protect your database.
To check if a product is already in the cart for a particular user you could change your first sql query to something like this (written as a prepared statement):
$conn = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn->prepare("SELECT c.quantity FROM cart c
JOIN users u ON u.user_id = c.user_id
WHERE c.product_id = ? AND u.email = ?");
$stmt->bind_param("is", $product_id, $email);
// 'i' means integer and 's' means string
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows > 0) {
// product exists in cart
}
$stmt->close();
I developed a system that requires the user to login. I am using Android Studio (JAVA) to code the apps and PHP to connect from apps to a MySQL database. Before the error happened, I used MySQLi method and it worked. But when I converted it to PDO, I got some error. When I see the logcat at android studio, the error states:
1) Value br of type java.lang.String cannot be converted to JSONObject
Below is my code:
MainActivity.JAVA
public class MainActivity extends AppCompatActivity {
EditText etBadgeid, etPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etBadgeid = findViewById(R.id.etBadgeid);
etPassword = findViewById(R.id.etPassword);
findViewById(R.id.btnLogin).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
userLogin();
}
});
}
private void userLogin() {
final String badgeid = etBadgeid.getText().toString();
final String pwd = etPassword.getText().toString();
class UserLogin extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
//converting response to json object
JSONObject obj = new JSONObject(s);
//if no error in response
if (!obj.getBoolean("error")) {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
//getting the user from the response
JSONObject userJson = obj.getJSONObject("user");
//creating a new user object
User user = new User(
userJson.getString("badgeid"),
userJson.getString("email"),
userJson.getString("fullname"),
userJson.getInt("roles_id"),
userJson.getInt("team_id")
);
//storing the user in shared preferences
SharedPrefManager.getInstance(getApplicationContext()).userLogin(user);
//starting the profile activity
finish();
startActivity(new Intent(getApplicationContext(), Home.class));
} else {
Toast.makeText(getApplicationContext(), "Invalid username or password", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(Void... voids) {
//creating request handler object
RequestHandler requestHandler = new RequestHandler();
//creating request parameters
HashMap<String, String> params = new HashMap<>();
params.put("badgeid", badgeid);
params.put("pwd", pwd);
//returing the response
return requestHandler.sendPostRequest(URLs.URL_LOGIN, params);
}
}
UserLogin ul = new UserLogin();
ul.execute();
}
#Override
public void onBackPressed() {
finish();
System.exit(0);
}
}
login.php
<?php
require_once 'configPDO.php';
$response = array();
if(isTheseParametersAvailable(array('badgeid', 'pwd'))){
$badgeid = $_POST['badgeid'];
$pwd = $_POST['pwd'];
$stmt = $conn->prepare("SELECT badgeid, email, fullname, roles_id, team_id FROM users WHERE badgeid = :badgeid AND pwd = :pwd AND roles_id = 3");
// $stmt->bind_param("ss",$badgeid, $pwd);
$stmt->bindParam(':badgeid',$badgeid,PDO::PARAM_STR);
$stmt->bindParam(':pwd',$pwd,PDO::PARAM_STR);
$stmt->execute();
//$stmt->store_result();
$result = $stmt->fetch(\PDO::FETCH_ASSOC); // Get results as array
if ($result) {
// Since we only get the fields we want to send back, you can assign `$result` directly to `$response['user']`
$response['user'] = $result;
$response['error'] = false;
$response['message'] = 'Login successfull';
$response['user'] = $user;
}else{
$response['error'] = false;
$response['message'] = 'Invalid username or password';
}
}
echo json_encode($response);
function isTheseParametersAvailable($params){
foreach($params as $param){
if(!isset($_POST[$param])){
return false;
}
}
return true;
}
?>
Does anyone know what is the problem?
I try to connect Login and Registration form through PHP API, But I get the error and I don't understand how its will be resolve. I check the solution regarding this error but I don't understand it. Thank you in advance!
Error :-
W/System.err: org.json.JSONException: Value null of type org.json.JSONObject$1 cannot be converted to JSONObject
Here is my code for Registration form (Login.java)
Login. java (This is the java file where for Registration)
public class Login extends Activity {
EditText editname, editemail, editpassword, editmobile;
Button btnRegister;
private static final String TAG = "Login";
private static final String URL_FOR_REGISTRATION = "http://codexpertise.com/codexpertise.com/apitest/signup.php";
ProgressDialog progressDialog;
ImageButton btnfb;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
// Progress dialog
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
editname = (EditText) findViewById(R.id.editname);
editemail = (EditText) findViewById(R.id.editemail);
editpassword = (EditText) findViewById(R.id.editpassword);
editmobile = (EditText) findViewById(R.id.editmobile);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnfb = (ImageButton)findViewById(R.id.btnfb);
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
submitForm();
}
private void submitForm() {
registerUser(editname.getText().toString(),
editemail.getText().toString(),
editpassword.getText().toString(),
editmobile.getText().toString());
}
private void registerUser(final String name, final String email, final String password,
final String mobile) {
// Tag used to cancel the request
String cancel_req_tag = "register";
progressDialog.setMessage("Adding you ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
URL_FOR_REGISTRATION, 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 user = jObj.getJSONObject("user").getString("name");
Toast.makeText(getApplicationContext(), "Hi " + user +", You are successfully Added!", Toast.LENGTH_SHORT).show();
// Launch login activity
Intent intent = new Intent(
Login.this,
MainActivity.class);
startActivity(intent);
finish();
} else {
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).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_LONG).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);
params.put("gender", mobile);
return params;
}
};
// Adding request to request queue
AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq, cancel_req_tag);
}
private void showDialog() {
if (!progressDialog.isShowing())
progressDialog.show();
}
private void hideDialog() {
if (progressDialog.isShowing())
progressDialog.dismiss();
}
});
btnfb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Uri uri = Uri.parse("https://www.facebook.com/"); // missing 'http://' will cause crashed
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
}
}
Here is the some image which i test it on postman
[1
Check this
[2
Try this
your response not any boolean error = jObj.getBoolean("error"); so you can read your response code and change your condition as your requirement..
try
{
JSONObject jObj = new JSONObject(response);
String respCode = jObj.getString("resp_code");
//boolean error = jObj.getBoolean("error");
if (respCode.equals("200")) {
String user = jObj.getJSONObject("user").getString("name");
Toast.makeText(getApplicationContext(), "Hi " + user +", You are successfully Added!", Toast.LENGTH_SHORT).show();
// Launch login activity
Intent intent = new Intent(
Login.this,
MainActivity.class);
startActivity(intent);
finish();
} else {
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
I'm currently found a problem in my android registration process, the validation seems not working fine. What i mean is that, when there is a blank field, and click register, it straight registered on my database with blank field. I'm not sure what causes it, i hope someone can help me. Below is my android java + php code
Register.java
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 etPassword2 = (EditText) findViewById(R.id.etPassword2);
final Button bNext = (Button) findViewById(R.id.bNext);
final Button bBLogin = (Button) findViewById(R.id.bBLogin);
bNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String Username = etUsername.getText().toString().trim();
final String Acc_Pass = etPassword.getText().toString().trim();
final String Acc_Pass2 = etPassword2.getText().toString().trim();
Response.Listener<String> responeListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonRespone = new JSONObject(response);
boolean success = jsonRespone.getBoolean("success");
if (TextUtils.isEmpty(Username) || Username.length() < 6){
if (TextUtils.isEmpty(Username))
{
etUsername.setError("You are required to enter a username");
}
else if (Username.length() < 6)
{
etUsername.setError("Your username is too short, minimum character is 6. Please re-enter");
}
return;
} if (TextUtils.isEmpty(Acc_Pass) || Acc_Pass.length() < 6){
if (TextUtils.isEmpty(Acc_Pass))
{
etPassword.setError("Your password is empty. Please try again");
}
else if (Acc_Pass.length() < 6)
{
etPassword.setError("Your password is too short, minimum character is 6. Please re-enter");
}
return;
} if (TextUtils.isEmpty(Acc_Pass2) || !Acc_Pass2.equals(Acc_Pass)){
if (TextUtils.isEmpty(Acc_Pass2))
{
etPassword2.setError("Your password is empty. Please try again");
}
else if (!Acc_Pass2.equals(Acc_Pass))
{
etPassword2.setError("Password mismatch. Please try again");
}
return;
} else if (!success){
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
builder.setMessage("Register Failed Username Unavailable")
.setNegativeButton("Retry", null)
.create()
.show();
return;
} else {
Intent intent = new Intent(RegisterActivity.this, RegisterActivity2.class);
RegisterActivity.this.startActivity(intent);
return;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(Username, Acc_Pass, Acc_Pass2, responeListener);
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
queue.add(registerRequest);
}
});
bBLogin.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
RegisterActivity.this.startActivity(intent);
}
});
}
}
RegisterRequest.java
public class RegisterRequest extends StringRequest {
private static final String REGISTER_REQUEST_URL = "http://192.168.1.2/AppRegister.php";
private Map<String, String> params;
public RegisterRequest(String Username, String Acc_Pass, String Acc_Pass2, Response.Listener<String> listener){
super (Method.POST, REGISTER_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("Username", Username);
params.put("Acc_Pass", Acc_Pass);
params.put("Acc_Pass2", Acc_Pass2);
}
#Override
public Map<String, String> getParams() {
return params;
}
}
AppRegister.php
<?php
$connect = mysqli_connect("localhost", "root", "", "registering");
$Username = $_POST["Username"];
$Acc_Pass = $_POST["Acc_Pass"];
$Acc_Pass2 = $_POST["Acc_Pass2"];
function registerUser() {
global $connect, $Username, $Acc_Pass, $Acc_Pass2;
$statement = mysqli_prepare($connect, "INSERT INTO account_details (Username, Acc_Pass, Acc_Pass2) VALUES (?, ?, ?)");
mysqli_stmt_bind_param($statement, "sss", $Username, $Acc_Pass, $Acc_Pass2);
mysqli_stmt_execute($statement);
mysqli_stmt_close($statement);
}
function usernameAvailable() {
global $connect, $Username;
$statement = mysqli_prepare($connect, "SELECT * FROM account_details WHERE Username = ?");
mysqli_stmt_bind_param($statement, "s", $Username);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
$count = mysqli_stmt_num_rows($statement);
mysqli_stmt_close($statement);
if ($count < 1){
return true;
}else {
return false;
}
}
$response = array();
$response["success"] = false;
if (usernameAvailable()){
registerUser();
$response["success"] = true;
}
echo json_encode($response);
mysqli_close($con);
?>
Updated Register.java
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 etPassword2 = (EditText) findViewById(R.id.etPassword2);
final Button bNext = (Button) findViewById(R.id.bNext);
final Button bBLogin = (Button) findViewById(R.id.bBLogin);
bNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String Username = etUsername.getText().toString().trim();
final String Acc_Pass = etPassword.getText().toString().trim();
final String Acc_Pass2 = etPassword2.getText().toString().trim();
if (etUsername.getText().toString().matches("") || etPassword.getText().toString().matches("") || etPassword2.getText().toString().matches("")) {
if (TextUtils.isEmpty(Username) || Username.length() < 6) {
if (TextUtils.isEmpty(Username))
{
etUsername.setError("You are required to enter a username");
}
else if (Username.length() < 6)
{
etUsername.setError("Your username is too short, minimum character is 6. Please re-enter");
}
} if (TextUtils.isEmpty(Acc_Pass) || Acc_Pass.length() < 6) {
if (TextUtils.isEmpty(Acc_Pass))
{
etPassword.setError("Your password is empty. Please try again");
}
else if (Acc_Pass.length() < 6)
{
etPassword.setError("Your password is too short, minimum character is 6. Please re-enter");
}
} if (TextUtils.isEmpty(Acc_Pass2) || !Acc_Pass2.equals(Acc_Pass)) {
if (TextUtils.isEmpty(Acc_Pass2))
{
etPassword2.setError("Your password is empty. Please try again");
}
else if (!Acc_Pass2.equals(Acc_Pass))
{
etPassword2.setError("Password mismatch. Please try again");
}
}
} else {
Response.Listener<String> responeListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonRespone = new JSONObject(response);
boolean success = jsonRespone.getBoolean("success");
Intent intent = new Intent(RegisterActivity.this, RegisterActivity2.class);
RegisterActivity.this.startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(Username, Acc_Pass, Acc_Pass2, responeListener);
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
queue.add(registerRequest);
}
}
});
bBLogin.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
RegisterActivity.this.startActivity(intent);
}
});
}
}
Simply check edittext is empty or not by using following code;
if( etUsername.getText().toString().matches("") || etPassword.getText().toString().matches("") || etPassword2.getText().toString().matches("") )
{
Toast.makeText(getApplicationContext(),"Please enter all fields....",Toast.LENGTH_SHORT).show();
}
else if( ! etPassword.getText().toString().matches(etPassword2.getText().toString()))
{
Toast.makeText(getApplicationContext(),"Please enter same both password fields....",Toast.LENGTH_SHORT).show();
}
else
{
Response.Listener<String> responeListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonRespone = new JSONObject(response);
boolean success = jsonRespone.getBoolean("success");
Intent intent = new Intent(RegisterActivity.this, RegisterActivity2.class);
RegisterActivity.this.startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(Username, Acc_Pass, Acc_Pass2, responeListener);
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
queue.add(registerRequest);
}
}
Try to follow this snippet
On Button Click Event
if(et_Username.isEmpty() || etUsername.length() == 0 || etUsername.equals("") || etUsername == null){
Toast.makeText(SignUpActivity.this, "Field is empty",Toast.LENGTH_SHORT).show();}
else
{
SignUp();
}
Create SignUp method
public void SignUp() {
final String Username = etUsername.getText().toString().trim();
final String Acc_pass = etPassword.getText().toString().trim();
final String Acc_pass2 = etPassword2.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("RESPONSE", response);
JSONObject jObj = null;
try {
jObj = new JSONObject(response);
String success = jObj.getString("success");
String errorMessage = jObj.getString("message");
} else {
Toast.makeText(SignUpActivity.this, errorMessage, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
// Toast.makeText(SignUpActivity.this, response, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(SignUpActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("Username", Username);
params.put("password", Acc_pass);
params.put("password2", Acc_pass2);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
I have crated login application which is a part of my native application building process.There are few end points which uses login session.I am getting successful result for login endpoint but It was not forwarding its session to next activity.For example: If user is loggedIn successful he can access rest of features in further activities. But while I'm trying to switch activity I am getting "User Needs to login".
MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
jsonResponse = new LoginPOJO();
// UserLogin Field
etUserName = (EditText) findViewById(R.id.etUserName);
// UserLogin Password
etPassword = (EditText) findViewById(R.id.etPassword);
// Login Button Image
btnLogin = (ImageView) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(this);
// User SignUp Button Image
ImageView btnSignUp = (ImageView) findViewById(R.id.btnSignUp);
btnSignUp.setOnClickListener(this);
// Forget Password Textbutton
TextView frgtPassword = (TextView) findViewById(R.id.forgetpassword);
frgtPassword.setOnClickListener(this);
// Skip for now button
final TextView skipfornow = (TextView) findViewById(R.id.skipnow);
skipfornow.setOnClickListener(this);
}
private void logIn(final String username, final String password) {
final ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setMessage("Logging you in...");
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.show();
String UPLOAD_URL = "http://xxxxx-dev.elasticbeanstalk.com/api/v1/login";
final StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
//Dismissing the progress dialog
progressDialog.dismiss();
// Getting the final Json Object
JSONObject parentObject;
try {
parentObject = new JSONObject(s);
LoginPOJO.setCode(parentObject.getString("code"));
// Getting the data from Data Json Object
JSONObject dataObject = parentObject.getJSONObject("data");
// Getting data from Geo object
JSONObject geoObject = dataObject.getJSONObject("geo");
// Getting data from businesses Array
JSONArray businessesArray = dataObject.getJSONArray("businesses");
// Getting data from Meta Object
JSONObject metaObject = parentObject.getJSONObject("meta");
startActivity(new Intent(MainActivity.this, PromotionsFeedActivity.class));
} catch (JSONException e) {
e.printStackTrace();
}
//Showing toast message of the response
Log.i("TAG", "onResponse: " + s);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
//Dismissing the progress dialog
progressDialog.dismiss();
//Showing snackbar
Toast.makeText(MainActivity.this, "Connection Problem", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Converting Bitmap to String
//Creating parameters
Map<String, String> params = new Hashtable<>();
params.put("apikey", Utilities.API_KEY);
params.put("secret", Utilities.SECRET_KEY);
params.put("email", username);
params.put("password",password);
//Adding parameters
//returning parameters
return params;
}
};
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
feed.java
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_promotions_feed);
jsonResponse = new LoginPOJO();
communityImage = (TextView) findViewById(R.id.communityImage);
communityImage.setOnClickListener((View.OnClickListener) this);
searchImage = (TextView) findViewById(R.id.searchImage);
searchImage.setOnClickListener((View.OnClickListener) this);
specialsImage = (TextView) findViewById(R.id.searchImage);
specialsImage.setOnClickListener(this);
calenderImage = (TextView) findViewById(R.id.calenderImage);
calenderImage.setOnClickListener(this);
profileImage = (TextView) findViewById(R.id.profileImage);
profileImage.setOnClickListener(this);
TextView response = (TextView) findViewById(R.id.response);
String data = LoginPOJO.getCode();
response.setText(data);
}
private void getPromotionsFeed(final String location) {
final ProgressDialog progressDialog = new ProgressDialog(PromotionsFeedActivity.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setMessage("Getting promotions feed...");
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.show();
String UPLOAD_URL = "http://xxxx-dev.elasticbeanstalk.com/api/v1/get_promotions_feed";
final StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
//Dismissing the progress dialog
progressDialog.dismiss();
// Getting the final Json Object
JSONObject parentObject;
try {
parentObject = new JSONObject(s);
} catch (JSONException e) {
e.printStackTrace();
}
//Showing toast message of the response
Log.i("TAG", "onResponse: " + s);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
//Dismissing the progress dialog
progressDialog.dismiss();
//Showing snackbar
Toast.makeText(PromotionsFeedActivity.this, "Connection Problem", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Converting Bitmap to String
//Creating parameters
Map<String, String> params = new Hashtable<>();
params.put("apikey", Utilities.API_KEY);
params.put("secret", Utilities.SECRET_KEY);
params.put("location","xxx");
//Adding parameters
//returning parameters
return params;
}
};
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
LogCat
04-03 18:47:26.263 10750-10750/com.example.reception.farbinder_test I/TAG: onResponse: {"code":200,"status":"ok","message":"Logged in.","data":{"id":"Pg4yYHXIQK","firstName":"Arun","lastName":"","shortName":"Arun","email":"arun#farbinder.com","role":"owner","showInviteMessage":false,"verified":true,"zipCode":"07666","location":"Teaneck, NJ","geo":{"latitude":40.888461,"longitude":-74.012066,"zipcode":"07666","city":"Teaneck","state":"NJ","type":"geo"},"defaultCommunity":{"id":18313,"name":"Teaneck, NJ Community","city":"Teaneck","state":"NJ","latitude":40.888461,"longitude":-74.012066,"type":"community"},"businesses":[{"id":72,"name":"my bus","type":"business"}],"type":"user"},"meta":{"userVideoUrl":"https://d1e6yi6s3cx2ur.cloudfront.net/videos/0/_20160316_ios-user.m4v","businessVideoUrl":"https://d1e6yi6s3cx2ur.cloudfront.net/videos/0/_20160316_ios-business.m4v","promoVideoUrl":"https://d1e6yi6s3cx2ur.cloudfront.net/videos/0/_20160316_ios-user.m4v","searchVideoUrl":"https://d1e6yi6s3cx2ur.cloudfront.net/videos/0/_20160316_ios-user.m4v","faqUrl":"http://farbinder-dev.elasticbeanstalk.com/api/v1/faq","privacyUrl":"http://farbinder-dev.elasticbeanstalk.com/api/v1/privacy","termsUrl":"http://farbinder-dev.elasticbeanstalk.com/api/v1/terms","contactFormUrl":"http://farbinder-dev.elasticbeanstalk.com/api/v1/contact?u\u003d25fee27e9d18464eadbad0faa632a9b6e82787cc613ca64e","feedbackFormUrl":"http://farbinder-dev.elasticbeanstalk.com/api/v1/feedback?u\u003d25fee27e9d18464eadbad0faa632a9b6e82787cc613ca64e","type":"links"}}
04-03 18:47:26.265 1518-1877/system_process W/InputMethodManagerService: Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy#2ddf4f6b attribute=null, token = android.os.BinderProxy#330c1b98
04-03 18:47:26.326 1518-1660/system_process V/WindowManager: Adding window Window{11f00761 u0 com.example.reception.farbinder_test/com.example.reception.farbinder_test.PromotionsFeedActivity} at 4 of 10 (after Window{27eec5b0 u0 com.example.reception.farbinder_test/com.example.reception.farbinder_test.MainActivity EXITING})
04-03 18:47:26.330 1518-1880/system_process V/WindowManager: Adding window Window{1217747 u0 com.example.reception.farbinder_test/com.example.reception.farbinder_test.PromotionsFeedActivity} at 4 of 11 (before Window{11f00761 u0 com.example.reception.farbinder_test/com.example.reception.farbinder_test.PromotionsFeedActivity})
04-03 18:47:26.441 10750-10750/com.example.reception.farbinder_test E/RecyclerView: No adapter attached; skipping layout
04-03 18:47:26.457 1162-1162/? W/SurfaceFlinger: couldn't log to binary event log: overflow.
04-03 18:47:27.092 10750-10750/com.example.reception.farbinder_test I/TAG: onResponse: {"code":401,"status":"error","message":"User not logged in."}
You do your login in a service, and then have the service broadcast the successful login to any interested classes.