When I press on the register button this error occurs.
I have installed the volley 1.1.1
this is my code:
public class MainActivity extends AppCompatActivity {
private EditText etEmail, etPassword;
private String email, password;
private String URL = "http://10.0.2.2/login/login.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
email = password = "";
etEmail = findViewById(R.id.etEmail);
etPassword = findViewById(R.id.etPassword);
}
public void login(View view) {
email = etEmail.getText().toString().trim();
password = etPassword.getText().toString().trim();
if(!email.equals("")&&!password.equals("")){
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.equals("success")) {
Intent intent = new Intent(MainActivity.this, Success.class);
startActivity(intent);
finish();
} else if (response.equals("failure")) {
Toast.makeText(MainActivity.this, "Invalid Login Id/Password", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString().trim(), Toast.LENGTH_SHORT).show();
}
}){
protected Map<String, String> getParms() throws AuthFailureError {
Map<String, String> parms = new HashMap<>();
parms.put("email",email);
parms.put("password", password);
return parms;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}else{
Toast.makeText(this, "Fields can not be empty!", Toast.LENGTH_SHORT).show();
}
}
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'm trying to login with four different users using php and mysql database in android, and after if any user login with email and password i'm trying to fetch their information like (Name, Address, ID, etc.) from mysql database.
And i want that whenever if any of user from those four users login they can able to see their own information from database like(Name, Address, ID, etc.)
I have already tried to separate those users with the user type and with if-else condition that is in code that i provided.
public class LoginActivity extends AppCompatActivity {
private static final String TAG="LoginActivity";
private TextView createaccount;
private EditText Ausername,Apassword;
private Button LoginButton;
private Context mContext;
//URLS class
//ALL URLs
URLs urLs;
RelativeLayout relativeLayout1,relativeLayout2;
Handler handler=new Handler();
Runnable runnable=new Runnable() {
#Override
public void run() {
relativeLayout1.setVisibility(View.VISIBLE);
relativeLayout2.setVisibility(View.VISIBLE);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
urLs = new URLs();
if (SharedPrefManager.getInstance(getApplicationContext()).isLoggedIn()){
finish();
Intent intentD = new Intent(LoginActivity.this, DashboardActivity.class);
startActivity(intentD);
}
relativeLayout1 = findViewById(R.id.rel3);
relativeLayout2 = findViewById(R.id.rel2);
Ausername = findViewById(R.id.etuname);
Apassword = findViewById(R.id.etpass);
LoginButton = findViewById(R.id.loginbutton);
handler.postDelayed(runnable, 2000);
createaccount = findViewById(R.id.tvregistration);
createaccount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(LoginActivity.this, Rigistration_Option.class);
startActivity(intent);
}
});
LoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
userLogin();
}
});
}
private void userLogin(){
//first getting the values
final String email = Ausername.getText().toString();
final String password = Apassword.getText().toString();
//validating inputs
if (TextUtils.isEmpty(email)) {
Ausername.setError("Please enter your username");
Ausername.requestFocus();
return;
}
if (TextUtils.isEmpty(password)) {
Apassword.setError("Please enter your password");
Apassword.requestFocus();
return;
}
//if everything is fine
class UserLogin extends AsyncTask<Void, Void, String> {
ProgressBar progressBar;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar = findViewById(R.id.progressbar);
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressBar.setVisibility(View.GONE);
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
CA_SIGNUP_GTST user = new CA_SIGNUP_GTST(
userJson.getInt("id"),
userJson.getString("name"),
userJson.getString("email"),
userJson.getString("mobile"),
userJson.getString("address")
);
//storing the user in shared preferences
SharedPrefManager.getInstance(getApplicationContext()).userLogin(user);
//starting the profile activity
finish();
Intent intentD = new Intent(LoginActivity.this, DashboardActivity.class);
startActivity(intentD);
} 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();
HashMap<String, String> params = new HashMap<>();
URLs urLs = new URLs();
if (urLs.equals("cma_login")) {
params.put("email", email);
params.put("password", password);
return requestHandler.sendPostRequest(URLs.CMA_LOGIN, params);
}
else if (urLs.equals("ca_login")){
params.put("email", email);
params.put("password", password);
return requestHandler.sendPostRequest(URLs.CA_LOGIN, params);
}
else if (urLs.equals("cs_login")){
params.put("email", email);
params.put("password", password);
return requestHandler.sendPostRequest(URLs.CS_LOGIN, params);
}
else if (urLs.equals("adv_login")){
params.put("email", email);
params.put("password", password);
return requestHandler.sendPostRequest(URLs.ADV_LOGIN, params);
}
return null;
}
}
UserLogin ul = new UserLogin();
ul.execute();
}
}
i expect that after user login they can see their own information but when i try to login with second and the third user then they are unable to login.
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 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?
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