I want to read the a value from firestore document. But it doesn't work for me and I don't know where is the problem.should i use get() or realtime updates.
I tried both but doesn't work for me
this is my code.
I confirmed my positions by using toast and the are ok.
How to solve this problem?
public class SingleAdActivity extends AppCompatActivity {
String x;
String a;
String z;
String coname;
TextView Co_Name;
private ListenerRegistration listenerRegistration;
DocumentReference firebaseFirestore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_ad);
Co_Name = findViewById(R.id.SingleAd_CoName);
ad_discription = findViewById(R.id.disrcibe_ad);
phone_number = findViewById(R.id.phone);
x = getIntent().getStringExtra("single_ad_position");
a = getIntent().getStringExtra("single_ad_categoryP");
z = getIntent().getStringExtra("documentId");
firebaseFirestore = FirebaseFirestore.getInstance().collection("MainCategories")
.document(String.valueOf(a))
.collection("Ads")
.document(z);
#Override
protected void onStart () {
super.onStart();
listenerRegistration = firebaseFirestore
.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
#Override
public void
onEvent(#Nullable DocumentSnapshot documentSnapshot, #Nullable FirebaseFirestoreException e) {
if (e != null) {
Toast.makeText(SingleAdActivity.this, "error", Toast.LENGTH_SHORT).show();
return;
}
assert documentSnapshot != null;
if (documentSnapshot.exists()) {
coname = documentSnapshot.getString("CompanyName");
Co_Name.setText(coname);
} else {
// Co_Name.setText(a);
}
}
});
}
#Override
protected void onStop () {
super.onStop();
listenerRegistration.remove();
}
}
}
The way I do it is like this:
FirebaseFirestore firestoreDb = FirebaseFirestore.getInstance();
firestoreDb..collection(yourCollection)
.document(yourDocument)
.get()
.addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()) {
Object yourObject = task.getResult().toObject(YourClassName.class);
} else {
if(task.getException() != null)
{
task.getException().printStackTrace();
}
}
}
});
Related
I apply (Callback method to fix the asynchronous problem)the https://www.youtube.com/watch?v=0ofkvm97i0s video. But I have problems.
Hear are readData and interface.
private void readData(FirestoreCallback firestorecallback){
String currentUserId = firebaseAuth.getCurrentUser().getUid();
DocumentReference docRef = firestore.collection("Users").document(currentUserId);
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()){
DocumentSnapshot document = task.getResult();
if(document.exists()){
a = document.getString('gender');
}
firestorecallback.onCallback(a);
}
}
});
}
private interface FirestoreCallback{
void onCallback(String b);
}
And in onCreate method
readData(new FirestoreCallback() {
#Override
public void onCallback(String b) {
String c;
if(b=='남자'){
c ='여자';
}
if(b=='여자'){
c = '남자';
}
EventChangeListener(b);
Log.d('',b);
Log.d('',c);
}
});
EventChangeListener function's code
private void EventChangeListener(String a) {
//firestore.collection('Users').orderBy('time',Query.Direction.DESCENDING).limit(50)
//
firestore.collection('Users')
//.whereEqualTo('mbti','ENTP')
//.whereEqualTo('region','')
.whereEqualTo('gender',a)
.orderBy('time',Query.Direction.DESCENDING).limit(50)
.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot value, #Nullable FirebaseFirestoreException error) {
if(error != null){
if(progressDialog.isShowing()){
progressDialog.dismiss();
}
Log.e("Firestore error",error.getMessage());
return;
}
for (DocumentChange dc : value.getDocumentChanges()){
if (dc.getType() == DocumentChange.Type.ADDED){
userArrayList.add(dc.getDocument().toObject(User.class));
}
myAdapter.notifyDataSetChanged();
if(progressDialog.isShowing()){
progressDialog.dismiss();
}
}
}
});
}
As you can see, I can get the variable 'b' but I want to when users' 'b' is male c-> male, 'b' is female c-> male.
So I define the variable 'c' but android said variable c is not defined
public void onCallback(String b) {
String c;
if(b=='female'){
c ='male';
}
if(b=='male'){
c = 'female';
}
EventChangeListener(b);
Log.d('',b);
Log.d('',c);
}
So the app crashes when the user presses the sign-in button and only if the details he wrote down in the edit texts are correct by the firebaseAuth. reopening the app will make the app behave as nothing happened and the user will be signed in.
Here's the code:
public class LoginActivity extends Activity {
private Button btnRegister, btnSignIn, btnForgot;
private EditText etPhone, etPassword;
private ProgressBar mprogressBar;
private FirebaseAuth fbAuth;
private FirebaseUser fbUser;
private FirebaseFirestore db;
private DocumentReference uDocRef;
private CollectionReference uColctRef;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btnRegister = findViewById(R.id.btnRegister);
btnSignIn = findViewById(R.id.btnSignIn);
btnForgot = findViewById(R.id.btnForgot);
etPhone = findViewById(R.id.etPhone);
etPassword = findViewById(R.id.etPassword);
mprogressBar = findViewById(R.id.mprogressBar);
fbAuth = FirebaseAuth.getInstance();
fbUser = fbAuth.getCurrentUser();
initFirebase();
}
private void initFirebase() {
db = FirebaseFirestore.getInstance();
uColctRef = db.collection(UserFirebase.UsersCollection);
if (fbUser != null)
{
Toast.makeText(this, "User already logged in: " + fbUser.getEmail(), Toast.LENGTH_LONG).show();
refreshListAndSubscribe();
Intent zone = new Intent(this, ZoneActivity.class);
startActivity(zone);
}
}
private void refreshListAndSubscribe() {
uColctRef
.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot result,
#Nullable FirebaseFirestoreException e) {
if (e != null) {
Log.e("FirebaseDemo-Query", "Listen failed", e);
e.printStackTrace();
return;
}
Log.i("FirebaseDemo-Query", "Listen succeded");
checklist(result);
}
});
}
private void checklist(QuerySnapshot result) {
String email;
boolean isApproved;
sharedPreferences = getSharedPreferences("SaveData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
for (QueryDocumentSnapshot document : result) {
email = document.get(UserFirebase.email).toString();
if (etPhone.getText().toString().trim().equals(email))
{
String branchCode = String.valueOf(document.get(UserFirebase.branchCode));
String role = document.get(UserFirebase.roleType).toString();
isApproved = Boolean.parseBoolean(document.get(UserFirebase.isApproved).toString());
editor.putString("myBranch", branchCode);
editor.putString("myRole", role);
editor.putString("myEmail", email);
editor.putBoolean("isApproved", isApproved);
editor.apply();
}
if (fbUser != null)
{
if (fbUser.getEmail().equals(email))
{
String branchCode = String.valueOf(document.get(UserFirebase.branchCode));
String role = document.get(UserFirebase.roleType).toString();
isApproved = Boolean.parseBoolean(document.get(UserFirebase.isApproved).toString());
editor.putString("myBranch", branchCode);
editor.putString("myRole", role);
editor.putString("myEmail", email);
editor.putBoolean("isApproved", isApproved);
editor.apply();
}
}
}
}
public void onSign(View v)
{
if (isEmpty())
return;
inProgress(true);
fbAuth.signInWithEmailAndPassword(etPhone.getText().toString().trim(), etPassword.getText().toString())
.addOnSuccessListener(new OnSuccessLstnr("User Signed In", true))
.addOnFailureListener(new OnFailLstnr("Sign-in failed!"));
}
public void setPassword(View v)
{
Intent pass = new Intent(this, PasswordActivity.class);
startActivity(pass);
}
public void onRegister(View v)
{
Intent auth = new Intent (this, RegisterActivity.class);
startActivity(auth);
}
private void inProgress(boolean inProgress)
{
if (inProgress)
{
mprogressBar.setVisibility(View.VISIBLE);
btnSignIn.setEnabled(false);
btnRegister.setEnabled(false);
btnForgot.setEnabled(false);
}
else
{
mprogressBar.setVisibility(View.INVISIBLE);
btnSignIn.setEnabled(true);
btnRegister.setEnabled(true);
btnForgot.setEnabled(true);
}
}
private boolean isEmpty()
{
if (TextUtils.isEmpty(etPhone.getText().toString()))
{
etPhone.setError("REQUIRED!");
return true;
}
if (TextUtils.isEmpty(etPassword.getText().toString()))
{
etPassword.setError("REQUIRED!");
return true;
}
return false;
}
private class OnFailLstnr implements OnFailureListener
{
String msg;
public OnFailLstnr(String _msg)
{
this.msg = _msg;
}
#Override
public void onFailure(#NonNull Exception e)
{
inProgress(false);
Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_SHORT).show();
}
}
public class OnSuccessLstnr implements OnSuccessListener<AuthResult>
{
String msg;
boolean open;
OnSuccessLstnr(String _msg, boolean _open)
{
this.msg = _msg;
this.open = _open;
}
#Override
public void onSuccess(AuthResult authResult)
{
Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_LONG).show();
inProgress(false);
if (open)
{
refreshListAndSubscribe();
Intent in = new Intent(LoginActivity.this, ZoneActivity.class);
startActivity(in);
finish();
}
}
}
The Logcat:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getEmail()' on a null object reference
at com.a.shon.scoutszone2.Activities.LoginActivity.checklist(LoginActivity.java:127)
at com.a.shon.scoutszone2.Activities.LoginActivity.access$000(LoginActivity.java:42)
at com.a.shon.scoutszone2.Activities.LoginActivity$1.onEvent(LoginActivity.java:101)
at com.a.shon.scoutszone2.Activities.LoginActivity$1.onEvent(LoginActivity.java:91)
I've Tried fixing it using answers to some similliar questions that were already posted in the site, but it didn't really change or fix the problem.
I would like to get help with solving this issue out and every help would be appreciated by A LOT!
Thanks in advance!
Found a solution, Seems like dealing with Already authenticated users (Users who already logged in, just reopening the app) and users who are just logged out from the app in one method (Check the - private void checklist(QuerySnapshot result), to understand what I'm talking about) is quite a messy way to deal with it, and making it really buggy.
The solution:
In InitFirebase() change the calling of refreshListAndSubscribe(); to a different new method, i called it refreshExistingUser(), its the same code as refreshListAndSubscribe()
the only part which is different between the two is the calling for the second method at the end of them.
Ill Add here a part of the code to make it simpler to understand:
private void initFirebase() {
db = FirebaseFirestore.getInstance();
uColctRef = db.collection(UserFirebase.UsersCollection);
if (fbUser != null)
{
Toast.makeText(this, "User already logged in: " + fbUser.getEmail(), Toast.LENGTH_LONG).show();
refreshExistingUser();
Intent zone = new Intent(this, ZoneActivity.class);
startActivity(zone);
}
}
private void refreshListAndSubscribe() {
uColctRef
.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot result,
#Nullable FirebaseFirestoreException e) {
if (e != null) {
Log.e("FirebaseDemo-Query", "Listen failed", e);
e.printStackTrace();
return;
}
Log.i("FirebaseDemo-Query", "Listen succeded");
checklist(result);
}
});
}
private void checklist(QuerySnapshot result) {
String email;
boolean isApproved;
sharedPreferences = getSharedPreferences("SaveData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
for (QueryDocumentSnapshot document : result) {
email = document.get(UserFirebase.email).toString();
if (etPhone.getText().toString().trim().equals(email))
{
String branchCode = String.valueOf(document.get(UserFirebase.branchCode));
String role = document.get(UserFirebase.roleType).toString();
isApproved = Boolean.parseBoolean(document.get(UserFirebase.isApproved).toString());
editor.putString("myBranch", branchCode);
editor.putString("myRole", role);
editor.putString("myEmail", email);
editor.putBoolean("isApproved", isApproved);
editor.apply();
}
}
}
private void refreshExistingUser() {
uColctRef
.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot result,
#Nullable FirebaseFirestoreException e) {
if (e != null) {
Log.e("FirebaseDemo-Query", "Listen failed", e);
e.printStackTrace();
return;
}
Log.i("FirebaseDemo-Query", "Listen succeded");
checkuser(result);
}
});
}
private void checkuser(QuerySnapshot result) {
String email;
boolean isApproved;
sharedPreferences = getSharedPreferences("SaveData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
for (QueryDocumentSnapshot document : result) {
email = document.get(UserFirebase.email).toString();
if (fbUser.getEmail().equals(email)) { //When the user isnt == null (Reopening the app and such)
String branchCode = String.valueOf(document.get(UserFirebase.branchCode));
String role = document.get(UserFirebase.roleType).toString();
isApproved = Boolean.parseBoolean(document.get(UserFirebase.isApproved).toString());
editor.putString("myBranch", branchCode);
editor.putString("myRole", role);
editor.putString("myEmail", email);
editor.putBoolean("isApproved", isApproved);
editor.apply();
}
}
}
Do you know why dataFromDatabase in IntentService code always returns null?
collection.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
dataFromDatabase = documentSnapshot.get("name").toString();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
dataFromDatabase = "Error";
}
});
The user is logged in and userID returns correct value of his ID.
Firestore database looks like this:
Firestore database
This is full code of my IntentService:
public class AppWidgetService extends IntentService {
String dataFromDatabase;
String userID;
public static final String ACTION_FOO = "pl.skawit.challenge.action.FOO";
public AppWidgetService() {
super("AppWidgetService");
}
#Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
final String action = intent.getAction();
if (ACTION_FOO.equals(action)) {
handleActionFoo();
}
}
}
private void handleActionFoo() {
FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
userID = Objects.requireNonNull(FirebaseAuth.getInstance().getCurrentUser()).getUid();
DocumentReference collection = firebaseFirestore.document("users_data/" + userID);
collection.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
dataFromDatabase = documentSnapshot.get("name").toString();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
dataFromDatabase = "Error";
}
});
}
I found a similar post where it says your if documentSnapshot is null and you're sure the document exists, then the problem can be caused by permissions [1].
[1]DocumentSnapshot is always null for a valid document reference
I'm having an issue with FireStore offline persistence when getting information from a single document.
The below method of filling form works fine when online, but I'm seeing a long delay (filling data into a simple EditText form) when I test the app offline (sometimes three or four seconds):
private void importFirestoreData() {
dbDocument = dbFirestore.collection("sites").document(siteId);
dbDocument.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Log.d(TAG, "DocumentSnapshot data: " + document.getData());
companyNameEditText.setText(document.getString("companyName"));
siteLocationEditText.setText(document.getString("siteLocation"));
siteAddressEditText.setText(document.getString("siteAddress"));
companyWebsiteEditText.setText(document.getString("companyWebsite"));
} else {
Log.d(TAG, "No such document");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
}
The rest of the code is here:
public class SiteAddEditActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "SiteAddEditActivity";
public static final String KEY_SITE_ID = "key_site_id";
private TextView mainTitleTextView;
private EditText companyNameEditText, siteLocationEditText, siteAddressEditText, companyWebsiteEditText;
private Button saveButton, cancelButton;
private String siteId;
// Database declarations
private FirebaseAuth mAuth;
private FirebaseUser mUser;
private FirebaseFirestore dbFirestore;
private DocumentReference dbDocument;
private Query dbQuery;
private boolean newDoc;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
setContentView(R.layout.site_add_edit_activity);
setUpViews();
setUpListeners();
setUpFirestore();
getIDfromExtras();
}
private void setUpViews() {
mainTitleTextView = findViewById(R.id.textViewMainHeading);
companyNameEditText = findViewById(R.id.editTextCompanyName);
siteLocationEditText = findViewById(R.id.editTextSiteLocation);
siteAddressEditText = findViewById(R.id.editTextSiteAddress);
companyWebsiteEditText = findViewById(R.id.editTextCompanyWebsite);
saveButton = findViewById(R.id.buttonSave);
cancelButton = findViewById(R.id.buttonCancel);
}
private void setUpListeners() {
saveButton.setOnClickListener(this);
cancelButton.setOnClickListener(this);
}
private void setUpFirestore() {
mAuth = FirebaseAuth.getInstance();
mUser = mAuth.getCurrentUser();
dbFirestore = FirebaseFirestore.getInstance();
}
private void getIDfromExtras() {
newDoc = true;
// Get site ID from extras
siteId = getIntent().getExtras().getString(KEY_SITE_ID);
if (siteId == null) {
throw new IllegalArgumentException("Must pass extra " + KEY_SITE_ID);
}
else {
newDoc = false;
mainTitleTextView.setText(R.string.app_edit_site);
importFirestoreData();
}
}
private void importFirestoreData() {
dbDocument = dbFirestore.collection("sites").document(siteId);
dbDocument.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Log.d(TAG, "DocumentSnapshot data: " + document.getData());
companyNameEditText.setText(document.getString("companyName"));
siteLocationEditText.setText(document.getString("siteLocation"));
siteAddressEditText.setText(document.getString("siteAddress"));
companyWebsiteEditText.setText(document.getString("companyWebsite"));
} else {
Log.d(TAG, "No such document");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
}
#Override
public void onClick(View view) {
int i = view.getId();
if(i == R.id.buttonSave){
if (newDoc){
saveSite();
}
else {
updateSite();
}
startActivity(new Intent(SiteAddEditActivity.this, SiteActivity.class));
} else if (i == R.id.buttonCancel) {
FirebaseAuth mAuth = FirebaseAuth.getInstance();
Toast.makeText(this, "User (" + mAuth.getUid() + ") Signed Out!", Toast.LENGTH_LONG).show();
mAuth.signOut();
startActivity(new Intent(SiteAddEditActivity.this,LoginMainActivity.class));
}
}
private void updateSite() {
SitePOJO updateSite = new SitePOJO(
companyNameEditText.getText().toString().trim(),
siteLocationEditText.getText().toString().trim(),
siteAddressEditText.getText().toString(),
companyWebsiteEditText.getText().toString().trim()
);
dbDocument.set(updateSite);
}
private void saveSite() {
SitePOJO newSite = new SitePOJO(
companyNameEditText.getText().toString().trim(),
siteLocationEditText.getText().toString().trim(),
siteAddressEditText.getText().toString(),
companyWebsiteEditText.getText().toString().trim()
);
dbDocument = dbFirestore.collection("sites").document();
String thisDoc = dbDocument.getId();
dbDocument.set(newSite);
Toast.makeText(this, "New site created (document ref: " + thisDoc + ")", Toast.LENGTH_LONG).show();
}
}
I'm guessing it is how I am getting the data - I'm wondering if it is better to handle the data in some sort of adapter (separate to the activities?)..
Thank you to Reaz - yes this post did help..
My simple mind got confused between.get().addOnCompleteListener and .addSnapshotListener..
Correct working code below:
private void importFirestoreData() {
dbDocument = dbFirestore.collection("sites").document(siteId);
dbDocument.addSnapshotListener(new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(#javax.annotation.Nullable DocumentSnapshot documentSnapshot, #javax.annotation.Nullable FirebaseFirestoreException e) {
if (e != null) {
Log.w(TAG, "Listen failed.", e);
return;
}
if (documentSnapshot != null && documentSnapshot.exists()) {
Log.d(TAG, "Current data: " + documentSnapshot.getData());
companyNameEditText.setText(documentSnapshot.getString("companyName"));
siteLocationEditText.setText(documentSnapshot.getString("siteLocation"));
siteAddressEditText.setText(documentSnapshot.getString("siteAddress"));
companyWebsiteEditText.setText(documentSnapshot.getString("companyWebsite"));
} else {
Log.d(TAG, "Current data: null");
}
}
});
}
I'm developing an app, but I found a problem. I can encrypt but I can not decipher. Can you help me fix it?
the app comes to sensitive data and I would like to send in Firebase encrypted data but they remain decrypted on the list.
This is my code:
public class UserActivity extends AppCompatActivity {
private EditText input_tipo, input_id, input_password;
private ListView list_data;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mDatabaseReference;
private FirebaseAnalytics firebaseAnalytics;
private List<User> list_users = new ArrayList<>();
private User selectedUser;
private FirebaseAuth mAuth;
private FirebaseUser mUser;
private String encryptPass, decryptPass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
Toolbar tool = (Toolbar) findViewById(R.id.toolbar);
tool.setTitle("MySecurity");
setSupportActionBar(tool);
input_tipo = (EditText) findViewById(R.id.tipo);
input_id = (EditText) findViewById(R.id.id);
input_password = (EditText) findViewById(R.id.password);
list_data = (ListView) findViewById(R.id.list_data);
mAuth = FirebaseAuth.getInstance();
mUser = mAuth.getCurrentUser();
list_data.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
User user = (User) adapterView.getItemAtPosition(i);
selectedUser = user;
input_tipo.setText(user.getTipo());
input_id.setText(user.getId());
input_password.setText(user.getPassword());
}
});
initFirebase();
addEventFirebaseListener();
findNetwork();
}
private void findNetwork() {
ConnectivityManager CM = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo ninfo = CM.getActiveNetworkInfo();
if (ninfo != null && ninfo.isConnectedOrConnecting()) {
Toast.makeText(getBaseContext(), "Connesso in Firebase:" + ninfo.getTypeName(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "Connessione internet assente", Toast.LENGTH_LONG).show();
}
}
private void addEventFirebaseListener() {
list_data.setVisibility(View.VISIBLE);
mDatabaseReference.child("users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (list_users.size() > 0)
list_users.clear();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
User user = postSnapshot.getValue(User.class);
list_users.add(user);
}
ListViewAdapter adapter = new ListViewAdapter(UserActivity.this, list_users);
list_data.setAdapter(adapter);
list_data.setVisibility(View.VISIBLE);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void initFirebase() {
FirebaseApp.initializeApp(this);
mFirebaseDatabase = FirebaseDatabase.getInstance();
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
firebaseAnalytics = FirebaseAnalytics.getInstance(this);
firebaseAnalytics.setAnalyticsCollectionEnabled(true);
firebaseAnalytics.setMinimumSessionDuration(5000);
mDatabaseReference = mFirebaseDatabase.getReference().child("users").child(mUser.getUid());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.home, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_add) {
createUser();
} else if (item.getItemId() == R.id.menu_remove) {
deleteUser(selectedUser);
} else if (item.getItemId() == R.id.menu_deselect) {
DeselectedUser(selectedUser);
}else if(item.getItemId()== R.id.menu_decrypt){
DecryptUser(selectedUser);
}
return true;
}
private void DecryptUser(User selectedUser) {
if (selectedUser != null) {
mDatabaseReference.child("users").child(selectedUser.getUid());
String password = selectedUser.getPassword().trim();
String Message= selectedUser.getPassword().trim();
try {
decryptPass= AESCrypt.decrypt( password, Message);
input_tipo.setText(input_tipo.getText().toString());
input_id.setText(input_id.getText().toString());
input_password.setText(decryptPass);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void DeselectedUser(User selectedUser) {
if (selectedUser != null) {
mDatabaseReference.child("users").child(selectedUser.getUid());
clearEditText();
}
}
private void deleteUser(User selectedUser) {
if (selectedUser != null) {
mDatabaseReference.child("users").child(selectedUser.getUid()).removeValue();
clearEditText();
}
}
private void createUser() {
String password = input_password.getText().toString().trim();
String Message= input_password.getText().toString().trim();
try {
encryptPass = AESCrypt.encrypt(password, Message);
User user1= new User(UUID.randomUUID().toString(), input_tipo.getText().toString(),
input_id.getText().toString(), encryptPass);
mDatabaseReference.child("users").child(user1.getUid()).setValue(user1);
clearEditText();
} catch (Exception e) {
e.printStackTrace();
}
}
private void clearEditText() {
input_tipo.setText("");
input_id.setText("");
input_password.setText("");
}
#Override
protected void onStop() {
super.onStop();
finish();
}
}
The password and Message variables are assigned the same thing (selectedUser.getPassword().trim()). What you are doing is trying to decrypt the user password, using the user password. Probably you need to assign the ciphertext that you want to decrypt to the Message variable.