Android - getting undefined index JSONException, but I'm not sure why [duplicate] - java

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

Related

com.android.volley.clientError Android Studio Error

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();
}
}

String cannot be converted to boolean error

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.

How to get data from text view in first activity and post it from another activity?

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!

java.lang.ClassCastException: Activity cannot be cast to MainActivity

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?

How do I compare password and confirm password?

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
}
}

Categories