Adding user via admin panel in android studio with firebase - java

I wanted to ask for your help with something that eating my brain out since I am new at Firebase and android studio. I created this attendance app but only the admin can log into the system then as the admin he has the ability to add students and teachers so that they can have access to the system when they want to log in the system. but once I add a teacher he cannot log in the system. the system saying incorrect username and password while the credentials are all well-typed. is there a way to give access to a user without creating the sign-up page. I am using firebase as the database. here is my code for adding a teacher
public class FacultyAddActivity extends AppCompatActivity {
private Toolbar addFacTool;
private EditText facName, facEmail, facPhone, facID, facAddress;
private Spinner facSpinner;
private String[] designList;
private String selectDesign;
private Button addFacBtn;
private String intentMode, intentFac;
private DatabaseReference facReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_faculty_add);
addFacTool = findViewById(R.id.toolAdd);
setSupportActionBar(addFacTool);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
Intent intent = getIntent();
intentFac = intent.getStringExtra("FACULTY");
intentMode = intent.getStringExtra("MODE");
facName = findViewById(R.id.txtLName);
facEmail = findViewById(R.id.txtLEmail);
facAddress = findViewById(R.id.txtLAddress);
facPhone = findViewById(R.id.txtLPhone);
facID = findViewById(R.id.txtLID);
addFacBtn = findViewById(R.id.btnLSubmit);
facSpinner = findViewById(R.id.spnDes);
designList = getResources().getStringArray(R.array.designation);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(FacultyAddActivity.this, android.R.layout.simple_list_item_1, designList);
facSpinner.setAdapter(arrayAdapter);
facSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectDesign = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
addFacBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addFaculty();
}
});
}
private void addFaculty() {
String name = facName.getText().toString();
String email = facEmail.getText().toString();
String address = facAddress.getText().toString();
String phone = facPhone.getText().toString();
String ID = facID.getText().toString();
if (name.isEmpty()){
facName.setError("Enter lecturer name");
facName.requestFocus();
}
else if (email.isEmpty()){
facEmail.setError("Enter lecturer email");
facEmail.requestFocus();
}
else if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()){
facEmail.setError("Enter lecturer email");
facEmail.requestFocus();
}
else if (address.isEmpty()){
facAddress.setError("Enter lecturer address");
facAddress.requestFocus();
}
else if (phone.isEmpty()){
facPhone.setError("Enter lecturer phone number");
facPhone.requestFocus();
}
else if (selectDesign.isEmpty() && selectDesign.equals("Select Designation")){
Toast.makeText(getApplicationContext(), "Select Designation", Toast.LENGTH_SHORT).show();
}
else if (ID.isEmpty()){
facID.setError("Enter lecturer ID");
facID.requestFocus();
}
else{
facReference = FirebaseDatabase.getInstance().getReference().child("Department").child("Lecturer");
String key = facReference.push().getKey();
FacultyConstructor facultyConstructor = new FacultyConstructor(ID, name, intentFac, selectDesign, phone, email, address, "123456", intentMode);
facReference.child(key).setValue(facultyConstructor).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
Toast.makeText(getApplicationContext(), "Lecturer added successfully", Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
if (item.getItemId() == android.R.id.home){
this.finish();
}
return super.onOptionsItemSelected(item);
}
}

Related

Mesibo first app in Fragment bad connection status

I'm following Mesibo Tutorial for the First App and trying to integrate it in my app. The difference to the source code of tutorial https://github.com/mesibo/samples/tree/master/android/java/FirstApp is only that I have implemented it in Fragment instead of Activity and using databinding for views.
Every time if I'm clicking to LOGIN_AS_USER1 or LOGIN_AS_USER2 Button it shows connection Status 5. The created users are never online.
The users with corresponding user addresses and app ID (app Package) were created manually in Mesibo console. Tokens, addresses and app ID are double checked.
My Fragment code:
public class CommunicationFragment extends Fragment implements Mesibo.ConnectionListener, Mesibo.MessageListener {
private FragmentCommunicationBinding binding;
class DemoUser {
public String token;
public String name;
public String address;
DemoUser(String token, String name, String address) {
this.token = token;
this.name = name;
this.address = address;
}
}
//Refer to the Get-Started guide to create two users and their access tokens
DemoUser mUser1 = new DemoUser("631b138a5bfd2827b20d312721ee6549198539a5041517df2e33311958", "User-1", "1233");
DemoUser mUser2 = new DemoUser("ae80d38f59a814b3f4694055bbd90005c2fdae2ae7a530fe44311959", "User-2", "4566");
DemoUser mRemoteUser;
Mesibo.UserProfile mProfile;
Mesibo.ReadDbSession mReadSession;
Button mSendButton, mUiButton, mAudioCallButton, mVideoCallButton;
Button mLoginButton1, mLoginButton2;
TextView mMessageStatus, mConnStatus;
EditText mMessage;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_communication, container, false);
View view = binding.getRoot();
mLoginButton1 = binding.login1;
mLoginButton2 = binding.login2;
mSendButton = binding.send;
mUiButton = binding.launchUI;
mAudioCallButton = binding.audioCall;
mVideoCallButton = binding.videoCall;
mMessageStatus = binding.msgStatus;
mConnStatus = binding.connStatus;
mMessage = binding.message;
mSendButton.setEnabled(false);
mUiButton.setEnabled(false);
mAudioCallButton.setEnabled(false);
mVideoCallButton.setEnabled(false);
mLoginButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mesiboInit(mUser1, mUser2); }
});
mLoginButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mesiboInit(mUser2, mUser1); }
});
mSendButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Mesibo.MessageParams p = new Mesibo.MessageParams();
p.peer = mRemoteUser.address;
p.flag = Mesibo.FLAG_READRECEIPT | Mesibo.FLAG_DELIVERYRECEIPT;
Mesibo.sendMessage(p, Mesibo.random(), mMessage.getText().toString().trim());
mMessage.setText("");}
});
mUiButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
MesiboUI.launchMessageView(getActivity(), mRemoteUser.address, 0);
}
});
mAudioCallButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
MesiboCall.getInstance().callUi(getActivity(), mProfile.address, false);
}
});
mVideoCallButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
MesiboCall.getInstance().callUi(getActivity(), mProfile.address, true);
}
});
return view;
}
private void mesiboInit(DemoUser user, DemoUser remoteUser) {
Mesibo api = Mesibo.getInstance();
api.init(getActivity().getApplicationContext());
Mesibo.addListener(this);
Mesibo.setSecureConnection(true);
Mesibo.setAccessToken(user.token);
Mesibo.setDatabase("mydb", 0);
Mesibo.start();
mRemoteUser = remoteUser;
mProfile = new Mesibo.UserProfile();
mProfile.address = remoteUser.address;
mProfile.name = remoteUser.name;
Mesibo.setUserProfile(mProfile, false);
// disable login buttons
mLoginButton1.setEnabled(false);
mLoginButton2.setEnabled(false);
// enable buttons
mSendButton.setEnabled(true);
mUiButton.setEnabled(true);
mAudioCallButton.setEnabled(true);
mVideoCallButton.setEnabled(true);
MesiboCall.getInstance().init(getActivity().getApplicationContext());
// Read receipts are enabled only when App is set to be in foreground
Mesibo.setAppInForeground(getActivity(), 0, true);
mReadSession = new Mesibo.ReadDbSession(mRemoteUser.address, this);
mReadSession.enableReadReceipt(true);
mReadSession.read(100);
}
#Override
public void Mesibo_onConnectionStatus(int status) {
mConnStatus.setText("Connection Status: " + status);
}
#Override
public boolean Mesibo_onMessage(Mesibo.MessageParams messageParams, byte[] data) {
try {
String message = new String(data, "UTF-8");
Toast toast = Toast.makeText(getActivity().getApplicationContext(),
message,
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.show();
} catch (Exception e) {
}
return true;
}
#Override
public void Mesibo_onMessageStatus(Mesibo.MessageParams messageParams) {
mMessageStatus.setText("Message Status: " + messageParams.getStatus());
}
#Override
public void Mesibo_onActivity(Mesibo.MessageParams messageParams, int i) {
}
#Override
public void Mesibo_onLocation(Mesibo.MessageParams messageParams, Mesibo.Location location) {
}
#Override
public void Mesibo_onFile(Mesibo.MessageParams messageParams, Mesibo.FileInfo fileInfo) {
}
}
Most likely you are creating a token using the wrong App ID
https://mesibo.com/documentation/faq/other/#i-am-not-getting-connection-status-1-online
If you are not getting connection status 1, and getting 4 or 5, you
are not passing the correct appid while creating a token. The appid
passed to create a token must match the Android package name declared
in the AndroidManifest.xml or iOS bundle id declared in the Xcode
project (for example, com.mesibo.xxx ). If you are using Javascript
API or other platforms, ensure that you pass the same app id to the
setAppName API call.

Radio button returns wrong value in Android

I have a form where a person can enter details about a friend (name, age, gender, address). This friend is displayed in a list view and when a friend from the list is clicked on they have the choice to edit that record.
I can successfully update every detail about a friend except for the gender.
For example:
List view:
1) James Bond, 20, Male, Sydney NSW
Then I click edit and change it to
James smith, 21, Female, Canberra NSW
and then back in my list view it will show:
1) James smith, 21, Male, Canberra NSW
Notice how the gender doesn't change?
I can figure out why this is happening as I use the same logic to change the name and age as i did to change the gender
Here is the relevant code:
ViewFriend.java ( this class displays the list view and has the edit option)
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view, final int position, long id) {
String text = listView.getItemAtPosition(position).toString();
final int ID = Integer.parseInt(String.valueOf(text.charAt(0)));
AlertDialog.Builder builder = new AlertDialog.Builder(viewFriends.this);
builder.setTitle("Notice");
builder.setMessage("Please select to to edit, delete a friend or cancel");
// add the buttons
builder.setPositiveButton("Edit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(), editOrDelete.class);
ArrayList<String> result1 = mydb.retrieveRow(ID);
name = result1.get(1);
age = result1.get(2);
gender = result1.get(3);
address = result1.get(4);
code = result1.get(0);
intent.putExtra("code", code);
intent.putExtra("name", name);
intent.putExtra("age", age);
intent.putExtra("gender", gender);
intent.putExtra("address", address);
startActivity(intent);
}
});
builder.setNeutralButton(" Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mydb.deleteTitle(ID);
finish();
Intent intent = new Intent(getApplicationContext(),viewFriends.class);
startActivity(intent);
}
});
builder.setNegativeButton("Cancel", null);
AlertDialog dialog = builder.create();
dialog.show();
}
});
The code above retrieves the details from the database and passes it to the intent. I have printed the contents of each variable (name, age, gender, address) and they print out correctly.
editFriend.java ( this class pre fills the form with the data passed through the intent that displays correctly)
public class editFriend extends AppCompatActivity {
private Intent intent;
private RadioGroup rg;
private Button update;
private RadioButton rb;
private String newName,newAddress,newGender;
private int newAge;
EditText ed, ed1;
public String name,address,gender,age,code;
private int selectedID,ages,codes;
NumberPicker numberPicker;
private databaseManager4 myDataBase;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_editordeletefriend);
intent= getIntent();
myDataBase = new databaseManager4(this);
rg = (RadioGroup)findViewById(R.id.radioGroup_update);
selectedID = rg.getCheckedRadioButtonId();
rb = (RadioButton) findViewById(selectedID);
ed = (EditText)findViewById(R.id.fullName_update);
numberPicker = (NumberPicker)findViewById(R.id.resultAge_update);
numberPicker.setMinValue(6);
numberPicker.setMaxValue(110);
numberPicker.setWrapSelectorWheel(false);
update = (Button)findViewById(R.id.update_button);
ed1 = (EditText)findViewById(R.id.address_update);
name = intent.getStringExtra("name");
age = intent.getStringExtra("age");
gender = intent.getStringExtra("gender");
address = intent.getStringExtra("address");
code = intent.getStringExtra("code");
codes = Integer.parseInt(code);
displayForm();
newName = ed.getText().toString();
newAge = numberPicker.getValue();
newGender = rb.getText().toString();
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int id = rg.getCheckedRadioButtonId();
rb = (RadioButton) findViewById(id);
if (myDataBase.updateRow(codes,newName,newAge,newGender,ed1.getText().toString())){
Toast.makeText(getApplicationContext(),"successfully updated the friend "
+ed.getText().toString(),Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(),"Could not update the friend "
+ed.getText().toString(),Toast.LENGTH_SHORT).show();
}
intent = new Intent(getApplicationContext(),viewFriends.class);
startActivity(intent);
}
});
}
public void displayForm(){
ed.setText(name);
ed1.setText(address);
if (gender.equals("Male")){
rb = (RadioButton)findViewById(R.id.resultGenderMale_update);
}
else if (gender.equals("Female"))
{
rb = (RadioButton)findViewById(R.id.resultGenderFemale_update);
}
rb.setChecked(true);
ages= Integer.parseInt(age);
numberPicker.setValue(ages);
}
public void clear(){
ed.setText("");
ed1.setText("");
}
}
This is where the issue lies, even if the user clicks on Male it registers as female and i am unsure why.
Any ideas how i can fix this?
Your problem is that you set value of rb variable to a single radio button, predefined with previous gender value here
if (gender.equals("Male")){
rb = (RadioButton)findViewById(R.id.resultGenderMale_update);
}
else if (gender.equals("Female"))
{
rb = (RadioButton)findViewById(R.id.resultGenderFemale_update);
}
And you read value of the same button then. To fix that in you click listener for update button you need to read checked radio button id using getCheckedRadioButtonId on radio group (your rg variable).
upd:
this is how your Edit Friend activity code might look like
public class EditFriendActivity extends AppCompatActivity {
private RadioGroup mGenderRadioGroup;
private Button mUpdateButton;
private EditText mNameField;
private EditText mAddressField;
private NumberPicker mAgePicker;
private databaseManager4 mDatabaseManager;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_editordeletefriend);
initUI();
mDatabaseManager = new databaseManager4(this);
}
private void initUI() {
Intent intent = getIntent();
mNameField = (EditText) findViewById(R.id.fullName_update);
mNameField.setText(intent.getStringExtra("name"));
mAddressField = (EditText) findViewById(R.id.address_update);
mAddressField.setText(intent.getStringExtra("address"));
mAgePicker = (NumberPicker) findViewById(R.id.resultAge_update);
mAgePicker.setMinValue(6);
mAgePicker.setMaxValue(110);
mAgePicker.setWrapSelectorWheel(false);
mAgePicker.setValue(Integer.parseInt(intent.getStringExtra("age")));
mUpdateButton = (Button) findViewById(R.id.update_button);
mUpdateButton.setOnClickListener(updateClickListener);
mGenderRadioGroup = (RadioGroup) findViewById(R.id.radioGroup_update);
RadioButton targetRadioButton = null;
switch (Gender.fromString(intent.getStringExtra("gender"))) {
case MALE:
targetRadioButton = (RadioButton) findViewById(R.id.resultGenderMale_update);
break;
case FEMALE:
targetRadioButton = (RadioButton) findViewById(R.id.resultGenderFemale_update);
break;
}
if (targetRadioButton != null) {
targetRadioButton.setChecked(true);
}
}
public void clear() {
mNameField.setText("");
mAddressField.setText("");
}
private Gender getSelectedGender() {
int checkedButtonId = mGenderRadioGroup.getCheckedRadioButtonId();
switch (checkedButtonId) {
case R.id.resultGenderMale_update:
return Gender.MALE;
case R.id.resultGenderFemale_update:
return Gender.FEMALE;
}
return Gender.UNDEFINED;
}
private View.OnClickListener updateClickListener =
new View.OnClickListener() {
#Override
public void onClick(View v) {
Gender newGender = getSelectedGender();
int code = Integer.parseInt(getIntent().getStringExtra("code"));
System.out.println("gender is" + newGender.stringValue);
if (mDatabaseManager.updateRow(
code,
mNameField.getText().toString(),
mAgePicker.getValue(),
newGender.stringValue,
mAddressField.getText().toString())) {
Toast.makeText(
getApplicationContext(),
"successfully updated the friend " + ed.getText().toString(),
Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(
getApplicationContext(),
"Could not update the friend " + ed.getText().toString(),
Toast.LENGTH_SHORT)
.show();
}
Intent viewFriendsIntent = new Intent(getApplicationContext(), viewFriends.class);
startActivity(viewFriendsIntent);
finish();
}
};
private enum Gender {
UNDEFINED("undefined"),
MALE("Male"),
FEMALE("Female");
private #Nullable String stringValue;
Gender(#Nullable String stringValue) {
this.stringValue = stringValue;
}
public static Gender fromString(#Nullable String value) {
if (value != null) {
for (Gender gender : Gender.values()) {
if (value.equals(gender.stringValue)) {
return gender;
}
}
}
return UNDEFINED;
}
}
}

Why the id is changing every time on the same phone ? Firebase database

enter image description hereFirst of all i want to say that my english isn't very good but i hope this is not a problem (i hope). So I wrote a code that "should" get user id from the user of my app but every time
firebase get other id on the same phone can someone help me with this problem ?
If you need more info, please write it in comments . Thank you in advance. Here my code .
EditText editTextName;
Button buttonAdd;
Spinner spinnerGenres;
DatabaseReference databaseArtists;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one_cent);
databaseArtists = FirebaseDatabase.getInstance().getReference("prousers");
editTextName = (EditText) findViewById(R.id.editTextName);
buttonAdd = (Button) findViewById(R.id.buttonAddArtist);
spinnerGenres = (Spinner) findViewById(R.id.spinnerGenres);
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addArtist();
}
});
}
private void addArtist(){
String name = editTextName.getText().toString().trim();
String genre = spinnerGenres.getSelectedItem().toString();
if (!TextUtils.isEmpty(name)){
String id = databaseArtists.push().getKey();
Artist artist = new Artist(id, name, genre);
databaseArtists.child(id).setValue(artist);
Toast.makeText(this, "You are a pro user :D", Toast.LENGTH_LONG).show();
finish();
System.exit(0);
}else{
Toast.makeText(this, "Something's wrong", Toast.LENGTH_LONG).show();
}
}
}
and this one too
public Artist(){
}
public Artist(String artistId, String artistName, String artistGenre) {
this.artistId = artistId;
this.artistName = artistName;
this.artistGenre = artistGenre;
}
public String getArtistId() {
return artistId;
}
public String getArtistName() {
return artistName;
}
public String getArtistGenre() {
return artistGenre;
}
}

Authenticated users accessing their data using Firebase for Android

I am struggling to make a tie between my users in Firebase, and data that I want it to be linked to.
At the moment I am able to create users and log in with users credentials. Additionally, I am able to create Maintenance Issues using my MaintenanceActivity.
However, when I log in with an arbitrary user, the same maintenance issues will always show.
I am unsure how to link the User ID of each user to a maintenance issue, so that when a user logs in only their maintenance issues will show.
Totally unsure on where to start here, so any help would be much appreciated. Been struggling with this for a few days.
SignUpActivity
This creates users in the 'Users' table in my Firebase database, but I also want it to contain the User ID which can be linked to maintenance issues.
mDatabase = FirebaseDatabase.getInstance().getReference().child("users");
final DatabaseReference[] ref = new DatabaseReference[1];
final FirebaseUser[] mCurrentUser = new FirebaseUser[1];
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toasty.info(getApplicationContext(), "creation of account was: " + task.isSuccessful(), Toast.LENGTH_SHORT).show();
if (task.isSuccessful()) {
mCurrentUser[0] = task.getResult().getUser();
ref[0] =mDatabase.child(mCurrentUser[0].getUid());
ref[0].child("email").setValue(email);
Intent intent = new Intent(SignUpActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
});
MaintenanceActvity
public class MaintenanceActivity extends AppCompatActivity {
EditText editTextTitle;
EditText editTextDesc;
Spinner spinnerPrimary;
Spinner spinnerSecondary;
Spinner spinnerProperty;
Button buttonSubmit;
DatabaseReference databaseMaintenance;
ListView listViewIssues;
List<Maintenance> maintenanceList;
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference fDatabaseRoot = database.getReference();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maintenance);
Toolbar toolbar = (Toolbar) findViewById(R.id.actionBar);
setSupportActionBar(toolbar);
ActionBar ab = getSupportActionBar();
ab.setDisplayHomeAsUpEnabled(true);
databaseMaintenance = FirebaseDatabase.getInstance().getReference("maintenance");
editTextTitle = (EditText) findViewById(R.id.editTextTitle);
editTextDesc = (EditText) findViewById(R.id.editTextDesc);
buttonSubmit = (Button) findViewById(R.id.buttonSubmit);
spinnerPrimary = (Spinner) findViewById(R.id.spinnerPrimary);
spinnerSecondary = (Spinner) findViewById(R.id.spinnerSecondary);
spinnerProperty = (Spinner) findViewById(R.id.spinnerProperty);
listViewIssues = (ListView) findViewById(R.id.listViewIssues);
maintenanceList = new ArrayList<>();
buttonSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addMaintenance();
}
});
listViewIssues.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Maintenance maintenance = maintenanceList.get(position);
showMoreInfoDialog(maintenance.getMaintenanceId(), maintenance.getMaintenanceTitle(), maintenance.getMaintenanceDescription(), maintenance.getMaintenancePrimary(), maintenance.getMaintenanceSecondary(), maintenance.getMaintenanceProperty());
return false;
}
});
}
#Override
protected void onStart() {
super.onStart();
databaseMaintenance.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
maintenanceList.clear();
for(DataSnapshot maintenanceSnapshot : dataSnapshot.getChildren()){
Maintenance maintenance = maintenanceSnapshot.getValue(Maintenance.class);
maintenanceList.add(maintenance);
}
MaintenanceList adapter = new MaintenanceList (MaintenanceActivity.this, maintenanceList);
listViewIssues.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
fDatabaseRoot.child("properties").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Is better to use a List, because you don't know the size
// of the iterator returned by dataSnapshot.getChildren() to
// initialize the array
final List<String> propertyAddressList = new ArrayList<String>();
for (DataSnapshot addressSnapshot: dataSnapshot.getChildren()) {
String propertyAddress = addressSnapshot.child("propertyAddress").getValue(String.class);
if (propertyAddress!=null){
propertyAddressList.add(propertyAddress);
}
}
Spinner spinnerProperty = (Spinner) findViewById(R.id.spinnerProperty);
ArrayAdapter<String> addressAdapter = new ArrayAdapter<String>(MaintenanceActivity.this, android.R.layout.simple_spinner_item, propertyAddressList);
addressAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerProperty.setAdapter(addressAdapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void showMoreInfoDialog(final String id, String maintenanceTitle, String maintenanceDescription, String maintenancePrimary, String maintenanceSecondary, String maintenanceProperty) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.more_info_dialog, null);
dialogBuilder.setView(dialogView);
final EditText editTextTitle = (EditText) dialogView.findViewById(R.id.editTextTitle);
final EditText editTextDesc = (EditText) dialogView.findViewById(R.id.editTextDesc);
final Button buttonUpdate = (Button) dialogView.findViewById(R.id.buttonUpdate);
final Spinner spinnerPrimary = (Spinner) dialogView.findViewById(R.id.spinnerPrimary);
final Spinner spinnerSecondary = (Spinner) dialogView.findViewById(R.id.spinnerSecondary);
final Spinner spinnerProperty = (Spinner) dialogView.findViewById(R.id.spinnerProperty);
final Button buttonDelete = (Button) dialogView.findViewById(R.id.buttonDelete);
dialogBuilder.setTitle("Updating Maintenance " + maintenanceTitle);
final AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
buttonUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String title = editTextTitle.getText().toString().trim();
String desc = editTextDesc.getText().toString().trim();
String primary = spinnerPrimary.getSelectedItem().toString();
String secondary = spinnerSecondary.getSelectedItem().toString();
String property = spinnerProperty.getSelectedItem().toString();
if(TextUtils.isEmpty(title)){
editTextTitle.setError("Title Required");
return;
}
updateMaintenance(title, desc, id, primary, secondary, property);
alertDialog.dismiss();
}
});
private boolean updateMaintenance(String title, String desc, String id, String primary, String secondary, String property) {
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("maintenance").child(id);
Maintenance maintenance = new Maintenance (id, title, desc, primary, secondary, property);
databaseReference.setValue(maintenance);
Toast.makeText(this, "Maintenance Updated Updated Successfully", Toast.LENGTH_LONG).show();
return true;
}
private void addMaintenance(){
String title = editTextTitle.getText().toString().trim();
String desc = editTextDesc.getText().toString().trim();
String primary = spinnerPrimary.getSelectedItem().toString();
String secondary = spinnerSecondary.getSelectedItem().toString();
String property = spinnerProperty.getSelectedItem().toString();
if(!TextUtils.isEmpty(title)){
String id = databaseMaintenance.push().getKey();
Maintenance maintenance = new Maintenance (id, title, desc, primary, secondary, property);
databaseMaintenance.child(id).setValue(maintenance);
Toast.makeText(this, "Maintenance Added", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "You must enter a maintenance record", Toast.LENGTH_LONG).show();
}
}
}
Firebase Database
Database Rules are as follows:
{
"rules": {
"users": {
"$uid": {
".write": "$uid === auth.uid",
".read": "$uid === auth.uid"
}
}
}
}
A basic approach that u can take is have a User Id for every maintenance node that you push.
So as per your firebase database you have a user ID "bfPG...."
This id can be the parent node for every maintenance record.
If you change this line to this
String id = databaseMaintenance.push().getKey();
this
String id = FirebaseAuth.getInstance().getCurrentUser().getUID(); //Check Syntax
you'll be pushing a maintenance record under a user ID and you can then differentiate maintenance records with different users.
Thus in order to get the records for a specific user you have to change your firebase query.
databaseMaintenance = FirebaseDatabase.getInstance().getReference("maintenance").orderByKey().equalTo(id);
https://firebase.google.com/docs/database/android/lists-of-data
check the link about how to filter records.
Another approach is you have an adapter to which you are adding maintenance records so before you add a record you can check if it belongs to the current user or not and add records accordingly.

Cant find a way to delete an item from sharedPreferences

I am trying to delete an item from taskList which is connected to sharedPreferences.
I managed to remove all items but the problem is I cant find a way to connect a counter to delete an individual item from a list that has a switch and when this switch is on true I need to remove the item from list by index number.
public class TaskAdapter extends BaseAdapter {
//transfer context
Context context;
//transfer user to use for shared preferences
String userName;
//create a list of tasks.....
List<taskItem> myTasks;
Calendar calendar = Calendar.getInstance();
PendingIntent pendingIntent;
int pos;
//constructor, for creating the adapter we need from the user context and userName
public TaskAdapter(Context context, String userName) {
this.context = context;
this.userName = userName;
//go to user shared preferences and fill the list
getData();
notifyDataSetChanged();
}
//how many item to display
#Override
public int getCount() {
//return the myTasks size....
return myTasks.size();
}
//return a specific item by index
#Override
public Object getItem(int i) {
return myTasks.get(i);
}
//return index number
#Override
public long getItemId(int i) {
return i;
}
//create our view
#Override
public View getView(final int index, final View view, ViewGroup viewGroup) {
//inflate the view inside view object -> viewInflated
final View viewInflated = LayoutInflater.from(context).inflate(R.layout.task_item, null, false);
//set our inflated view behavior
//set pointer for our inflated view
//set pointer for task name....
final TextView txtTaskName = (TextView) viewInflated.findViewById(R.id.taskName);
//set pointer for taskInfo
final TextView txtTaskInfo = (TextView) viewInflated.findViewById(R.id.taskInfo);
//set pointer for task status....
final Switch swTask = (Switch) viewInflated.findViewById(taskDone);
//set task name, by the index of my myTasks collection
txtTaskName.setText(myTasks.get(index).taskName);
//set task info, by index of myTasks collection
txtTaskInfo.setText(myTasks.get(index).taskInfo);
//set task status , switch is getting true/false
swTask.setChecked(myTasks.get(index).taskStatus);
//show date and time dialog
final ImageView dtPicker = (ImageView) viewInflated.findViewById(R.id.imgTime);
dtPicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final AlertDialog.Builder ad = new AlertDialog.Builder(context);
final AlertDialog aDialog = ad.create();
final LinearLayout adLayout = new LinearLayout(context);
adLayout.setOrientation(LinearLayout.VERTICAL);
TextView txtTime = new TextView(context);
txtTime.setText("Choose time");
adLayout.addView(txtTime);
final TimePicker tp = new TimePicker(context);
adLayout.addView(tp);
final DatePicker dp = new DatePicker(context);
tp.setVisibility(View.GONE);
adLayout.addView(dp);
final Button btnNext = new Button(context);
btnNext.setText("Next>");
adLayout.addView(btnNext);
btnNext.setGravity(1);
Button btnCancel = new Button(context);
btnCancel.setText("Cancel");
adLayout.addView(btnCancel);
btnCancel.setGravity(1);
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
aDialog.cancel();
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final int hour = tp.getHour();
final int min = tp.getMinute();
final String myHour = String.valueOf(hour);
final String myMin = String.valueOf(min);
calendar.set(Calendar.MONTH, dp.getMonth());
calendar.set(Calendar.YEAR, dp.getYear());
calendar.set(Calendar.DAY_OF_MONTH, dp.getDayOfMonth());
dp.setVisibility(View.GONE);
tp.setVisibility(View.VISIBLE);
btnNext.setText("Finish");
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
calendar.set(Calendar.HOUR_OF_DAY, tp.getHour());
calendar.set(Calendar.MINUTE, tp.getMinute());
Intent my_intent = new Intent(context, RingtonePlayingService.class);
pendingIntent = PendingIntent.getService(context, 0, my_intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
if(hour > 12){
String myHour = String.valueOf(hour - 12);
}
if(min < 10)
{
String myMin = "0"+String.valueOf(min);
}
Toast.makeText(context, "Set for- "+tp.getHour()+":"+tp.getMinute() , Toast.LENGTH_LONG).show();
aDialog.cancel();
}
});
}
});
aDialog.setView(adLayout);
aDialog.show();
}
});
//create listener event, when switch is pressed
swTask.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//we using utlShared to update task status
//create instance of utlShared
utlShared myShared = new utlShared(context);
//calling method of task, and giving userName(shared preferences, taskName, taskStatus)
myShared.task(userName, txtTaskName.getText().toString(), txtTaskInfo.getText().toString(), swTask.isChecked());
//we sending a message to the user, and inform him/her about the change
Toast.makeText(context, swTask.isChecked() ? "Task done" : "Task undone", Toast.LENGTH_SHORT).show();
}
});
//return the view with the behavior.....
return viewInflated;
}
private void getData() {
//go to specific shared preferences by user name.....
SharedPreferences taskPref = context.getSharedPreferences(userName, context.MODE_PRIVATE);
//create instance of our myTasks list
myTasks = new ArrayList<>();
Map<String, ?> tasks = taskPref.getAll();
for (Map.Entry<String, ?> oneTask : tasks.entrySet()) {
//insert task to list by Key and Value, we check if value is equal to 1, becuase 1=true 0=false
for(int pos=0 ; pos<myTasks.size() ; pos++){
myTasks.get(pos);
}
String[] str = oneTask.getValue().toString().split(",");
myTasks.add(new taskItem(str[0], str[1], str[2].equals("1")));
}
}
}
And my utlShared class is
public class utlShared {
//context to use later
Context context;
//declatrtion of shared preferences object
private SharedPreferences userPref;
//declaration of shared preferences editor
private SharedPreferences.Editor editor;
public utlShared() {}
public utlShared(Context context)
{
//get context to use it
this.context=context;
//declaretion of shared preferences with file name and file mode (private,public)
userPref=context.getSharedPreferences("users",Context.MODE_PRIVATE);
//declaration of editor
editor=userPref.edit();
}
//get user and password
public void addUser(String userName, String password)
{
//stores in the phone device under data\data\package name
//put in shared preferences user name and password
editor.putString(userName,password);
//commit (save/apply) the changes.
editor.commit();
}
public boolean checkUser(String userName)
{
//get name by key->userName
String checkString = userPref.getString(userName,"na");
//print to logcat a custom message.....
Log.e("checkUser", "checkUser: "+checkString );
//check if userName equals to responded data, if it's na, we don't have the user...
return !checkString.equals("na");
}
public boolean checkUserPassword(String userName, String userPassword)
{
String checkString = userPref.getString(userName,"na");
return checkString.equals(userPassword);
}
public void task(String userName,String taskName,String taskInfo, boolean taskDone)
{
//pointer to user task shared preferences
SharedPreferences taskPref=context.getSharedPreferences(userName, Context.MODE_PRIVATE);
//create editor to change the specific shared preferences
SharedPreferences.Editor taskEditor=taskPref.edit();
//add new task -> if true write 1 else write 0
if(!taskDone){
String myData = taskName+","+taskInfo+","+(taskDone?"1":"0");
taskEditor.putString(taskName,myData);
//apply the changes
taskEditor.commit();
}
}
public void clearTasks(String userName, String taskName, String taskInfo, boolean taskDone)
{
SharedPreferences taskPref=context.getSharedPreferences(userName, Context.MODE_PRIVATE);
SharedPreferences.Editor tskEditor=taskPref.edit();
tskEditor.clear();
tskEditor.commit();
}
}
This method is called from my Welcome class which is
public class Welcome extends AppCompatActivity {
String userName;
Context context;
utlShared myUtl;
ListView taskList;
String taskName;
String taskInfo;
boolean taskDone;
AlarmManager alarmManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
setPointer();
}
private void setPointer()
{
this.context=this;
userName=getIntent().getStringExtra("userName");
myUtl = new utlShared(context);
taskList=(ListView)findViewById(R.id.taskList);
setListData();
alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Toast.makeText(Welcome.this, "welcome user:"+userName, Toast.LENGTH_SHORT).show();
Button btnBack = (Button)findViewById(R.id.btnBack);
FloatingActionButton btnDelete=(FloatingActionButton)findViewById(R.id.btnDelete);
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myUtl.clearTasks(userName, taskName, taskInfo, taskDone);
setListData();
}
});
btnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, MainActivity.class);
startActivity(intent);
finish();
}
});
}
private void setListData() {
final TaskAdapter adapter = new TaskAdapter(context, userName);
taskList.setAdapter(adapter);
}
public void addCustomTask(View view)
{
//create builder
AlertDialog.Builder builder = new AlertDialog.Builder(context);
//set title
builder.setTitle("Add new task!");
//inflate view from layout ->custom layout,null,false as defualt values
View viewInflated= LayoutInflater.from(context).inflate(R.layout.dlg_new_task,null,false);
final EditText txtCustomLine = (EditText)viewInflated.findViewById(R.id.txtHLine);
final EditText txtCustomTask = (EditText)viewInflated.findViewById(R.id.txtTask);
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
builder.setPositiveButton("Add task", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
String myTaskCustom = txtCustomTask.getText().toString();
String myTaskLine = txtCustomLine.getText().toString();
myUtl.task(userName, myTaskCustom, myTaskLine, false);
setListData();
}
});
//display our inflated view in screen
builder.setView(viewInflated);
//show the dialog
builder.show();
}
}
Sorry for the long code but I have spent so much time on that problem and didnt find a normal way to fix it...
Thanks in advance guys, much appreciated!
taskEditor.remove('item tag');
taskEditor.commit();
Guess my question wasnt clear enough but I have found a way to do that.
if(!taskDone){
String myData = taskName+","+taskInfo+","+(taskDone?"1":"0");
taskEditor.putString(taskName,myData);
//apply the changes
taskEditor.commit();
}
else
{
taskEditor.remove(taskName);
taskEditor.commit();
adapter.notifyDataSetChanged();
}
Eventhough its not perfect because I can refresh the view after I update the Editor and only after I restart the app my last deleted tasks disappear.
Cheers and thanks a lot guys!

Categories