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?
Related
I have created two activities SignUp and Login.
Also, I have SharedPreferences which get edittext value. When I call SharedPreferences(getNomre) inside onCreate It works but doesn't work as global variable. I want to declare a variable named mobileNomre for using put to Constant.mobile. How can I send Shared Preference value to Constant.mobile?
p.s: Acitivity code is too large. I noted some parts of them.
Thanks
SignUpActivity:
public void SignUpWithEmail(View view) {
if (!validateForm()) {
return;
}
showProgressDialog();
final String email = edtEmail.getText().toString();
final String password = edtPassword.getText().toString();
final String name = edtName.getText().toString();
final String mobile = edtMobile.getText().toString();
Session.setNomre(getApplicationContext(),"nomreler",mobile);
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(name).build();
assert user != null;
user.updateProfile(profileUpdates)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
}
}
});
sendEmailVerification();
} else {
hideProgressDialog();
try {
throw Objects.requireNonNull(task.getException());
} catch (FirebaseAuthInvalidCredentialsException | FirebaseAuthInvalidUserException | FirebaseAuthUserCollisionException invalidEmail) {
inputEmail.setError(invalidEmail.getMessage());
} catch (Exception e) {
e.printStackTrace();
inputEmail.setError(e.getMessage());
}
}
}
});
}
LoginActivity:
public class LoginActivity extends AppCompatActivity {
String TAG = "LoginActivity";
int RC_SIGN_IN = 9001;
CallbackManager mCallbackManager;
String token;
String mobileNomre = Session.getNomre(getApplicationContext(),"nomreler","");
public static FirebaseAuth mAuth;
GoogleSignInClient mGoogleSignInClient;
TextView tvPrivacy, tvTest;
ProgressDialog mProgressDialog;
public TextInputEditText edtEmail, edtPassword;
public TextInputLayout inputEmail, inputPass;
public void UserSignUpWithSocialMedia( final String mobileNomre,
final String fCode,
final String referCode,
final String name,
final String email,
final String profile,
final String type) {
StringRequest strReq = new StringRequest(Request.Method.POST, Constant.QUIZ_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
if (obj.getString("error").equals("false")) {
JSONObject jsonobj = obj.getJSONObject("data");
if (!jsonobj.getString(Constant.status).equals(Constant.DE_ACTIVE)) {
Session.saveUserDetail(getApplicationContext(),
jsonobj.getString(Constant.userId),
jsonobj.getString(Constant.name),
jsonobj.getString(Constant.email),
jsonobj.getString(Constant.mobile),
jsonobj.getString(Constant.PROFILE), referCode);
User user = new User(
jsonobj.getString(Constant.mobile),
jsonobj.getString(Constant.name),
jsonobj.getString(Constant.email),
"0",
false,
jsonobj.getString(Constant.PROFILE),
"0",
token,
jsonobj.getString(Constant.userId));
FirebaseDatabase.getInstance().getReference("user").child(FirebaseAuth.getInstance().
getCurrentUser().getUid()).setValue(user).
addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task1) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.putExtra("type", "default");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
finish();
}
});
hideProgressDialog();
} else
setSnackBarStatus();
} else {
LoginManager.getInstance().logOut();
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put(Constant.accessKey, Constant.accessKeyValue);
params.put(Constant.userSignUp, "1");
params.put(Constant.email, email);
params.put(Constant.name, name);
params.put(Constant.PROFILE, profile);
params.put(Constant.fcmId, token);
params.put(Constant.type, type);
params.put(Constant.mobile, mobileNomre );
params.put(Constant.REFER_CODE, referCode);
params.put(Constant.FRIENDS_CODE, fCode);
WifiManager wm = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
params.put(Constant.ipAddress, ip);
System.out.println("---params social " + params.toString());
return params;
}
};
// AppController.getInstance().getRequestQueue().getCache().clear();
AppController.getInstance().addToRequestQueue(strReq);
}
SharedPrereferences:
public class Session {
public static void setNomre(Context mContext, String key, String objString) {
SharedPreferences.Editor editor =
mContext.getSharedPreferences(mContext.getString(R.string.app_name),
Context.MODE_PRIVATE).edit();
editor.putString(key, objString);
editor.commit();
}
public static String getNomre(Context mContext, final String key, final String defaultStr) {
SharedPreferences pref = mContext.getSharedPreferences(mContext.getString(R.string.app_name),
Context.MODE_PRIVATE);
return pref.getString(key, defaultStr);
}}
Make your String public static to access it globally;
public static String mobileNomre = Session.getNomre(getApplicationContext(),"nomreler","");
Haven't tried but working around with below code can give you an idea,
We uses this method if we want to access any function of Activity1 in Activity2..
AnotherActivity anotheractivity = (AnotherActivity) this.getActivity();
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 want the data of textview in the second activity to pass in the third but i dont want to display it in the third activity. I want to directly send the data from the second activity to Pass in my sql db after clicking the button in the final activity. Is is achievable?
This is my first activity.
public class MainActivity extends AppCompatActivity {
private EditText email, password;
private Button btn_login;
private ProgressBar loading;
private static String URL_LOGIN ="http://192.168.1.83/Attendance/login.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loading= findViewById(R.id.loading);
email = findViewById(R.id.editTextUserEmail);
password = findViewById(R.id.editTextPassword);
btn_login = findViewById(R.id.buttonRegister);
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mEmail = email.getText().toString().trim();
String mPassword = password.getText().toString().trim();
if (!mEmail.isEmpty() || !mPassword.isEmpty()) {
Login(mEmail, mPassword);
}else{
email.setError("Please Enter Email");
password.setError("Please Enter Password");
}
}
});
}
private void Login(final String email, final String password) {
loading.setVisibility(View.VISIBLE);
btn_login.setVisibility(View.GONE);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
Log.d("JSON", jsonObject.toString());
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 name =
object.getString("name").trim();
String email =
object.getString("email").trim();
// Toast.makeText(MainActivity.this,
"Success Login \nYour name: "+name+"\nYour Email: "+email,
// Toast.LENGTH_LONG).show();
Intent intent = new
Intent(MainActivity.this, HomeActivity.class);
intent.putExtra("name",name);
intent.putExtra("email", email);
startActivity(intent);
loading.setVisibility(View.GONE);
}
}
} catch (JSONException e) {
e.printStackTrace();
loading.setVisibility(View.GONE);
btn_login.setVisibility(View.VISIBLE);
Toast.makeText(MainActivity.this, "Error"
+e.toString(),
Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Error"
+error.toString(),
Toast.LENGTH_LONG).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("email", email);
params.put("password", password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
This is my second activity
public class HomeActivity extends AppCompatActivity {
private TextView name,email;
private TextView welcome;
private Button Send;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
name = findViewById(R.id.name);
email = findViewById(R.id.email);
Send = findViewById(R.id.btn_send);
welcome = findViewById(R.id.welcome);
final Intent intent = getIntent();
String extraName = intent.getStringExtra("name");
String extraEmail = intent.getStringExtra("email");
name.setText(extraName);
email.setText(extraEmail);
Send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent(HomeActivity.this,StatusActivity.class);
intent1.putExtra("wel", welcome.getText().toString());
intent1.putExtra("name1", name.getText().toString());
intent1.putExtra("email1", email.getText().toString());
startActivity(intent1);
}
});
}
And this is my final activity but Here i dont want to show the text view i just want to post it from here.
public class StatusActivity extends AppCompatActivity {
private TextView welcome, name, email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_status);
welcome = findViewById(R.id.abcd);
name = findViewById(R.id.name1);
email = findViewById(R.id.email1);
final Intent intent = getIntent();
String extraName1 = intent.getStringExtra("name1");
String extraEmail1 = intent.getStringExtra("email1");
String extraWelcome = intent.getStringExtra("wel");
name.setText(extraName1);
email.setText(extraEmail1);
welcome.setText(extraWelcome);
}
Your question is pretty clear until you put MySql to the topic. Why you want to pass the data from one activity to another through the database. Why involve database operations which take time and resources.
You may pass data from one activity to another through Intents (primitive values, Strings and Parcelables)!
All you have to do is:
Get the data (int your case from TextView).
Create the Intent to navigate to the next Activity.
Put the data to the Intent.
Start the Activity.
Retrieve the data from the Intent.
For example if will navigate to the next Activity via button click then in that button's onClick():
// 1.
String data = myTextView.getText();
// 2.
Intent intent = new Intent(yourContext,YourNextActivity.class);
// 3.
intent.putStringExtra("MY DATA KEY",data);
// 4.
yourContext.startActivity(intent);
// 5. Now in YourNextActivity's onCreate();
String retrievedData = YourNextActivity.this.getIntent().getStringExtra("MY DATA KEY");
// Done!
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