android studio com.android.volley.clienterror - java

its giving me a error that is called com.android.volley.clienterror
whenever i press the register or login button. I imagine that the
error could be that my android app isnt connected to my database but
idk.................................................................................................................................................................................................................
import android.content.Intent;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.Map;
public class register extends AppCompatActivity {
private EditText etName, etEmail, etPassword, etReenterPassword;
private TextView tvStatus;
private Button btnRegister;
private String URL = "http://10.0.2.2/login.register.php";
private String name, email, password, reenterPassword;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
etName = findViewById(R.id.etName);
etEmail = findViewById(R.id.etEmail);
etPassword = findViewById(R.id.etPassword);
etReenterPassword = findViewById(R.id.etReenterPassword);
tvStatus = findViewById(R.id.tvStatus);
btnRegister = findViewById(R.id.btnRegister);
name = email = password = reenterPassword = "";
}
public void save(View view){
name = etName.getText().toString().trim();
email = etEmail.getText().toString().trim();
password = etPassword.getText().toString().trim();
reenterPassword = etReenterPassword.getText().toString().trim();
if(!password.equals(reenterPassword)){
Toast.makeText(this , "Password mismatch", Toast.LENGTH_SHORT).show();
}
else if(!name.equals("")&& !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")) {
tvStatus.setText("Successfully registered");
btnRegister.setClickable(false);
} else if (response.equals("failure")) {
tvStatus.setText("something went wrong!");
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.toString().trim(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> data = new HashMap<>();
data.put("name", name);
data.put("email", email);
data.put("password", password);
return data;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
}
public void login(View view){
Intent intent = new Intent (this, MainActivity.class);
startActivity(intent);
finish();
}
}

Related

My Quiz App is crashing when I load Categories from Firebase Firestore but able to recieve users data to firestore from App

When I try to load categories in any activity the quizapp is getting crashed when i load. But when i send users data to firestore, its working.
All the data set in DbQuery.java matches the names entered with Firestore data. But There is something wrong in this that whenever I load this data in login Activity, signup activity or splash activity the app is getting crashed.
Here is my code:
DbQuery.java
package com.nightout.ttsgeneralawareness;
import android.content.Intent;
import android.util.ArrayMap;
import androidx.annotation.NonNull;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FieldValue;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import com.google.firebase.firestore.WriteBatch;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class DbQuery {
public static FirebaseFirestore g_firestore;
public static List<CategoryModel> g_catList = new ArrayList<>();
public static void createUserData(String email, String name, MyCompleteListener completeListener) {
Map<String, Object> userData = new ArrayMap<>();
userData.put("EMAIL_ID", email);
userData.put("NAME", name);
userData.put("TOTAL_SCORE", 0);
DocumentReference userDoc = g_firestore.collection("USERS")
.document(Objects.requireNonNull(FirebaseAuth.getInstance().getCurrentUser()).getUid());
WriteBatch batch = g_firestore.batch();
batch.set(userDoc, userData);
DocumentReference countDoc = g_firestore.collection("USERS").document("TOTAL_USERS");
batch.update(countDoc, "COUNT", FieldValue.increment(1));
batch.commit()
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
completeListener.onSuccess();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
completeListener.onFailure();
}
});
}
public static void loadCategories(MyCompleteListener completeListener) {
g_catList.clear();
g_firestore.collection("QUIZ").get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
Map<String, QueryDocumentSnapshot> docList = new ArrayMap<>();
for (QueryDocumentSnapshot doc : queryDocumentSnapshots) {
docList.put(doc.getId(), doc);
}
QueryDocumentSnapshot catListDooc = docList.get("Categories");
long catCount = catListDooc.getLong("COUNT");
for (int i = 1; i <= catCount; i++) {
String catID = catListDooc.getString("CAT" + String.valueOf(i) + "_ID");
QueryDocumentSnapshot catDoc = docList.get(catID);
int noOfTest = catDoc.getLong("NO_OF_TESTS").intValue();
String catName = catDoc.getString("NAME");
g_catList.add(new CategoryModel(catID, catName, noOfTest));
}
completeListener.onSuccess();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
completeListener.onFailure();
}
});
}
LoginActivity.java
package com.nightout.ttsgeneralawareness;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import java.util.Locale;
public class LoginActivity extends AppCompatActivity {
private EditText email, password;
private Button loginButton;
private TextView forgotpwd, signup_button;
private FirebaseAuth mAuth;
private Dialog progressDialog;
private TextView dialogText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
getSupportActionBar().hide();
email = findViewById(R.id.email);
password = findViewById(R.id.password);
loginButton = findViewById(R.id.login_button);
forgotpwd = findViewById(R.id.forgot_pwd);
signup_button = findViewById(R.id.signup_button);
//google
progressDialog = new Dialog(LoginActivity.this);
progressDialog.setContentView(R.layout.dialog);
progressDialog.setCancelable(false);
progressDialog.getWindow().setLayout(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
dialogText = progressDialog.findViewById(R.id.dialog_text);
dialogText.setText("Signing in...");
mAuth = FirebaseAuth.getInstance();
//google
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (validData())
{
login();
}
}
});
signup_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(LoginActivity.this, SignUpActivity.class);
startActivity(intent);
}
});
}
private boolean validData()
{
if (email.getText().toString().isEmpty())
{
email.setError("Enter E-Mail ID");
return false;
}
if (password.getText().toString().isEmpty())
{
password.setError("Enter Password");
return false;
}
return true;
}
private void login()
{
progressDialog.show();
mAuth.signInWithEmailAndPassword(email.getText().toString().trim(), password.getText().toString().trim())
.addOnCompleteListener(this, task -> {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Toast.makeText(LoginActivity.this,"Login Success",Toast.LENGTH_SHORT).show();
DbQuery.loadCategories(new MyCompleteListener() {
#Override
public void onSuccess() {
progressDialog.dismiss();
Intent intent = new Intent(LoginActivity.this,MainActivity.class);
startActivity(intent);
LoginActivity.this.finish();
}
#Override
public void onFailure() {
progressDialog.dismiss();
Toast.makeText(LoginActivity.this,"Something Went Wrong!",Toast.LENGTH_SHORT).show();
}
});
} else {
progressDialog.dismiss();
// If sign in fails, display a message to the user.
Toast.makeText(LoginActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
}

I am having problem uploading user data on firestore during time of registration using firebase authentication

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FieldValue;
import com.google.firebase.firestore.FirebaseFirestore;
import java.util.HashMap;
import java.util.Map;
public class Register extends AppCompatActivity {
Button btn2_signup;
Button btn_login;
EditText e_mail, pass_word,phone_number;
public EditText user_name;
FirebaseAuth mAuth;
FirebaseFirestore fStore;
public static String username;
String userID;
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
e_mail=findViewById(R.id.email);
pass_word=findViewById(R.id.password1);
user_name=findViewById(R.id.username);
phone_number=findViewById(R.id.phone_number);
btn2_signup=findViewById(R.id.sign);
btn_login = findViewById(R.id.login);
mAuth=FirebaseAuth.getInstance();
btn2_signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = e_mail.getText().toString().trim();
String password= pass_word.getText().toString().trim();
if(email.isEmpty())
{
e_mail.setError("Email is empty");
e_mail.requestFocus();
return;
}
if(!Patterns.EMAIL_ADDRESS.matcher(email).matches())
{
e_mail.setError("Enter the valid email address");
e_mail.requestFocus();
return;
}
if(password.isEmpty())
{
pass_word.setError("Enter the password");
pass_word.requestFocus();
return;
}
if(password.length()<6)
{
pass_word.setError("Length of the password should be more than 6");
pass_word.requestFocus();
return;
}
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
username = user_name.getText().toString();
Toast.makeText(Register.this,"You are successfully Registered", Toast.LENGTH_SHORT).show();
Intent i = new Intent(Register.this,Login.class);
startActivity(i);
}
else
{
Toast.makeText(Register.this,"You are not Registered! Try again",Toast.LENGTH_SHORT).show();
}
}
});
}
});
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Register.this,Login.class);
startActivity(i);
}
});
}
public void uploadUserData(){
String email = e_mail.getText().toString();
String phoneNumber = phone_number.getText().toString();
userID = mAuth.getCurrentUser().getUid();
CollectionReference collectionReference = fStore.collection("Users data");
Map<String,Object> user = new HashMap<>();
user.put("timestamp", FieldValue.serverTimestamp());
user.put("userid",userID);
user.put("email",email);
user.put("phoneNumber",phoneNumber);
collectionReference.add(user)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(),"Error!",Toast.LENGTH_SHORT).show();
//Log.w(TAG, "Error!", e);
}
});
}
}
I want to upload the user data on firestore during the time of registration of user using firebase authentication. I have created a method called uploadUserData() but when its called from createUserWithEmailAndPassword in onComplete method the app stops. Can someone please point out the errors in code and the changes required.

how do I pass an u_id value to another activity?

Here is my main file where i get u_id and other data but i pass u_id text to other activity
Mainactivity.java
package com.desktop.app;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.desktop.app.Stitle.EXTRA_TITLE;
public class MainActivity extends AppCompatActivity {
Button signup,login,learnmore ;
EditText ed1,ed2,u_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signup = (Button) findViewById(R.id.signupbutton);
learnmore = (Button) findViewById(R.id.learnmore);
login = (Button) findViewById(R.id.loginbutton);
ed1 = (EditText) findViewById(R.id.emailedittext);
u_id = (EditText) findViewById(R.id.uid);
ed2 = (EditText) findViewById(R.id.passwordedittext);
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent in = new Intent(MainActivity.this,Activity2.class);
startActivity(in);
}
});
learnmore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent in = new Intent(MainActivity.this,Activity1.class);
startActivity(in);
}
});
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = ed1.getText().toString().trim();
String password = ed2.getText().toString().trim();
final String log_id = u_id.getText().toString();
if(email.isEmpty()){
ed1.setError("Fill this field");
ed1.requestFocus();
return;
}
if(password.isEmpty()){
ed2.setError("Fill this field");
ed2.requestFocus();
return;
}
if(log_id.isEmpty()){
u_id.setError("Fill this field");
u_id.requestFocus();
return;
}
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
login();
Intent i = new Intent (MainActivity.this,fullview.class);
Bundle b =new Bundle();
b.putString("text", String.valueOf(u_id));
i.putExtras(b);
startActivity(i);
}
});
}
private void login(){
String url= "http://192.168.0.136/fyp/andr_log.php";
final RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.trim().equals("Login Successfull")){
Toast.makeText(getApplicationContext(), "Login Successfull",Toast.LENGTH_LONG).show();
Intent in = new Intent(MainActivity.this,Search.class);
startActivity(in);
}
else {
Toast.makeText(getApplicationContext(), "Login Unsuccessfull",Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "error:" +error.toString() ,Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Email", ed1.getText().toString().trim() );
params.put("uid", u_id.getText().toString().trim() );
params.put("Password", ed2.getText().toString().trim() );
return params;
}
};
requestQueue.add(stringRequest);
}});
}
}
fullview.java
package com.desktop.app;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static android.support.v7.app.AlertDialog.*;
import static com.desktop.app.Stitle.EXTRA_AUTHOR;
import static com.desktop.app.Stitle.EXTRA_HR;
import static com.desktop.app.Stitle.EXTRA_PUBLISHER;
import static com.desktop.app.Stitle.EXTRA_PUBY;
import static com.desktop.app.Stitle.EXTRA_ACC;
import static com.desktop.app.Stitle.EXTRA_RAK;
import static com.desktop.app.Stitle.EXTRA_STATUS;
import static com.desktop.app.Stitle.EXTRA_TITLE;
import static com.desktop.app.Stitle.EXTRA_VR;
public class fullview extends AppCompatActivity {
Button location, avail, request;
TextView textviewtitle, textviewauthors, textviewpublisher, textviewpubyear,textviewacc,u_id;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fullview);
Intent intent = getIntent();
Bundle b = getIntent().getExtras();
String id= b.getString("text");
u_id= findViewById(R.id.uid);
String title = intent.getStringExtra(EXTRA_TITLE);
String author = intent.getStringExtra(EXTRA_AUTHOR);
String publisher = intent.getStringExtra(EXTRA_PUBLISHER);
int puby = intent.getIntExtra(EXTRA_PUBY,0);
int accc = intent.getIntExtra(EXTRA_ACC,0);
final int rak = intent.getIntExtra(EXTRA_RAK,0);
final int hr = intent.getIntExtra(EXTRA_HR,0);
final int vr = intent.getIntExtra(EXTRA_VR,0);
final String status = intent.getStringExtra(EXTRA_STATUS);
textviewtitle = findViewById(R.id.textviewtitle);
textviewauthors = findViewById(R.id.textviewauthors);
textviewpublisher = findViewById(R.id.textviewpublisher);
textviewpubyear = findViewById(R.id.textviewpubyear);
textviewacc = findViewById(R.id.textviewacc);
textviewtitle.setText(title);
textviewauthors.setText(author);
textviewpublisher.setText(publisher);
textviewpubyear.setText(String.valueOf(puby));
textviewacc.setText(String.valueOf(accc));
location = findViewById(R.id.loc);
location.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
{
AlertDialog.Builder builder=new AlertDialog.Builder(fullview.this);
builder.setTitle("Location");
builder.setMessage("Rak-No :: " + rak + "\nColumn :: " + hr +"\nRow :: " + vr);
AlertDialog alertDialog=null;
builder.setPositiveButton("Close", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(fullview.this,"Closed",Toast.LENGTH_SHORT).show();
}
});
alertDialog=builder.create();
alertDialog.show();
}
}
});
avail = findViewById(R.id.avail);
avail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
AlertDialog.Builder builder=new AlertDialog.Builder(fullview.this);
{
if (status.equals("yes")) {
builder.setTitle("Availablity");
builder.setMessage("Available");
} else {
builder.setTitle("Availablity");
builder.setMessage("Not Available");
}
}
AlertDialog alertDialog=null;
builder.setPositiveButton("Close", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(fullview.this,"Closed",Toast.LENGTH_SHORT).show();
}
});
alertDialog=builder.create();
alertDialog.show();
}
});
request= findViewById(R.id.request);
request.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
request();
}
});
}
private void request(){
String url= "http://192.168.0.136/fyp/bookreq.php";
final RequestQueue requestQueue = Volley.newRequestQueue(fullview.this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.trim().equals("successfull")){
Toast.makeText(getApplicationContext(), "Go to Admin For Approval",Toast.LENGTH_LONG).show();
Intent in = new Intent(fullview.this,Search.class);
startActivity(in);
}
else {
Toast.makeText(getApplicationContext(), "Already Requested",Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "error:" +error.toString() ,Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Title", textviewtitle.getText().toString().trim());
params.put("Author", textviewauthors.getText().toString().trim());
params.put("Publisher", textviewpublisher.getText().toString().trim());
params.put("Acc", textviewacc.getText().toString().trim());
params.put("Puby", textviewpubyear.getText().toString().trim());
Log.i("Info",textviewtitle.getText().toString().trim());
return params;
}
};
requestQueue.add(stringRequest);
}
}
Here is my second file above where i want to shoe u_id text but i done with this to pass u_id text to other activity
Intent i = new Intent (MainActivity.this,fullview.class);
Bundle b =new Bundle();
b.putString("text", String.valueOf(u_id));
i.putExtras(b);
startActivity(i);
this code i use to pass u_id text and next activity code i use below code
Bundle b = getIntent().getExtras();
String id= b.getString("text");
u_id= findViewById(R.id.uid);
This is what your problem is.
Intent i = new Intent (MainActivity.this,fullview.class);
Bundle b =new Bundle();
b.putString("text", String.valueOf(u_id));
i.putExtras(b);
startActivity(i);
Change this line
b.putString("text", String.valueOf(u_id));
to
b.putString("text", u_id.getText().toString().trim());
EDIT:
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = ed1.getText().toString().trim();
String password = ed2.getText().toString().trim();
final String log_id = u_id.getText().toString();
if(email.isEmpty()){
ed1.setError("Fill this field");
ed1.requestFocus();
}else if(password.isEmpty()){
ed2.setError("Fill this field");
ed2.requestFocus();
} else if(log_id.isEmpty()){
u_id.setError("Fill this field");
u_id.requestFocus();
} else {
login();
Intent i = new Intent(MainActivity.this,fullview.class);
Bundle b =new Bundle();
b.putString("text", u_id.getText().toString().trim());
i.putExtras(b);
startActivity(i);
}
}

Getting "java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()" in Firebase

Image of DB in firebase console
I don't really know what's wrong here, I am able to add data on the other activity. I am getting error "java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()" and don't know how to fix. There are 3 other classes created only one other is adding data to firebase realtime database storage.
package com.example.akshay.katiroll.FirstScreen;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.akshay.katiroll.R;
import com.example.akshay.katiroll.SecondScreen.welcome;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class Profile extends AppCompatActivity {
EditText fName, lName, PhNo, BDay, Zip;
Button svBtn;
DatabaseReference mDataReference;
String keyUser;
String fNameStr, lNameStr, PhNoStr, BDayStr, ZipStr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
keyUser = getIntent().getStringExtra("USER_KEY");
mDataReference = FirebaseDatabase.getInstance().getReference().child("Users").child(keyUser);//error in this line
fName = (EditText) findViewById(R.id.fName);
lName = (EditText) findViewById(R.id.lName);
PhNo = (EditText) findViewById(R.id.phno);
BDay = (EditText) findViewById(R.id.bday);
Zip = (EditText) findViewById(R.id.zip);
svBtn = (Button) findViewById(R.id.svBtn);
svBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fNameStr = fName.getText().toString();
lNameStr = lName.getText().toString();
PhNoStr = PhNo.getText().toString();
BDayStr = BDay.getText().toString();
ZipStr = Zip.getText().toString();
if(!TextUtils.isEmpty(fNameStr) && !TextUtils.isEmpty(lNameStr) && !TextUtils.isEmpty(PhNoStr)) {
DatabaseReference mDataRef = mDataReference.child("Users").push();
mDataRef.child("firstName").setValue(""+fNameStr);
mDataRef.child("lastName").setValue(""+lNameStr);
mDataRef.child("phoneNumber").setValue(""+PhNoStr);
mDataRef.child("isVerified").setValue("verified");
if(!TextUtils.isEmpty(BDayStr)){
mDataRef.child("birthday").setValue(""+BDayStr);
}else{
mDataRef.child("birthday").setValue("null");
}
if(!TextUtils.isEmpty(ZipStr)){
mDataRef.child("zipcode").setValue("ZipStr");
}else{
mDataRef.child("zipcode").setValue("null");
}
Toast.makeText(Profile.this, "User profile added", Toast.LENGTH_LONG).show();
startActivity(new Intent(Profile.this, welcome.class));
}else{
Toast.makeText(Profile.this, "Failed to create User Account", Toast.LENGTH_LONG).show();
}
}
});
}
}
package com.example.akshay.katiroll.FirstScreen;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.akshay.katiroll.R;
import com.example.akshay.katiroll.SecondScreen.welcome;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.Iterator;
public class katiRoll extends AppCompatActivity {
EditText userEdit;
EditText passEdit;
String sUser, sPass;
Button sign;
Button reg;
Boolean signInVLogIn;
FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener mAuthListener;
DatabaseReference mDatabaseRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_kati_roll);
float Re = 255;
float Gr = 148;
float Bl = 0;
userEdit = (EditText)findViewById(R.id.user);
passEdit = (EditText)findViewById(R.id.pass);
sign = (Button) findViewById(R.id.sign);
reg = (Button) findViewById(R.id.reg);
userEdit.setTextColor(Color.rgb(Re,Gr,Bl));
passEdit.setTextColor(Color.rgb(Re,Gr,Bl));
sign.setTextColor(Color.rgb(Re,Gr,Bl));
reg.setTextColor(Color.rgb(Re,Gr,Bl));
mAuth = FirebaseAuth.getInstance();
mDatabaseRef = FirebaseDatabase.getInstance().getReference().child("Users");
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if(!TextUtils.isEmpty(sUser) && !TextUtils.isEmpty(sPass)){
signInVLogIn = true;
}else{
signInVLogIn = false;
}
if(user != null && signInVLogIn) {
}else{
//Toast.makeText(katiRoll.this, "Log In Failed", Toast.LENGTH_LONG).show();
}
}
};
sign.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sUser = userEdit.getText().toString().trim();
sPass = passEdit.getText().toString().trim();
if(!TextUtils.isEmpty(sUser) && !TextUtils.isEmpty(sPass))
{
mAuth.signInWithEmailAndPassword(sUser, sPass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
mDatabaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
checkUserValidation(dataSnapshot, sUser);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}else{
Toast.makeText(katiRoll.this, "User Login Doesn't Exist" , Toast.LENGTH_LONG).show();
}
}
});
}
}
});
reg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(katiRoll.this, signUp.class));
}
});
}
private void checkUserValidation(DataSnapshot dataSnapshot, String emailForVer) {
Iterator iterator = dataSnapshot.getChildren().iterator();
while (iterator.hasNext())
{
DataSnapshot dataUser = (DataSnapshot)iterator.next();
if (dataUser.child("emailUser").getValue().toString().equals(emailForVer)){
if(dataUser.child("isVerified").getValue().toString().equals("unverified"))
{
Intent in = new Intent(katiRoll.this, Profile.class);
in.putExtra("USER KEY", dataUser.child("userKey").getValue().toString());
startActivity(in);
Log.d("USERKEY",dataUser.child("userKey").getValue().toString());
}
else{
startActivity(new Intent(katiRoll.this, welcome.class));
}
}
}
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
protected void onStop() {
super.onStop();
if(mAuthListener !=null){
mAuth.removeAuthStateListener(mAuthListener);
}
}
}
package com.example.akshay.katiroll.FirstScreen;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.akshay.katiroll.SecondScreen.welcome;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.example.akshay.katiroll.R;
import com.google.firebase.database.ValueEventListener;
import java.util.Iterator;
public class signUp extends AppCompatActivity {
EditText nUser, nPass;
Button registerBtn, backToMain;
ImageButton passVis;
FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener mAuthListener;
DatabaseReference mDatabaseRef, mUserCheckData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
nUser = (EditText) findViewById(R.id.nUser);
nPass = (EditText) findViewById(R.id.nPass);
registerBtn = (Button) findViewById(R.id.registerBtn);
backToMain = (Button) findViewById(R.id.backToMain);
passVis = (ImageButton)findViewById(R.id.passVis);
passVis.setImageResource(R.drawable.open);
passVis.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Drawable drawable = passVis.getDrawable();
if(drawable.getConstantState().equals(getResources().getDrawable(R.drawable.open,null).getConstantState())){
passVis.setImageResource(R.drawable.closed);
nPass.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
}else{
passVis.setImageResource(R.drawable.open);
nPass.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_WEB_PASSWORD);
}
}
});
float Re = 255;
float Gr = 148;
float Bl = 0;
nUser.setTextColor(Color.rgb(Re, Gr, Bl));
nPass.setTextColor(Color.rgb(Re, Gr, Bl));
registerBtn.setTextColor(Color.rgb(Re, Gr, Bl));
backToMain.setTextColor(Color.rgb(Re, Gr, Bl));
mAuth = FirebaseAuth.getInstance();
mDatabaseRef = FirebaseDatabase.getInstance().getReference();
mUserCheckData = FirebaseDatabase.getInstance().getReference().child("User");
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
final String emailForVer = user.getEmail();
mUserCheckData.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
checkForValidation(dataSnapshot, emailForVer);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
Log.d("TAG", "onAuthStateChanged:signed_out");
}
}
};
registerBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String nUserString, nPassString;
nUserString = (nUser.getText().toString().trim());
nPassString = (nPass.getText().toString().trim());
if(nPassString.length()>=6){
if (!TextUtils.isEmpty(nUserString) && !TextUtils.isEmpty(nPassString)) {
mAuth.createUserWithEmailAndPassword(nUserString, nPassString).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
DatabaseReference mChildDatabase = mDatabaseRef.child("Users").push();
String key_user = mChildDatabase.getKey();
mChildDatabase.child("isVerified").setValue("unverified");
mChildDatabase.child("userKey").setValue(key_user);
mChildDatabase.child("EmailUser").setValue(nUserString);
mChildDatabase.child("PasswordUser").setValue(nPassString);
Toast.makeText(signUp.this, "User Account Created, Check Email For Confirmation", Toast.LENGTH_LONG).show();
FirebaseUser user = mAuth.getCurrentUser();
if (user != null) {
user.sendEmailVerification();
}
startActivity(new Intent(signUp.this, Profile.class));
} else {
Toast.makeText(signUp.this, "Failed to create User Account", Toast.LENGTH_LONG).show();
}
}
});
} else {
Toast.makeText(signUp.this, "Failed to create User Account", Toast.LENGTH_LONG).show();
}
}else {
Toast.makeText(signUp.this, "Failed to create User Account", Toast.LENGTH_LONG).show();
}
}
});
backToMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(signUp.this, katiRoll.class));
}
});
}
private void checkForValidation(DataSnapshot dataSnapshot, String emailForVer) {
Iterator iterator = dataSnapshot.getChildren().iterator();
while (iterator.hasNext())
{
DataSnapshot dataUser = (DataSnapshot)iterator.next();
if (dataUser.child("emailUser").getValue().toString().equals(emailForVer)){
if(dataUser.child("isVerified").getValue().toString().equals("unverified"))
{
Intent in = new Intent(signUp.this, Profile.class);
in.putExtra("USER KEY", dataUser.child("userKey").getValue().toString());
startActivity(in);
Log.d("USERKEY",dataUser.child("userKey").getValue().toString());
}
else{
startActivity(new Intent(signUp.this, welcome.class));
}
}
}
}
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
protected void onStop() {
super.onStop();
if(mAuthListener !=null){
mAuth.removeAuthStateListener(mAuthListener);
}
}
}
package com.example.akshay.katiroll.SecondScreen;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.example.akshay.katiroll.FirstScreen.katiRoll;
import com.example.akshay.katiroll.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class welcome extends AppCompatActivity {
Button logOutBtn;
FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener mAuthListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
float Re = 255;
float Gr = 148;
float Bl = 0;
logOutBtn = (Button)findViewById(R.id.logOutBtn);
logOutBtn.setTextColor(Color.rgb(Re,Gr,Bl));
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user !=null) {
}else{
}
}
};
logOutBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mAuth.signOut();
finish();
startActivity(new Intent(welcome.this, katiRoll.class));
}
});
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
protected void onStop() {
super.onStop();
mAuth.removeAuthStateListener(mAuthListener);
}
}
The problem that is telling to you is that you are doing wrong the reference, you are trying to get something inside Firebase Database that is not there
This line is telling you that the child("Users").child(KeyUser); does not exist in your current DB structure
To fix this you should see your databse structure and then redo your reference.
if you post a photo of your Firebase DB i will be glad to refactor your code to your needs.
also here you are getting wrong your USER_KEY
keyUser = getIntent().getStringExtra("USER_KEY");
To fix this a short way would be doing this
keyUser = getIntent().getExtras().getString("USER_KEY");
you are geting an intent from where? if you are trying to get a putExtra from another Activity, you are doing it wrong, post where you are seting the extra ("USER_KEY");
Intent.getStringExtra() and Intent.getExtras() returns null if there are no extras, so you need to check for that before trying to call getString()
one quick example to check for extras first would be this
String keyUser;
Bundle extras = getIntent().getExtras();
if(extras == null) {
Log.e("keyUser is null","");
} else {
keyUser= extras.getString("USER_KEY");
}
happy coding

Login Module doesn't work

I am developing an android application with help of:
https://www.youtube.com/watch?v=T7Z4GVFaT4A&list=PLe60o7ed8E-TztoF2K3y4VdDgT6APZ0ka&index=4
When I reciprocated the same tutorial, the application worked absolutely fine. Then I modulated the application to fit into my application idea. The Registration was successful and stored data into db as expected.
But facing issue in LoginActivity.
Expected way the app should proceed: When I click blogin button, it should validate the user stored in db and open corresponding AdminViewActivity.
What actually happening is that when i click the button blogin, nothing happens. The table name is "allusers" and already contains values. I type the same values while logging in through my application.
Please help me find where I could have gone wrong. Thanks in advance.
LoginActivity.java
package com.example.android.ablo;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class LoginActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final Button bregister = (Button) findViewById(R.id.bregister);
final Button blogin = (Button) findViewById(R.id.blogin);
final EditText etusername=(EditText)findViewById(R.id.etusername);
final EditText etpassword=(EditText)findViewById(R.id.etpassword);
bregister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(LoginActivity.this, RegisterActivity.class);
LoginActivity.this.startActivity(i);
}
});
blogin.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
final String username=etusername.getText().toString();
final String password=etpassword.getText().toString();
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){
String name= jsonResponse.getString("name");
Intent i=new Intent(LoginActivity.this,AdminViewActivity.class);
i.putExtra("name",name);
LoginActivity.this.startActivity(i);
}else{
AlertDialog.Builder builder= new AlertDialog.Builder(LoginActivity.this);
builder.setMessage("Login Failed").setNegativeButton("Retry",null).create().show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
LoginRequest loginRequest=new LoginRequest(username,password,responseListener );
RequestQueue queue= Volley.newRequestQueue(LoginActivity.this);
queue.add(loginRequest);
}
});
}
}
LoginRequest.java
package com.example.android.ablo;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import java.util.HashMap;
import java.util.Map;
/**
* Created by User on 21-01-2018.
*/
public class LoginRequest extends StringRequest {
private static final String LOGIN_REQUEST_URL = "http://ablo.000webhostapp.com/AbloLogin.php";
private Map<String,String> params;
public LoginRequest( String username, String password, Response.Listener<String> listener){
super(Request.Method.POST, LOGIN_REQUEST_URL, listener, null );
params= new HashMap<>();
params.put("username",username);
params.put("password",password);
}
#Override
public Map<String, String> getParams() {
return params;
}
}
AbloLogin.php
<?php
$con = mysqli_connect("localhost", "id4335430_ablo_users", "wontreveal", "id4335430_ablo_users");
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "SELECT * FROM allusers WHERE username = ? AND password = ?");
mysqli_stmt_bind_param($statement, "ss", $username, $password);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $allusersID, $name, $username, $password);
$response = array();
$response["success"] = false;
while(mysqli_stmt_fetch($statement)){
$response["success"] = true;
$response["name"] = $name;
$response["username"] = $username;
$response["password"] = $password;
}
echo json_encode($response);
?>
AdminViewActivity.java
package com.example.android.ablo;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.w3c.dom.Text;
public class AdminViewActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_view);
final Button badduser = (Button) findViewById(R.id.badduser);
final Button bmanageusers = (Button) findViewById(R.id.bmanageusers);
final TextView tvadmin =(TextView) findViewById(R.id.tvadmin);
Intent i= getIntent();
String name= i.getStringExtra("name");
String message= name+ "'s Admin View";
tvadmin.setText(message);
badduser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(AdminViewActivity.this, CreateUserActivity.class);
AdminViewActivity.this.startActivity(i);
}
});
bmanageusers.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(AdminViewActivity.this, ManageUsersActivity.class);
AdminViewActivity.this.startActivity(i);
}
});
}
}

Categories