Just tried to run and I receive this error:
org.json.JSONException: Value ture at success of type java.lang.String cannot be converted to boolean
at org.json.JSON.typeMismatch(JSON.java:100)
at org.json.JSONObject.getBoolean(JSONObject.java:378)
I'm a beginner with Java and I can't seem to figure out why string won't convert to Boolean.
The error code comes up specifically on the "if" line and "else if" line.
The code:
public class RegisterActivity extends AppCompatActivity {
private ArrayAdapter adapter;
private Spinner spinner;
private String userID;
private String userPassword;
private String userGender;
private String userMajor;
private String userEmail;
private AlertDialog dialog;
private boolean validate = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
spinner = (Spinner) findViewById(R.id.majorSpinner);
adapter = ArrayAdapter.createFromResource(this, R.array.major, android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
final EditText idText = (EditText) findViewById(R.id.idText);
final EditText passwordText = (EditText) findViewById(R.id.passwordText);
final EditText emailText = (EditText) findViewById(R.id.emailText);
RadioGroup genderGroup = (RadioGroup) findViewById(R.id.genderGroup);
int genderGroupID = genderGroup.getCheckedRadioButtonId();
userGender = ((RadioButton) findViewById(genderGroupID)).getText().toString();
genderGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
RadioButton genderButton = (RadioButton) findViewById(i);
userGender = genderButton.getText().toString();
}
});
final Button validateButton = (Button) findViewById(R.id.validateButton);
validateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String userID = idText.getText().toString();
if(validate)
{
return;
}
if(userID.equals(""))
{
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
dialog = builder.setMessage("아이디는 빈 칸일 수 없습니다.")
.setPositiveButton("확인", null)
.create();
dialog.show();
return;
}
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)
{
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
dialog = builder.setMessage("사용할 수 있는 아이디 입니다.")
.setPositiveButton("확인", null)
.create();
dialog.show();
idText.setEnabled(false);
validate = true;
idText.setBackgroundColor(getResources(). getColor(R.color.colorGray));
validateButton.setBackgroundColor(getResources(). getColor(R.color.colorGray));
}
else{
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
dialog = builder.setMessage("사용할 수 없는 아이디 입니다.")
.setNegativeButton("확인", null)
.create();
dialog.show();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
};
ValidateRequest validateRequest = new ValidateRequest(userID, responseListener);
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
queue.add(validateRequest);
}
});
Button registerButton = (Button) findViewById(R.id.registerButton);
registerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String userID = idText.getText().toString();
String userPassword = passwordText.getText().toString();
String userMajor = spinner.getSelectedItem().toString();
String userEmail = emailText.getText().toString();
if(!validate){
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
dialog = builder.setMessage("먼저 중복 체크를 해주세요.")
.setNegativeButton("확인", null)
.create();
dialog.show();
return;
}
if(userID.equals("") || userPassword.equals("") || userMajor.equals("") || userEmail.equals("") || userGender.equals("")){
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
dialog = builder.setMessage("빈 칸 없이 입력해주세요.")
.setNegativeButton("확인", null)
.create();
dialog.show();
return;
}
Response.Listener<String> responseListener = new Response.Listener<String>(){ #########Error here
#Override
public void onResponse(String response){ #########Error here
try
{
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if(success)
{
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
dialog = builder.setMessage("회원 등록이 성공했습니다.")
.setPositiveButton("확인", null)
.create();
dialog.show();
finish();
}
else {
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
dialog = builder.setMessage("회원 등록에 실패했습니다.")
.setNegativeButton("확인", null)
.create();
dialog.show();
}
}
catch (JSONException e)
{
e.printStackTrace();
// Toast.makeText(getApplicationContext(), "error",
// Toast.LENGTH_SHORT).show();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(userID, userPassword, userGender, userMajor, userEmail, responseListener);
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
queue.add(registerRequest);
}
});
}
#Override
protected void onStop(){
super.onStop();
if(dialog !=null)
{
dialog.dismiss();
dialog = null;
}
}
}
With this:
boolean success = jsonResponse.getBoolean("success");
you are trying to get a boolean value, but the value returned can not be converted to boolean, it's a string.
From your error log I see that it may be a value like "ture"!!!
So change it to:
String success = jsonResponse.getString("success");
and check it like:
if (success.equals("ture")) {
//.........
}
error message is saying itself everything.
org.json.JSONException: Value ture at success of type java.lang.String
the key (success ) holds a value as ture which is not boolean, instead it should be like true. so json is facing problem while converting it to boolean.
this issue is on webservice side, you have returned ture (not true) by mistake in webservice, so please make changes over there.
Related
I want to create login activity with multiple types of user. This login is connected with MySQL. The multiple choice is "Reviewer" and "Non-Reviewer". Now I use Spinner and the values I call from string.xml. At the table 'user', there are some column such as 'username', 'password', and 'usertype'. Example, user 'peter' is a "Reviewer", he will able to login if user name, password and user type that he uses is correct. How can i solve this problem? Below is my code.
//login activity
public class MainActivity extends AppCompatActivity{
private static final String KEY_USERNAME = "username";
private static final String LOGIN_URL = "http://lienawan.xyz/login.php";
private SharedPreferences.Editor loginPrefsEditor;
private EditText etEmail;
private EditText etPassword;
private CheckBox chkMe;
ArrayAdapter<CharSequence> adapter;
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); //will hide the title
Objects.requireNonNull(getSupportActionBar()).hide(); // hide the title ba
setContentView(R.layout.activity_main);
etEmail = findViewById(R.id.etEmail);
etPassword = findViewById(R.id.etPassword);
chkMe = findViewById(R.id.chkMe);
SharedPreferences loginPreferences = getSharedPreferences("loginPrefs", MODE_PRIVATE);
loginPrefsEditor = loginPreferences.edit();
boolean saveLogin = loginPreferences.getBoolean("saveLogin", false);
if (saveLogin) {
etEmail.setText(loginPreferences.getString("username", ""));
etPassword.setText(loginPreferences.getString("password", ""));
chkMe.setChecked(true);
}
Spinner spCategory = findViewById(R.id.spCategory);
adapter = ArrayAdapter.createFromResource(this,R.array.usertype,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spCategory.setAdapter(adapter);
spCategory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Button btnLogin = findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(etEmail.getWindowToken(), 0);
String username = etEmail.getText().toString();
String password = etPassword.getText().toString();
if (chkMe.isChecked()) {
loginPrefsEditor.putBoolean("saveLogin", true);
loginPrefsEditor.putString("username", username);
loginPrefsEditor.putString("password", password);
loginPrefsEditor.apply();
} else {
loginPrefsEditor.clear();
loginPrefsEditor.commit();
}
}
});
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Exit");
builder.setMessage("Do you want to exit?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
builder.show();
}
private void login() {
String username = etEmail.getText().toString().trim();
String password = etPassword.getText().toString().trim();
userLogin(username, password);
}
private void userLogin(final String username, final String password){
class UserLoginClass extends AsyncTask<String,Void,String> {
private ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this,"Login... Please Wait",null,true,true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
if(s.equalsIgnoreCase("success")){
Intent intent = new Intent(MainActivity.this,DashboardApp.class);
intent.putExtra(KEY_USERNAME,username);
startActivity(intent);
}else{
Toast.makeText(MainActivity.this,s, Toast.LENGTH_LONG).show();
}
}
#Override
protected String doInBackground(String... params) {
HashMap<String,String> data = new HashMap<>();
data.put("username",params[0]);
data.put("password",params[1]);
Connection ruc = new Connection();
String result = ruc.sendPostRequest(LOGIN_URL,data);
return result;
}
}
UserLoginClass ulc = new UserLoginClass();
ulc.execute(username, password);
}
}
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$username = $_POST['username'];
$password = $_POST['password'];
$approver = $_POST['approver'];
require_once('dbConnect.php');
$sql = "select * from user where username='$username' and password='$password'";
$check = mysqli_fetch_array(mysqli_query($con,$sql));
if(isset($check)){
echo "success";
}else{
echo "Invalid Username or Password";
}
}else{
echo "error try again";
To get selected value from spinner you write below code in onItemSelected :
String item;//declare globally out of your all method
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
item = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
}
Now,check if item and other value are not null , like below :
private void login() {
String username = etEmail.getText().toString().trim();
String password = etPassword.getText().toString().trim();
//checking if fields are not null
if (username.isEmpty() || password.isEmpty() || item.isEmpty()) {
Toast.makeText(getActivity().getApplicationContext(), "Please enter name or pass or select one type!", Toast.LENGTH_SHORT).show();
return;
}else{
userLogin(username, password,item);//passing value to volley
}
}
And in your volley request change like below :
private void userLogin(final String username, final String password,final String item){
...
#Override
protected String doInBackground(String... params) {
HashMap<String,String> data = new HashMap<>();
data.put("username",params[0]);
data.put("password",params[1]);
data.put("approver",params[2]);//adding item value
..
}
}
}
At your php side just change your query to :
$sql = "select * from user where username='$username' and password='$password' and usertype='$approver'";
Hope this helps you !
Note : Also never used plain-text password and try using prepared statement it is safe an secure.
I am trying to do a login session using Volley, PHP, MySQL but my login layout won't load. I do not know what is happening and in my logcat it says " java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.merylle.themoneyger/com.example.merylle.themoneyger.activity.LoginActivity}: java.lang.ClassCastException: com.example.merylle.themoneyger.activity.LoginActivity cannot be cast to com.example.merylle.themoneyger.activity.MainActivity"
which is cause by "Caused by: java.lang.ClassCastException: com.example.merylle.themoneyger.activity.LoginActivity cannot be cast to com.example.merylle.themoneyger.activity.MainActivity"
Can someone help me identify my error? Here's my code
SessionManager.java
public class SessionManager {
SharedPreferences sharedPreferences;
public SharedPreferences.Editor editor;
public Context context;
int PRIVATE_MODE=0;
private static final String PREF_NAME = "MONEYGER";
private static final String LOGIN = "IS_LOGIN";
public static final String FIRSTNAME = "NAME";
public static final String EMAIL = "EMAIL";
public static final String USERID = "USERID";
public SessionManager(Context context) {
this.context = context;
sharedPreferences = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = sharedPreferences.edit();
}
public void createSession(String firstname, String email) {
editor.putBoolean(LOGIN, true);
editor.putString(FIRSTNAME, firstname);
editor.putString(EMAIL, email);
/*editor.putString(USERID, userid);*/
editor.apply();
}
public boolean isLoggin(){
return sharedPreferences.getBoolean(LOGIN, false);
}
public void checkLogin() {
if (!this.isLoggin()) {
Intent i = new Intent(context, LoginActivity.class);
context.startActivity(i);
((MainActivity)context).finish();
}
}
public HashMap<String, String> getUserDetail() {
HashMap<String, String> user = new HashMap<>();
user.put(FIRSTNAME, sharedPreferences.getString(FIRSTNAME, null));
user.put(EMAIL, sharedPreferences.getString(EMAIL, null));
/*user.put(USERID, sharedPreferences.getString(USERID, null));*/
return user;
}
public void logout() {
editor.clear();
editor.commit();
Intent i = new Intent(context, LoginActivity.class);
context.startActivity(i);
((MainActivity)context).finish();
}
}
LoginActivity.java
public class LoginActivity extends Activity {
TextView title;
Typeface marcellus;
private EditText emailuser, passworduser;
TextView forgot;
private Button login, register;
private ProgressBar progressBar;
private static String HttpURL = "http://10.0.2.2:63343/TheMoneyger/api/user-login.php?";
SessionManager sessionManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
sessionManager = new SessionManager(this);
sessionManager.checkLogin();
title = (TextView) findViewById(R.id.txtTitle);
marcellus = Typeface.createFromAsset(getAssets(), "marcellus.ttf");
title.setTypeface(marcellus);
emailuser = (EditText) findViewById(R.id.txtEmail);
passworduser = (EditText) findViewById(R.id.txtPassword);
login = (Button) findViewById(R.id.btnLogin);
forgot = (TextView) findViewById(R.id.txtForgotPW);
register = (Button) findViewById(R.id.btnRegister);
progressBar = (ProgressBar)findViewById(R.id.progressBar3);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String mEmail = emailuser.getText().toString().trim();
String mPass = passworduser.getText().toString().trim();
if(!mEmail.isEmpty() || !mPass.isEmpty()) {
Login(mEmail, mPass);
}
else {
emailuser.setError("Please insert email");
passworduser.setError("Please insert password");
}
}
});
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent registration = new Intent(LoginActivity.this, RegistrationActivity.class);
startActivity(registration);
}
});
forgot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent forgot = new Intent(LoginActivity.this, ForgotPassword.class);
startActivity(forgot);
}
});
}
private void Login(final String emailuser, final String passworduser) {
progressBar.setVisibility(View.VISIBLE);
login.setVisibility(View.GONE);
StringRequest stringRequest = new StringRequest(Request.Method.POST, HttpURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
JSONArray jsonArray = jsonObject.getJSONArray("login");
if (success.equals("1")) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String firstname = object.getString("firstname").trim();
String email = object.getString("email").trim();
String id = object.getString("userid").trim();
sessionManager.createSession(firstname, email);
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra("firstname", firstname);
intent.putExtra("email", email);
startActivity(intent);
finish();
}
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(LoginActivity.this, "Something went wrong.. " + e.toString(), Toast.LENGTH_SHORT).show();
login.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this, "Something went wrong.. " + error.toString(), Toast.LENGTH_SHORT).show();
login.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE);
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("email", emailuser);
params.put("password", passworduser);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
Home2.java
public class Home2 extends Fragment {
private TextView profileName, profileEmail;
CardView cv1, cv2, cv3, cv4, cv5, cv6;
SessionManager sessionManager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
sessionManager = new SessionManager(getActivity().getApplicationContext());
sessionManager.checkLogin();
cv1 = (CardView)view.findViewById(R.id.cv1); //settings
cv2 = (CardView)view.findViewById(R.id.cv2); //profile
cv3 = (CardView)view.findViewById(R.id.cv3); //expenses summary
cv4 = (CardView)view.findViewById(R.id.cv4); //budget summary
cv5 = (CardView)view.findViewById(R.id.cv5); //report
cv6 = (CardView)view.findViewById(R.id.cv6); //logout
profileName = (TextView)view.findViewById(R.id.txtProfileName); //display profilename
profileEmail = (TextView)view.findViewById(R.id.txtProfileEmail); //display profileemail
HashMap<String, String> user = sessionManager.getUserDetail();
String mName = user.get(sessionManager.FIRSTNAME);
String mEmail = user.get(sessionManager.EMAIL);
profileName.setText(mName);
profileEmail.setText(mEmail);
return view;
}
}
user-login.php
<?php
if ($_SERVER['REQUEST_METHOD']=='POST') {
$email = $_POST['email'];
$password = $_POST['password'];
require_once 'config.php';
$sql = "SELECT * FROM users WHERE email='$username'";
$response = mysqli_query($db, $sql);
$result = array();
$result['login'] = array();
if ( mysqli_num_rows($response) === 1 ) {
$row = mysqli_fetch_assoc($response);
if ( password_verify($password, $row['password']) ) {
$index['firstname'] = $row['firstname'];
$index['email'] = $row['email'];
array_push($result['login'], $index);
$result['success'] = "1";
$result['message'] = "success";
echo json_encode($result);
mysqli_close($db);
} else {
$result['success'] = "0";
$result['message'] = "error";
echo json_encode($result);
mysqli_close($db);
}
}
}
?>
You have initialized sessionManager with LoginActivity's context:
sessionManager = new SessionManager(this);
and then inside SessionManager class you use this:
((MainActivity)context).finish();
which throws the error.
You can't cast LoginActivity's context to MainActivity.
Change to this:
((LoginActivity)context).finish();
After all it is LoginActivity you want to finish isn't it?
Why am I getting this error? please help. Thank you in advance!
final Button mShowDialog =(Button)findViewById(R.id.btnShowDialog);
mShowDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder mbuilder = new AlertDialog.Builder(LoginActivity.this);
View mView = getLayoutInflater().inflate(R.layout.dialog_login,null);
final EditText hehe= findViewById(R.id.etUsername);
final EditText hehe1= findViewById(R.id.etPassword);
final Button bLogin = mView.findViewById(R.id.bSignIn);
bLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String Username = hehe.getText().toString();
final String Password = hehe1.getText().toString();
// Response received from the server
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(LoginActivity.this, MainActivity.class);
LoginActivity.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage("Login Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
LoginRequest loginRequest = new LoginRequest(Username, Password, responseListener);
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
queue.add(loginRequest);
}
});
mbuilder.setView(mView);
AlertDialog dialog = mbuilder.create();
dialog.show();
}
});
use
final EditText hehe = mView.findViewById(R.id.etUsername);
// ^^^^^
final EditText hehe1 = mView.findViewById(R.id.etPassword);
final Button bLogin = mView.findViewById(R.id.bSignIn);
because findViewById alone will try to find the view from current layout of activity so you need to find views from mView object which is inflated from dialog_login.xml
I am getting error in
final EditText etregpassword = (EditText)findViewById(R.id.etregpassword);
I would like help with the comparison of password and confirm password and to display the error in password mismatch.
public class RegisterActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
final EditText etregname = (EditText)findViewById(R.id.etregname);
final EditText etregemailid = (EditText)findViewById(R.id.etregemailid);
final EditText etregpassword = (EditText)findViewById(R.id.etregpassword);
final EditText etconfirmregpassword = (EditText)findViewById(R.id.etconfirmregpassword);
final Button regbutton = (Button) findViewById(R.id.regbutton);
regbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String User_name = etregname.getText().toString();
final String Email_id = etregemailid.getText().toString();
final String Password = etregpassword.getText().toString();
final String Confirm_password = etconfirmregpassword.getText().toString();
Response.Listener<String> responseListner = new Response.Listener<String>(){
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
boolean SUCCESS = jsonObject.getBoolean("success");
if(SUCCESS){
Intent intent = new Intent(RegisterActivity.this,LoginActivity.class);
RegisterActivity.this.startActivity(intent);
}
else{
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
builder.setMessage("Register Failed")
.setNegativeButton("Retry",null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(User_name,Email_id,Password,Confirm_password,responseListner);
RequestQueue queue= Volley.newRequestQueue(RegisterActivity.this);
queue.add(registerRequest);
}
});
}
}
Just compare those values:
final String password = etregpassword.getText().toString();
final String confirmPassword = etconfirmregpassword.getText().toString();
if (!TextUtils.isEmpty(password) && !TextUtils.isEmpty(confirmPassword))
{
if(password.equals(confirmPassword))
{
//are equal
}
else {
//are different
}
}
This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 6 years ago.
So I'm trying to upload some data to MySQL. I believe that I am effectively passing the value of email in LoginActivity.java to PartySetup.java, but the value is apparently getting lost somewhere along the way. I've tried using sharedPreferences with the same result. Does anyone have any ideas why this is happening? Thanks!
LoginActivity.java:
public class LoginActivity extends AppCompatActivity{
public static ArrayList<String> emailSaver = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstancedState){
super.onCreate(savedInstancedState);
setContentView(R.layout.activity_login);
final EditText tempEmail = (EditText) findViewById(R.id.email);
final EditText tempPassword = (EditText) findViewById(R.id.password);
final Button loginButton = (Button) findViewById(R.id.btnLogin);
final Button toRegisterScreen = (Button) findViewById(R.id.btnLinkToRegisterScreen);
if (SaveSharedPreference.getUserName(LoginActivity.this).length() != 0){
// If the user's already been logged in, skip the login screen
Intent intent = new Intent(LoginActivity.this, OneTimeWelcome.class);
startActivity(intent);
finish();
}
toRegisterScreen.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Intent registerIntent = new Intent(LoginActivity.this, RegisterActivity.class);
LoginActivity.this.startActivity(registerIntent);
}
});
loginButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
final String email = tempEmail.getText().toString();
emailSaver.add(0, email);
final String password = tempPassword.getText().toString();
//Response received from the server
Response.Listener<String> responseListener = new Response.Listener<String>(){
#Override
public void onResponse(String response){
try{
Log.i("TAG", response);
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if(success){
String name = jsonResponse.getString("name");
Intent intent = new Intent(LoginActivity.this, OneTimeWelcome.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("name", name);
intent.putExtra("email", email);
LoginActivity.this.startActivity(intent);
finish();
}
else{
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage("Login Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
}
catch(JSONException e){
e.printStackTrace();
}
SaveSharedPreference.setUserName(LoginActivity.this, email);
}
};
LoginRequest loginRequest = new LoginRequest(email, password, responseListener);
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
queue.add(loginRequest);
}
});
}
}
PartySetup.java:
public class PartySetup extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient mGoogleApiClient;
private Location location;
private TextView tempLatitude;
private TextView tempLongitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_party_setup);
final EditText tempPartyName = (EditText) findViewById(R.id.party_name);
final EditText tempHostName = (EditText) findViewById(R.id.host_name);
final Button startParty = (Button) findViewById(R.id.create_party);
final CheckBox locationButton = (CheckBox) findViewById(R.id.set_location);
tempLatitude = (TextView) findViewById(R.id.latitude_text);
tempLongitude = (TextView) findViewById(R.id.longitude_text);
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
mGoogleApiClient.connect();
startParty.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (locationButton.isChecked() && tempPartyName != null){
final String partyName = tempPartyName.getText().toString();
final String hostName;
if (tempHostName == null){
hostName = "";
}
else hostName = tempHostName.getText().toString();
final String latitude = tempLatitude.getText().toString();
final String longitude = tempLongitude.getText().toString();
final String publicEmail = LoginActivity.emailSaver.get(0);
Response.Listener<String> responseListener = new Response.Listener<String>(){
#Override
public void onResponse(String response){
try{
Log.i("TAG", response);
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if(success){
Intent intent = new Intent(PartySetup.this, HomePage.class);
startActivity(intent);
}
else{
AlertDialog.Builder builder = new AlertDialog.Builder(PartySetup.this);
builder.setMessage("Invalid Party Nickname")
.setNegativeButton("Try Again", null)
.create()
.show();
}
} catch (JSONException e){
e.printStackTrace();
}
}
};
CreatePartyRequest createPartyRequest = new CreatePartyRequest(partyName, hostName, latitude, longitude, publicEmail, responseListener);
RequestQueue queue = Volley.newRequestQueue(PartySetup.this);
queue.add(createPartyRequest);
}
else {
AlertDialog.Builder builder = new AlertDialog.Builder(PartySetup.this);
builder.setMessage("Please check the location box")
.setNegativeButton("Try Again", null)
.create()
.show();
}
}
});
}
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
try{
location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
}
catch (SecurityException e){
e.printStackTrace();
}
if (location != null){
tempLatitude.setText(String.valueOf(location.getLatitude()));
tempLongitude.setText(String.valueOf(location.getLongitude()));
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
CreatePartyRequest.java:
public class CreatePartyRequest extends StringRequest {
private static final String CREATE_PARTY_REQUEST_URL = "http://10.0.2.2:8080/android_login_api/create_party_request.php";
private Map<String, String> params;
public CreatePartyRequest(String partyName, String hostName, String latitude, String longitude, String email, Response.Listener<String> listener){
super(Method.POST, CREATE_PARTY_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("partyName", partyName);
params.put("hostName", hostName);
params.put("latitude", latitude);
params.put("longitude", longitude);
params.put("user", email);
}
#Override
public Map<String, String> getParams(){
return params;
}
}
create_party_request.php:
<?php
$con = mysqli_connect("127.0.0.1" , "(my username)" , "(my password)" , "android_api");
$partyName = $_POST["partyName"];
$hostName = $_POST["hostName"];
$latitude = $_POST["latitude"];
$longitude = $_POST["longitude"];
$publicEmail = $_POST["publicEmail"];
global $con, $partyName, $hostName, $latitude, $longitude;
$statement = mysqli_prepare($con, "INSERT INTO parties (party_name, host_name, latitude, longitude, email) VALUES (?, ?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "sssss", $partyName, $hostName, $latitude, $longitude, $publicEmail);
mysqli_stmt_execute($statement);
mysqli_stmt_close($statement);
$response = array();
$response["success"] = true;
echo json_encode($response);
?>
As a side note, the fields in my sql table are party_name, host_name, latitude, longitude, user.
Here are the errors I'm getting. The log was a bit cut off, but as the title says, there is an undefined index error on the variable publicEmail on line 9 of the php:
Use params.put("publicEmail", email);
instead of params.put("user", email); in CreatePartyRequest.java