The message I receive is saying that
java.lang.String required
The highlighted line in the code is Common.CurrentUser=login; which is in the signIn method of MainActivity.
I am a beginner plz help me in this. thanks in advance. is there any problem with my Intent? how can i debug this? sholud i use "debug" option in android studio?
MainActivity
package sonu.enigma;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
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 com.rengwuxian.materialedittext.MaterialEditText;
import sonu.enigma.Common.Common;
import sonu.enigma.Model.User;
import static sonu.enigma.R.drawable.l;
public class MainActivity extends AppCompatActivity {
MaterialEditText edtNewUser, edtNewPassword, edtNewEmail; //for Sign Up
MaterialEditText edtUser, edtPassword; //for Sign In
Button btnSignUp, btnSignIn;
FirebaseDatabase database;
DatabaseReference users;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Firebase
database=FirebaseDatabase.getInstance();
users=database.getReference("Users");
edtUser=(MaterialEditText)findViewById(R.id.edtUserName);
edtPassword=(MaterialEditText)findViewById(R.id.edtPassword);
btnSignIn=(Button)findViewById(R.id.btn_sign_in);
btnSignUp=(Button)findViewById(R.id.btn_sign_up);
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showSignUpDialog();
}
});
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signIn(edtUser.getText().toString(), edtPassword.getText().toString());
}
});
}
private void signIn(final String user, final String pwd) {
users.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child(user).exists()){
if (!user.isEmpty()){
User login=dataSnapshot.child(user).getValue(User.class);
if (login.getPassword().equals(pwd)){
Intent homeActivity = new Intent(MainActivity.this, Home.class);
Common.CurrentUser=login;
startActivity(homeActivity);
finish();
}
else {
Toast.makeText(MainActivity.this, "Wrong Password", Toast.LENGTH_SHORT).show();
}
}
else {
Toast.makeText(MainActivity.this, "Please enter your User name", Toast.LENGTH_SHORT).show();
}
}
else{
Toast.makeText(MainActivity.this, "User is not exists!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void showSignUpDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
alertDialog.setTitle("Sign Up");
alertDialog.setMessage("Kindly, fill the information!");
LayoutInflater inflater= this.getLayoutInflater();
View sign_up_layout= inflater.inflate(R.layout.sign_up_layout, null);
edtNewUser=(MaterialEditText)sign_up_layout.findViewById(R.id.edtNewUserName);
edtNewEmail=(MaterialEditText)sign_up_layout.findViewById(R.id.edtNewEmail);
edtNewPassword=(MaterialEditText)sign_up_layout.findViewById(R.id.edtNewPassword);
alertDialog.setView(sign_up_layout);
alertDialog.setIcon(R.drawable.ic_account_circle_black_24dp);
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
final User user= new User(edtNewUser.getText().toString(),
edtNewPassword.getText().toString(),
edtNewEmail.getText().toString());
users.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child(user.getUserName()).exists())
Toast.makeText(MainActivity.this, "User already exists!", Toast.LENGTH_SHORT).show();
else {
users.child(user.getUserName())
.setValue(user);
Toast.makeText(MainActivity.this, "User Registration Successful!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
dialogInterface.dismiss();
}
});
alertDialog.show();
}
}
Why this error is showing? I m making a online quiz app using firebase as backend.
package sonu.enigma.Model;
/**
* Created by PAWAN on 01-10-2017.
*/
public class User {
private String userName;
private String password;
private String email;
public User(){
}
public User(String userName, String password, String email){
this.userName=userName;
this.password=password;
this.email =email;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
login is user data model.its not string .so Assign the string value
Use the code
Common.CurrentUser=login.getUserName();
instead of
Common.CurrentUser=login
Apparently the type of Common.CurrentUser is String and the type of login is not (is probably DataSnapshot). Try using something like Common.CurrentUser = login.getUserName();
OR change the type of field CurrentUser in the Common class from String to DataSnapshot
Related
currentonlineuser which I defined in Prevelent is returning null when clicking in cart button in details. class the getPhone is not returing anything even after initilizing it
this is code for details activity
private void addtocart() {
String saveCurrentDate, saveCurrentTime;
Calendar calForDate = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("MMM dd, yyyy");
saveCurrentDate = currentDate.format(calForDate.getTime());
SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss a");
saveCurrentTime = currentTime.format(calForDate.getTime());
final DatabaseReference cartListRef = FirebaseDatabase.getInstance().getReference().child("Cart List");
final HashMap<String, Object> cartMap = new HashMap<>();
cartMap.put("productName",nameholder.getText().toString());
cartMap.put("productPrice",emailholder.getText().toString());
cartMap.put("date",saveCurrentDate);
cartMap.put("time",saveCurrentTime);
cartMap.put("quantity",quantity.getText().toString());
if (**Prevalent.currentonlineUsers** != null) {
String phone = **Prevalent.currentonlineUsers.getPhone**();
cartListRef.child("Admin View").child(`Prevalent.currentonlineUsers.getPhone`())
.child("Products").child("productName")
.updateChildren(cartMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
cartListRef.child("user View").child(**Prevalent.currentonlineUsers.getPhone**())
.child("Products").child("productName")
.updateChildren(cartMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(details.this, "Added to cart", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(details.this,MainActivity.class);
startActivity(intent);
}
});
}
}
});
} else {
Toast.makeText(this, "ERROR", Toast.LENGTH_SHORT).show();
}
package com.example.register.Prevalent;
import com.example.register.Model.Users;
public class Prevalent {
public static Users currentonlineUsers;
public static final String UserPhoneKey = "UserPhone";
public static final String UserPasswordKey = "UserPassword";
}
this is the code of Users class
package com.example.register.Model;
public class Users {
private String name,phone,password;
public Users() {
}
public Users(String name, String phone, String password) {
this.name = name;
this.phone = phone;
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
this is the code of login class
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.register.Model.Users;
import com.example.register.Prevalent.Prevalent;
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 io.paperdb.Paper;
public class login extends AppCompatActivity {
private EditText InputPhoneNumber,InputPassword;
private ProgressDialog loadingBar;
private com.rey.material.widget.CheckBox chkbox;
private String parentDbName = "Users";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Button loginButton = (Button) findViewById(R.id.button);
InputPassword = (EditText) findViewById(R.id.password);
InputPhoneNumber = (EditText) findViewById(R.id.username);
loadingBar = new ProgressDialog(this);
chkbox = (com.rey.material.widget.CheckBox) findViewById(R.id.rembemberme);
Paper.init(this);
loginButton.setOnClickListener((new View.OnClickListener() {
#Override
public void onClick(View view) {
LoginUser();
}
}));
}
private void LoginUser() {
String phone = InputPhoneNumber.getText().toString();
String password = InputPassword.getText().toString();
if(TextUtils.isEmpty(phone)){
Toast.makeText(this, "Please write your phone", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(phone)){
Toast.makeText(this, "Please write your password", Toast.LENGTH_SHORT).show();
}
else {
loadingBar.setTitle("Login Account");
loadingBar.setMessage("wait");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
AllowAccessToAccount(phone,password);
}
}
private void AllowAccessToAccount(String phone, String password) {
final DatabaseReference RootRef;
RootRef = FirebaseDatabase.getInstance().getReference();
RootRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(snapshot.child(parentDbName).child(phone).exists()){
Paper.book().write(Prevalent.UserPhoneKey,phone);
Paper.book().write(Prevalent.UserPasswordKey,password);
Users usersdata = snapshot.child(parentDbName).child(phone).getValue(Users.class);
if(usersdata.getPhone().equals(phone)){
if(usersdata.getPassword().equals(password)){
Toast.makeText(login.this, "Logged IN Successfully", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
Intent intent = new Intent(login.this,test.class);
startActivity(intent);
}
}
else{
Toast.makeText(login.this, "Phone number do not exists", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
Toast.makeText(login.this, "create new acc.", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
this is the code of register if in case the error is related to this
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.Navigator;
import android.app.ProgressDialog;
import android.content.Intent;
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.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
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.HashMap;
public class register extends AppCompatActivity {
private Button CreateAccountButton;
private EditText InputName,InputPhoneNumber,InputPassword;
private ProgressDialog loadingBar;
Button exp;
//create obj of Databaserefrence to access firebase RealTime Database
DatabaseReference databaseReference ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CreateAccountButton =(Button) findViewById(R.id.sign);
InputName =(EditText) findViewById(R.id.Name);
InputPassword=(EditText) findViewById(R.id.password);
InputPhoneNumber=(EditText) findViewById(R.id.password);
loadingBar = new ProgressDialog(this);
CreateAccountButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CreateAccount();
}
});
}
private void CreateAccount() {
String name = InputName.getText().toString();
String phone = InputPhoneNumber.getText().toString();
String password = InputPassword.getText().toString();
if(TextUtils.isEmpty(name)){
Toast.makeText(this, "Please write your name", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(phone)){
Toast.makeText(this, "Please write your phone", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(phone)){
Toast.makeText(this, "Please write your password", Toast.LENGTH_SHORT).show();
}
else {
loadingBar.setTitle("Create Account");
loadingBar.setMessage("wait");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
ValidatephoneNumber(name,phone,password);
}
}
private void ValidatephoneNumber(String name, String phone, String password)
{
final DatabaseReference RootRef;
RootRef = FirebaseDatabase.getInstance().getReference();
RootRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot datasnapshot) {
if(!(datasnapshot.child("Users").child(phone).exists())){
HashMap<String,Object>userdataMap=new HashMap<>();
userdataMap.put("phone",phone);
userdataMap.put("password",password);
userdataMap.put("name",name);
RootRef.child("Users").child(phone).updateChildren(userdataMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
Toast.makeText(register.this, "ACCOUNT CREATED", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
Intent intent = new Intent(register.this,test.class);
startActivity(intent);
}
else {
Toast.makeText(register.this, "Networ Error", Toast.LENGTH_SHORT).show();
}
}
});
}
else {
Toast.makeText(register.this, "phone number already exists", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
Toast.makeText(register.this, "Enter new number", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
exp = (Button) findViewById(R.id.login);
exp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(register.this,login.class);
startActivity(intent);
}
});
}
}
it was giving the Error
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.register.Model.Users.getPhone()' on a null object reference
then I applied null check
its showing ERROR after clicking addtocart
I have a user class, which have a contactlist(friends). I want to add the possibility to add friends.
My database
In my code I have a addFriend method, which call a checkUser method. Here I check if the user exists so I can add him in the friend list. I am having difficulties implementing that, like how can I retrieve a variable from an anonymous class?
Here is my code.
package com.android.pfe.other;
import android.support.annotation.Keep;
import android.util.Log;
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.IgnoreExtraProperties;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import java.io.Serializable;
import java.util.Hashtable;
import java.util.List;
/**
* Created by SADA INFO on 13/04/2018.
*/
#IgnoreExtraProperties
#Keep
public class User implements Serializable {
private static final String TAG ="UserClass" ;
public String username;
public String email;
public Hashtable contact;
public String Uid;
public List article;
public DatabaseReference mDatabase;
public List<User> UserList;
public User uti;
public User() {
// Default constructor required for calls to DataSnapshot.getValue(com.android.pfe.other.User.class)
}
public User(String username, String email,String uid) {
this.username = username;
this.email = email;
this.contact=new Hashtable<String,Boolean>();
this.Uid=Uid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public void addUser(String UserId, String name, String email) {
mDatabase = FirebaseDatabase.getInstance().getReference("User");
User user = new User(name, email,UserId);
mDatabase.child(UserId).setValue(user);
}
public void addFriend(String UserId, final String email)
{
mDatabase = FirebaseDatabase.getInstance().getReference("User");
DatabaseReference user = mDatabase.child(UserId);
final DatabaseReference friendlist = user.child("contact");
if(checkUser(email)==true)
friendlist.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Hashtable list = dataSnapshot.getValue(Hashtable.class);
if(list.isEmpty())
{
friendlist.setValue(email);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public boolean checkUser(String email){
Query query = FirebaseDatabase.getInstance().getReference("User").orderByChild("email").equalTo(email);
query.addListenerForSingleValueEvent(mValueEventListener);
if(uti==null)
{
return false;
}
return true;
}
ValueEventListener mValueEventListener=new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists())
{
uti=dataSnapshot.getValue(User.class);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "loadUser:onCancelled", databaseError.toException());
}
};
}
I would recommend that you define an interface say 'ICheckUserListener' with something like onSuccess(DataSnapshot dataSnapshot) and onError(Exception e) methods.
public void checkUser(String email, ICheckUserListener listener)
//Since this method is independent of a specific User instance, it can be static which would require minor adjustments to prevent a memory-leak
{
ValueEventListener mValueEventListener = new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
listener.success(dataSnapshot.exists() ? dataSnapshot : null);
}
#Override
public void onCancelled(DatabaseError databaseError)
{
Log.w(TAG, "loadUser:onCancelled", databaseError.toException());
listener.onError(databaseError.toException());
}
};
FirebaseDatabase
.getInstance()
.getReference("User")
.orderByChild("email") //This is redundant if email ids are unique
.equalTo(email)
.addListenerForSingleValueEvent(mValueEventListener);
}
You can then implement 'ICheckUserListener' in your 'addFriend' method to handle the result.
Database
"userinformation": [
"-KeAi52QSaiuf7p5jEYM" : {
"website" : "test1"
"username" : "test1"
}
}
Class myprofile not retrieving data
package **.****;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.view.Menu;
import android.view.MenuItem;
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 ****.****.m_Model.useri1;
public class myprofile extends AppCompatActivity {
private TextView myusername111;
private DatabaseReference mFirebaseDatabase;
private FirebaseDatabase mFirebaseInstance;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myprofile__activity);
myusername111 = (TextView) findViewById(R.id.textview22);
mFirebaseInstance = FirebaseDatabase.getInstance();
mFirebaseInstance.getReference("userinformation").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
useri1 model = dataSnapshot.getValue(useri1.class);
myusername111.setText(model.getusername());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
class edit_profile
package package ***.****;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import ***.***.m_Model.useri1;
public class edit_profile extends AppCompatActivity {
private Toolbar toolbar;
private EditText website;
private EditText username;
private Button bsubmit;
private DatabaseReference mFirebaseDatabase;
private FirebaseDatabase mFirebaseInstance;
private android.view.ViewGroup parent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
mFirebaseInstance = FirebaseDatabase.getInstance();
mFirebaseDatabase = mFirebaseInstance.getReference("users");
usernamr = (EditText) findViewById(R.id.usernamr);
website = (EditText) findViewById(R.id.website);
Button bsubmit = (Button) findViewById(R.id.b_submit);
bsubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!isEmpty(website, username) && !isEmpty(website, username)) {
mNewprofile("53", website.getText().toString().trim(), username.getText().toString().trim());
finish();
startActivity(new Intent(getApplicationContext(), myprofile.class));
}
}
} );
}
private void mNewprofile(String s, String username, String website) {
new_profile1 userinformation1 = new new_profile1(website, username);
mFirebaseDatabase.child("userinformation").setValue(userinformation1);
}
class useri1
package **.****.m_Model;
public class useri1 {
public String username;
public String website;
public Update_user1() {
}
public Update_user1(String username,String website) {
this.website = website;
this.username = username;
}
public String getwebsite() {
return website;
}
public String getusername() {
return username;
}
public void setwebsite(String website) {
this.website = website;
}
public void setusermame(String usermame) {
this.usermame = usermame;
}
Error:
W/ClassMapper: No setter/field for -KeAi52QSaiuf7p5jEYM found on class
***.****.m_Model.useri1
You're retrieving the value of userinformation. So the snapshot you get in onDataChange will have this value:
"-KeAi52QSaiuf7p5jEYM" : {
"website" : "test1"
"username" : "test1"
}
A useri1 has a website and a username property. But in the JSON above, there is only a property named -KeAi52QSaiuf7p5jEYM. So the two don't match up, leading to the error you get.
To fix this you should do a few things:
loop over the children in the snapshot
drastically simplify your POJO
The resulting code would be:
mFirebaseInstance.getReference("userinformation").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
MyUser model = dataSnapshot.getValue(MyUser.class);
myusername111.setText(model.username);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
public class MyUser {
public String username;
public String website;
}
You could also use a class with getter and setter. But in that case make sure that the getters follow Java Bean property rules for the capitalization. So:
public class MyUser {
private String username;
private String website;
public MyUser() {
}
public String getUsername() { return username; }
public void setUsername(string value) { username = value; }
public String getWebsite() { return website; }
public void setWebsite(string value) { website = value; }
}
You should use ChildEventListener instead of ValueEventListener.
Because you are using ValueEventListener Firebase is trying to set a property named -KeAi52QSaiuf7p5jEYM, but it is not a property, it is a key.
The code to add ChildEventListener looks like:
mFirebaseInstance.getReference("userinformation").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousKey) {
Update_user1 user = dataSnapshot.getValue(Update_user1.class);
// ...
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String previousKey) {
// ...
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String previousKey) {
// ...
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
// ...
}
#Override
public void onCancelled(DatabaseError databaseError) {
// ...
}
});
I want the variables one, two and three to be able to read from my database when I scan the QR Code but I cant get them to display in the Builder.setMessage() line... I have tried calling the displayDeals() method in several places but none work...
package com.example.darren.offerapp;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
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 com.google.zxing.Result;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
public class PopUpPage extends AppCompatActivity implements ZXingScannerView.ResultHandler {
private ZXingScannerView mScannerView;
private FirebaseAuth firebaseAuth;
private FirebaseUser firebaseUser;
private DatabaseReference databaseReference;
private String dealID;
private Deals_Information deals_information;
private String one = "";
private String two = "";
private String three = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pop_up_page);
//stuff for popup window
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
getWindow().setLayout((int)(width*0.8), (int)(height*0.6));
//calling the method which will pull the deals from the database
//displaySuggestion();
firebaseAuth = FirebaseAuth.getInstance();
firebaseUser = firebaseAuth.getCurrentUser();
databaseReference = FirebaseDatabase.getInstance().getReference();
dealID = firebaseUser.getUid();
displayDeals();
}
public void displayDeals(){
databaseReference.child("FruitDeals").child(dealID).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
deals_information = dataSnapshot.getValue(Deals_Information.class);
one = deals_information.getDeal();
two = deals_information.getPrice();
three = deals_information.getAisleNum();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public void onClick(View v){
mScannerView = new ZXingScannerView(this);
setContentView(mScannerView);
mScannerView.setResultHandler(this);
mScannerView.startCamera();
}
#Override
protected void onPause() {
super.onPause();
mScannerView.stopCamera();
}
#Override
public void handleResult(Result result) {
//do anything with result here
Log.w("handleResult", result.getText());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Your Deal");
builder.setMessage("Offer: " + one + "\r\n\r\nPrice: " + two + "\r\n\r\nAisle Number: " + three + "");
AlertDialog alertDialog = builder.create();
alertDialog.show();
//resume scanning
//mScannerView.resumeCameraPreview(this); //uncomment out this line when you want to scan again
}
}
The Deals_Information class is here:
package com.example.darren.offerapp;
public class Deals_Information {
private String deal;
private String price;
private String aisleNum;
//getters and setters
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getAisleNum() {
return aisleNum;
}
public void setAisleNum(String aisleNum) {
this.aisleNum = aisleNum;
}
public String getDeal() {
return deal;
}
public void setDeal(String deal) {
this.deal = deal;
}
public Deals_Information(){
}
public Deals_Information(String deal, String price, String aisleNum)
{
this.deal = deal;
this.price = price;
this.aisleNum = aisleNum;
}
}
This is the image I am talking about in my last comment
So I have Firebase Database that looks like this:
{
"lists" : {
"-KZh-vvPcPGVqC22k2Bo" : {
"dateCreated" : "2016-12-23",
"listDescription" : "My Christmas Wish List for 2016",
"listTitle" : "William's Christmas List",
"user" : "ztGAx7eplGeZgdjqnegrtbfuyUy2"
}
},
"users" : {
"8pJJuscerZRGdwGGImnWlCKSEed2" : {
"email" : "example#example.com",
"name" : "Alyson"
},
"ztGAx7eplGeZgdjqnegrtbfuyUy2" : {
"email" : "example#example.com",
"name" : "William"
}
}
}
I am trying to only return the lists objects where the user field equals the UID of the logged in user. That way the logged in user gets all his lists. But I am having trouble querying the data that is in lists because of the unique key that is generated by push() which I use to append to lists whenever a user creates a new list object. How do I go about querying lists so that I get only the lists that match the UID of the signed in user? I have this so far
package com.fanciestw.listpro;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
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.Query;
public class allList extends AppCompatActivity {
private FirebaseAuth mAuth = FirebaseAuth.getInstance();
private FirebaseAuth.AuthStateListener mAuthStateListener;
private FirebaseDatabase mDatabase = FirebaseDatabase.getInstance();
private DatabaseReference mList = mDatabase.getReference().child("lists");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_list);
mAuthStateListener = new FirebaseAuth.AuthStateListener(){
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth){
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user != null) {
Log.d("User Activity", "User Signed In");
} else {
Log.d("User Activity", "User Signed Out");
signout(getCurrentFocus());
}
}
};
mList.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
List newList = dataSnapshot.getValue(List.class);
Log.d("List Returned", newList.listTitle + " " + newList.listDescription);
updateList();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
updateList();
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onStart(){
super.onStart();
Log.d("allList Activity", "onStart");
mAuth.addAuthStateListener(mAuthStateListener);
}
#Override
public void onStop(){
super.onStop();
Log.d("allList Activity", "onStop");
if(mAuthStateListener != null) mAuth.removeAuthStateListener(mAuthStateListener);
}
public void addNewList(View view){
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Add New List");
LayoutInflater inflater = this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.add_new_list_form, null);
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(dialogView);
// Set up the buttons
builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String title = ((EditText)dialogView.findViewById(R.id.add_list_title)).getText().toString();
String desc = ((EditText)dialogView.findViewById(R.id.add_list_desc)).getText().toString();
Log.d("New List Details", title + ", " + desc);
//TODO::Store created list with title and desc in database
List newList = new List(title, desc, mAuth.getCurrentUser().getUid());
String newListID = mList.push().getKey();
mList.child(newListID).setValue(newList);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
public void updateList(){
//Want to get lists where lists.user == firebaseAuth.getCurrentUser().UID();
}
public void signout(View view){
mAuth.signOut();
Intent intent = new Intent(this, login.class);
startActivity(intent);
}
}
Declare
private FirebaseAuth mAuth;
private FirebaseUser mCurrentUser;
private String userId = null;
Initialize
mAuth = FirebaseAuth.getInstance();
mCurrentUser = mAuth.getCurrentUser();
userId = mCurrentUser.getUid().toString();
String UIDstring = (String) dataSnapshot.child("users").getValue();
Determine
if (userId.equals(UIDstring)) {
//true
} else {
// false
}