This question already has answers here:
How do i use a variable outside the onResponse in Android?
(4 answers)
Closed 4 years ago.
Greeting all, I am having the hard time to set int value for a variable in ValueEventListener and get that value outside ValueEventListener for the method to checking is value == 1, the method will return 1, else return 0
I have tried many way like save the value via SharedPreferences, set value to Textview and call from textview, but still, the method always return 0 as it cannot read the value that have been set in ValueEventListener. Any help are much appreciate. Thank you
Here my code
int status = 0;
protected void onCreate(Bundle savedInstanceState) {
...
btnSync_in.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (getCustomerList() == 1) {
msg = msg + "Get customer success \n";
} else {
msg = msg + "Get customer unsuccessful \n";
}
AlertDialog.Builder statusDialog = new AlertDialog.Builder(SyncActivity.this);
statusDialog.setPositiveButton("OK", null);
statusDialog.setTitle("Status");
statusDialog.setMessage(msg);
statusDialog.show();
msg = "";
}
});
}
The method that will return the int
private int getCustomerList() {
urlRef = myRef.child("...");
urlRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
...
StringRequest stringRequest = new StringRequest(Request.Method.GET, customerURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
status = 1; //here my problem, value assign here is success
try {
...
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
...
status = 0; // here if unsuccessful
}
});
RequestQueue requestQueue = Volley.newRequestQueue(SyncActivity.this);
requestQueue.add(stringRequest);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
...
}
});
if (status == 1) {
return 1;
} else {
return 0;
}
}
Even better way why dont't you display your AlertDialog inside getCustomerList() method
Call your getCustomerList() like this
btnSync_in.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getCustomerList();
}
});
Then add your AlertDialog inside getCustomerList() like this
SAMPLE CODE
private void getCustomerList() {
AlertDialog.Builder statusDialog = new AlertDialog.Builder(SyncActivity.this);
statusDialog.setPositiveButton("OK", null);
statusDialog.setTitle("Status");
urlRef = myRef.child("...");
urlRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
...
StringRequest stringRequest = new StringRequest(Request.Method.GET, customerURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
msg = msg + "Get customer success \n";
statusDialog.setMessage(msg);
statusDialog.show();
msg = "";
try {
...
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
...
msg = msg + "Get customer unsuccessful \n";
statusDialog.setMessage(msg);
statusDialog.show();
msg = "";
}
});
RequestQueue requestQueue = Volley.newRequestQueue(SyncActivity.this);
requestQueue.add(stringRequest);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
...
}
});
}
Related
I have my MainActivity in which I handle the logout. Problem is after I log out, the app crashes in verifyUserExistance() at line:
String userID = Objects.requireNonNull(mAuth.getCurrentUser()).getUid();
Which gives :
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.google.firebase.quickstart.auth, PID: 8459
java.lang.NullPointerException
at java.util.Objects.requireNonNull(Objects.java:203)
at com.google.firebase.quickstart.auth.social.Main_Chat_Activity$3.lambda$null$1$Main_Chat_Activity$3(Main_Chat_Activity.java:372)
at com.google.firebase.quickstart.auth.social.-$$Lambda$Main_Chat_Activity$3$87CwjFnoJAhucBGNsLP_MxK833o.onComplete(Unknown Source:2)
at com.google.android.gms.tasks.zzj.run(com.google.android.gms:play-services-tasks##17.2.0:4)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7050)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)
Below is the code I use:
#Override
protected void onStart() {
super.onStart();
usersRef.child(mAuth.getCurrentUser().getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (!snapshot.hasChild("name"))
{
sendUserToLoginActivity();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
if (mAuth == null || currentUser == null || mAuth.getCurrentUser().getUid() == null ){
finish();
sendUserToLoginActivity();
}
else {
if(mAuth.getCurrentUser().getProviderId() == "google.com"){
user.setmGoogleSignInClient(mGoogleSignInClient);
}
user.setMauth(mAuth);
if (loginOutFlag>-1)
verifyUserExistence();
}
checkLocation();
if (isNew!=null)
{
if (isNew.equals("true")){
sendUserToSettingsActivity();
}
}
}
The method verifyUserExistance is;
private void verifyUserExistence() {
if (!verified && loginOutFlag > -1) {
String currentUserID = mAuth.getCurrentUser().getUid();
try {
rootRef.child("Users").child(currentUserID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.child("name").exists()) {
loginOutFlag = 1;
Toast.makeText(Main_Chat_Activity.this, "Welcome" + dataSnapshot.child("name").getValue().toString(), Toast.LENGTH_SHORT).show();
Log.w("Reportname:", dataSnapshot.child("name").getValue().toString());
Calendar cal = Calendar.getInstance();
final String timeNDate = cal.getTime().toString();
HashMap<String, Object> profileMap = new HashMap<>();
profileMap.put("connection", timeNDate);
rootRef.child("Users").child(currentUserID).updateChildren(profileMap)
.addOnCompleteListener(task ->
{
if (task.isSuccessful()) {
Toast.makeText(Main_Chat_Activity.this, "Success ", Toast.LENGTH_SHORT).show();
verified = true;
FirebaseMessaging.getInstance().getToken()
.addOnCompleteListener(task13 -> {
String userID = Objects.requireNonNull(mAuth.getCurrentUser()).getUid();
if (!task13.isSuccessful()) {
Log.w("FCM", "Fetching FCM registration token failed", task13.getException());
return;
}
// Get new FCM registration token
String deviceToken = task13.getResult();
// Log and toast
Log.d("FCM", deviceToken);
Toast.makeText(Main_Chat_Activity.this, deviceToken, Toast.LENGTH_SHORT).show();
final int[] no = {0};
DatabaseReference tokens = usersRef.child(userID).child("device_tokens");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
no[0] = (int) snapshot.getChildrenCount();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
};
tokens.addListenerForSingleValueEvent(valueEventListener);
String devName = "device" + no[0];
String token = deviceToken.split(":")[1];
usersRef.child(userID).child("device_tokens").child(devName)
.setValue(token)
.addOnCompleteListener(task12 -> {
if (task12.isSuccessful()) {
Toast.makeText(Main_Chat_Activity.this, "Token updated succesfully.", Toast.LENGTH_LONG).show();
}
});
});
} else {
String errorMSG = Objects.requireNonNull(task.getException()).toString();
//user.setMauth(null);
Toast.makeText(Main_Chat_Activity.this, "Error : " + errorMSG, Toast.LENGTH_SHORT).show();
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
catch (Exception e)
{
Log.d("EXCEPTION", e.toString());
}
}
}
and this is how I handle the logout;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if (item.getItemId() == R.id.main_logout_option) {
updateUserStatus("offline");
String currentUserID = mAuth.getCurrentUser().getUid();
rootRef.child("Users").child(currentUserID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.child("name").exists()) {
Calendar cal = Calendar.getInstance();
final String timeNDate = cal.getTime().toString();
HashMap<String, Object> profileMap = new HashMap<>();
profileMap.put("connection", timeNDate);
rootRef.child("Users").child(currentUserID).updateChildren(profileMap)
.addOnCompleteListener(task ->
{
if (task.isSuccessful()) {
loginOutFlag = -1;
} else {
String errorMSG = Objects.requireNonNull(task.getException()).toString();
Toast.makeText(Main_Chat_Activity.this, "This error : " + errorMSG, Toast.LENGTH_SHORT).show();
}
mGoogleSignInClient.signOut().addOnCompleteListener(task1 -> {
if (task1.isSuccessful()){
mAuth.signOut(); // very important if you are using firebase.
LoginManager.getInstance().logOut();
sendUserToLoginActivity();
finish();
}
});
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
sendUserToLoginActivity();
}
if (item.getItemId() == R.id.main_settings_option) {
sendUserToSettingsActivity();
}
if (item.getItemId() == R.id.main_find_friends_option) {
sendUserToFindFriendsActivity();
}
return true;
}
Problem is after I log out, the app crashes:
at line String userID = Objects.requireNonNull(mAuth.getCurrentUser()).getUid()
When you log out, the mAuth objct becomes null. So calling getCurrentUser() on a such an object, instead of returning a FirebaseUser object, it will return null, hence the presence of the NullPointerExcepetion.
Returns the currently signed-in FirebaseUser or null if there is none.
So the solution for your problem is to wait for the asynchronous operation to finish, and right after that to sign out, otherwise, you'll always get NullPointerExcepetion.
Here is an example of you can wait until the data is finished loading from the Realtime Database:
How to return DataSnapshot value as a result of a method?
hello i'm looking to create a way to check if the username is already in use or not.
The problem is that if the username is already taken the error is displayed correctly, but the user still registers ...
private boolean validateForm () {
boolean valid = true;
String username = rUsernameField.getText().toString();
String email = rEmailField.getText().toString();
if (TextUtils.isEmpty(email)) {
rEmailField.setError(getText(R.string.field_error));
valid = false;
} else {
rEmailField.setError(null);
}
String password = rPasswordField.getText().toString();
if (TextUtils.isEmpty(password)) {
rPasswordField.setError(getText(R.string.field_error));
valid = false;
} else {
rPasswordField.setError(null);
}
if (TextUtils.isEmpty(username)) {
rUsernameField.setError(getText(R.string.field_error));
valid = false;
validUsername = false;
} else {
rUsernameField.setError(null);
}
if (!validUsername) {
valid = false;
}
if (rCGUCheck.isChecked()) {
rCGUCheck.setError(null);
} else {
rCGUCheck.setError(getText(R.string.err_cgu));
valid = false;
}
return valid;
}
public void setValidUsername() {
String username = rUsernameField.getText().toString();
FirebaseDatabase.getInstance().getReference().child("users").orderByChild("username").equalTo(username).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
validUsername = false;
Log.d(TAG, "false");
rUsernameField.setError("This username already exists");
} else {
validUsername = true;
Log.d(TAG, "true");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void signUp() {
Log.d(TAG, "signUp");
if (!validateForm()) {
return;
}
#Override
public void onClick (View v){
int i = v.getId();
if (i == R.id.regBtn) {
setValidUsername();
signUp();
}
therefore if one of the fields is not filled in, the user cannot register. But what I don't understand is why even if the username already exists the user can still register ^^
Thank's in advance.
Have one function called validateUser:
public void validateUser() {
//get string from editTexts
String username = rUsernameField.getText().toString();
String email = rEmailField.getText().toString();
String password = rPasswordField.getText().toString();
FirebaseDatabase.getInstance().getReference().child("users").orderByChild("username").equalTo(username).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
//username is not available
rUsernameField.setError("This username already exists");
} else {
//username is available
//so check now if all is okay
if(!TextUtils.isEmpty(email) && !TextUtils.isEmpty(password) && !TextUtils.isEmpty(username) && rCGUCheck.isChecked()){
signUp();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
The signUp() method:
private void signUp(){
//sign up
Log.d(TAG, "signUp");
}
onclick() method
#Override
public void onClick (View v){
int i = v.getId();
if (i == R.id.regBtn) {
validateUser();
}
Your setValidUsername is an asynchronous operation. Data is loaded from Firebase asynchronously (like with most cloud APIs), since it may take some time to complete. While that is happening, you main code continues and your signUp method executes. Then when the data is available, your onDataChange is called and sets validUsername.
For a good example of this and a solution, see my answer here: getContactsFromFirebase() method return an empty list
For you this could mean:
Defining an interface for your own callback:
public interface UserExistsCallback {
void onCallback(boolean value);
}
Modify setValidUsername to take this callback as an argument, and call it:
public void isValidUsername(UserExistsCallback callback) {
String username = rUsernameField.getText().toString();
FirebaseDatabase.getInstance().getReference().child("users").orderByChild("username").equalTo(username).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
callback.onCallback(false);
rUsernameField.setError("This username already exists");
} else {
callback.onCallback(true);
Log.d(TAG, "true");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException(); // never ignore errors
}
});
}
Call this new function and use the value in the callback:
isValidUsername(new UserExistsCallback() {
#Override
public void onCallback(boolean exists) {
System.out.println("User exists: "+exists);
}
});
So In my app I have a few spinners the one spinner gives a Hourly Rate,
the data in the spinner I have edited using Matcher,regex etc. so that they display correctly in the spinner
but what I can't figure out is I have to pass the original string of the Array Item on item select to a URL builder And I have No Idea how to do this at all and have googled for hours now
so the original
object looks like this
7 - 1 - R100
so I used Matcher and Pattern to trim that value in the spinner to display just
R100
But now I have to pass the original value of
7 - 1 - R100
To a URI Builder
Here is the code for populating the spinner
private void LoadUserRatesSpinnerData(String url) {
RequestQueue requestQueue=Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject=new JSONObject(response);
if (jsonObject.getInt("success") == 1) {
JSONArray jsonArray=jsonObject.getJSONArray("Name");
for (int i=0; i < jsonArray.length(); i++) {
JSONObject jsonObject1=jsonArray.getJSONObject(i);
String rates=jsonObject1.getString("UserRate");
for(int p=0; p < 100; p++){
final Matcher matcher=Pattern.compile(" - ").matcher(rates);
if (matcher.find()) {
rates=rates.substring(matcher.end()).trim();
}
}
UserRate.add(rates);
}
}
UserRatesSpinner.setAdapter(new ArrayAdapter<>(IntTimeLog.this, android.R.layout.simple_spinner_dropdown_item, UserRate));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
int socketTimeout=30000;
RetryPolicy policy=new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
requestQueue.add(stringRequest);
}
The onItemSelected code for the spinner
UserRatesSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#SuppressLint("SetTextI18n")
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
if (position == 0) {
UserRatesSpinner.setClickable(true);
} else {
UserRatesSpinner.setClickable(true);
UserRates=UserRatesSpinner.getSelectedItem().toString();
}
if (LogHour.getText().toString().contains("Hours Logged")) {
LogHour.setText("Log Hours");
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
At the Moment only the R100 gets passed to the URI builder
You should declare a new variable, I called it trimmedRates. As it stands your code is overwriting the variable rates.
String trimmedRates;
if (matcher.find()) {
trimmedRates=rates.substring(matcher.end()).trim();
}
So I solved this Issue by making another ArrayList and adding the original Json data before I adding the data from the matcher to a seprate arraylist,
Here is the code
private void LoadTaskSpinner(String url) {
final ProgressDialog pd=new ProgressDialog(IntTimeLog.this);
pd.setMessage("Please Wait..Loading Time Log Data");
pd.setCanceledOnTouchOutside(false);
pd.show();
RequestQueue requestQueue=Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pd.cancel();
try {
JSONObject jsonObject=new JSONObject(response);
if (jsonObject.getInt("success") == 1) {
JSONArray jsonArray=jsonObject.getJSONArray("Name");
for (int i=0; i < jsonArray.length(); i++) {
JSONObject jsonObject1=jsonArray.getJSONObject(i);
String task=jsonObject1.getString("TaskName");
TaskName.add(task);
}
}
taskSpinner.setAdapter(new ArrayAdapter<>(IntTimeLog.this, android.R.layout.simple_spinner_dropdown_item, TaskName));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pd.cancel();
LoadErrorSpinner(ClientsUrl);
error.printStackTrace();
}
});
int socketTimeout=30000;
RetryPolicy policy=new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
requestQueue.add(stringRequest);
}
And then in the Item selection I used IF statements to get the correct String to the URL
UserRatesSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#SuppressLint("SetTextI18n")
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
if (position == 1) {
SelectedSpin = ItemSelect.get(1);
}
else{
UserRatesSpinner.setClickable(true);
}
if (position == 2) {
SelectedSpin = ItemSelect.get(2);
}
else {
UserRatesSpinner.setClickable(true);
}
if (position == 3) {
SelectedSpin = ItemSelect.get(3);
}
else{
UserRatesSpinner.setClickable(true);
}
if (LogHour.getText().toString().contains("Hours Logged")) {
LogHour.setText("Log Hours");
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
I have class A and B.
"A" makes an instance of "B" and call a method that modify a String property. However, after the calling the property checked in "A" is null.
Can anyone help me?
Class B
private String Retro;
....
public boolean Login(final String user, final String pass){
stringRequest = new StringRequest(Request.Method.POST, Url + strLogin,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
Retro = "Done";
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
**Retro = error.getMessage();**
Toast.makeText(context, "Error de acceso: "+Retro, Toast.LENGTH_LONG).show(); //error.getMessage()
}
}) {
#Override
protected Map<String, String> getParams(){
Map<String, String> parameters = new HashMap<>();
parameters.put("identifier", user);
parameters.put("password", pass);
return parameters;
}
};
// Add the request to the RequestQueue.
requestQueue.add(stringRequest);
return Retro == "Done";
}
Class A
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
accessDB = new StrapiDBAccess(this);
signIn();
}
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
try {
...
if (acct != null) {
....
boolean result = accessDB.Login(parcelAccess.personEmail, "*******");
tvAuth.setText(tvAuth.getText()+" "+**accessDB.getRetro()**); //
}
} catch (ApiException e) {
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
parcelAccess.signedIn = false;
parcelAccess.personName = "Anónimo";
Toast.makeText(this, "Error de autenticación con Google. Chequee que tiene internet e inténtelo de nuevo.", Toast.LENGTH_SHORT).show();
}
}
I found the answer to my doubt. It is impossible to do by a field, or getter or any direct way. It is neccesary to implement an interface for success or error. It would be this way:
Class B
public void Login(final String user, final String pass, final VolleyCallback callback){
Retro = "";
stringRequest = new StringRequest(Request.Method.POST, Url + strLogin,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
***callback.onSuccess("Done");***
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Retro = Retro + String.copyValueOf(error.getMessage().toCharArray());
***callback.onError(Retro);***
//error.getMessage()
}
}) {
#Override
protected Map<String, String> getParams(){
Map<String, String> parameters = new HashMap<>();
parameters.put("identifier", user);
parameters.put("password", pass);
return parameters;
}
};
// Add the request to the RequestQueue.
requestQueue.add(stringRequest);
Toast.makeText(context, "Error de acceso: "+ErrorCode, Toast.LENGTH_LONG).show();
}
Class A
accessDB.Login(parcelAccess.personEmail, "************", new StrapiDBAccess.VolleyCallback(){
#Override
public void onSuccess(String result) {
}
#Override
public void onError(String error)
//no pudo ingresar
}
}
});
Well, I hope to help anyone who has this kind of trouble
I am making android app with gcm integration for group chatting and messages broadcasting. But when I'm executing it, application showing an error:
json parsing error: Value true at error of type java.lang.Boolean cannot be converted to JSONObject
LoginActivity.java:
public class LoginActivity extends AppCompatActivity {
private String TAG = LoginActivity.class.getSimpleName();
private EditText inputName, inputEmail;
private TextInputLayout inputLayoutName, inputLayoutEmail;
private Button btnEnter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/**
* Check for login session. It user is already logged in
* redirect him to main activity
* */
if (MyApplication.getInstance().getPrefManager().getUser() != null) {
startActivity(new Intent(this, MainActivity.class));
finish();
}
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
inputLayoutName = (TextInputLayout) findViewById(R.id.input_layout_name);
inputLayoutEmail = (TextInputLayout) findViewById(R.id.input_layout_email);
inputName = (EditText) findViewById(R.id.input_name);
inputEmail = (EditText) findViewById(R.id.input_email);
btnEnter = (Button) findViewById(R.id.btn_enter);
inputName.addTextChangedListener(new MyTextWatcher(inputName));
inputEmail.addTextChangedListener(new MyTextWatcher(inputEmail));
btnEnter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
login();
}
});
}
/**
* logging in user. Will make http post request with name, email
* as parameters
*/
private void login() {
if (!validateName()) {
return;
}
if (!validateEmail()) {
return;
}
final String name = inputName.getText().toString();
final String email = inputEmail.getText().toString();
StringRequest strReq = new StringRequest(Request.Method.POST,
EndPoints.LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e(TAG, "response: " + response);
try {
JSONObject obj = new JSONObject(response);
// check for error flag
if (obj.getBoolean("error") == false) {
// user successfully logged in
JSONObject userObj = obj.getJSONObject("user");
User user = new User(userObj.getString("user_id"),
userObj.getString("name"),
userObj.getString("email"));
// storing user in shared preferences
MyApplication.getInstance().getPrefManager().storeUser(user);
// start main activity
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
} else {
// login error - simply toast the message
Toast.makeText(getApplicationContext(), "" + obj.getJSONObject("error").getString("message"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Log.e(TAG, "json parsing error: " + e.getMessage());
Toast.makeText(getApplicationContext(), "Json parse error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
Log.e(TAG, "Volley error: " + error.getMessage() + ", code: " + networkResponse);
Toast.makeText(getApplicationContext(), "Volley error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("name", name);
params.put("email", email);
Log.e(TAG, "params: " + params.toString());
return params;
}
};
//Adding request to request queue
MyApplication.getInstance().addToRequestQueue(strReq);
}
private void requestFocus(View view) {
if (view.requestFocus()) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
// Validating name
private boolean validateName() {
if (inputName.getText().toString().trim().isEmpty()) {
inputLayoutName.setError(getString(R.string.err_msg_name));
requestFocus(inputName);
return false;
} else {
inputLayoutName.setErrorEnabled(false);
}
return true;
}
// Validating email
private boolean validateEmail() {
String email = inputEmail.getText().toString().trim();
if (email.isEmpty() || !isValidEmail(email)) {
inputLayoutEmail.setError(getString(R.string.err_msg_email));
requestFocus(inputEmail);
return false;
} else {
inputLayoutEmail.setErrorEnabled(false);
}
return true;
}
private static boolean isValidEmail(String email) {
return !TextUtils.isEmpty(email) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
private class MyTextWatcher implements TextWatcher {
private View view;
private MyTextWatcher(View view) {
this.view = view;
}
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
public void afterTextChanged(Editable editable) {
switch (view.getId()) {
case R.id.input_name:
validateName();
break;
case R.id.input_email:
validateEmail();
break;
}
}
}
}
Because the response you are getting it not properly formatted for Json conversion.
JSONObject obj = new JSONObject(response);
Its returning boolean which you are trying to convert into JSONObject.
Edit 1: It might also occur that there is problem while fetching boolean.
Try to fetch it like this:
jsonObject.optBoolean("error");