This question already has answers here:
How can I serialize my User class for the Firebase Database and fix this error?
(2 answers)
Closed 4 years ago.
Having previously had my application working perfectly, it now continually crashes now that I have attempted to add extra, but almost identical functionally. By extra functionality I mean Edit Texts, Spinners, etc. This is hugely frustrating, as it clearly is something very small that seems to be the issue.
My LogCat is showing that there is an error on Line 114 of my Property class, however, I can't understand why this would be an issue as it did not affect the application before added functionality was implemented.
LogCat
02-26 21:19:20.424 9478-9478/com.example.benchalmers.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.benchalmers.myapplication, PID: 9478
com.google.firebase.database.DatabaseException: Class com.example.benchalmers.myapplication.Property does not define a no-argument constructor. If you are using ProGuard, make sure these constructors are not stripped.
at com.google.android.gms.internal.zzelx.zze(Unknown Source:51)
at com.google.android.gms.internal.zzelw.zzb(Unknown Source:772)
at com.google.android.gms.internal.zzelw.zza(Unknown Source:0)
at com.google.firebase.database.DataSnapshot.getValue(Unknown Source:10)
at com.example.benchalmers.myapplication.PropertyActivity$4.onDataChange(PropertyActivity.java:114)
at com.google.android.gms.internal.zzegf.zza(Unknown Source:13)
at com.google.android.gms.internal.zzeia.zzbyc(Unknown Source:2)
at com.google.android.gms.internal.zzeig.run(Unknown Source:65)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
02-26 21:19:20.425 9478-9478/com.example.benchalmers.myapplication E/UncaughtException: com.google.firebase.database.DatabaseException: Class com.example.benchalmers.myapplication.Property does not define a no-argument constructor. If you are using ProGuard, make sure these constructors are not stripped.
at com.google.android.gms.internal.zzelx.zze(Unknown Source:51)
at com.google.android.gms.internal.zzelw.zzb(Unknown Source:772)
at com.google.android.gms.internal.zzelw.zza(Unknown Source:0)
at com.google.firebase.database.DataSnapshot.getValue(Unknown Source:10)
at com.example.benchalmers.myapplication.PropertyActivity$4.onDataChange(PropertyActivity.java:114)
at com.google.android.gms.internal.zzegf.zza(Unknown Source:13)
at com.google.android.gms.internal.zzeia.zzbyc(Unknown Source:2)
at com.google.android.gms.internal.zzeig.run(Unknown Source:65)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Previous to making these changes, I was able to add, update and delete records perfectly, with no hiccups whatsoever. This is what leads me to believe that the issues I'm having are easily fixed.
At the moment the screen loads up for 1 second and then it crashes almost immediately.
I have made small changes to variable names etc. thinking that that might help, but to no avail.
Any help on this would be much appreciated. I'm very new at Android, and with Stack! First Post!
PropertyActivity.java
package com.example.benchalmers.myapplication;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
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 java.util.ArrayList;
import java.util.List;
public class PropertyActivity extends AppCompatActivity {
public static final String PROPERTY_NAME = "propertyname";
public static final String PROPERTY_ID = "propertyid";
EditText editTextProperty;
EditText editTextPostcode;
EditText editTextBedrooms;
EditText editTextBathrooms;
Button buttonAddProperty;
Spinner spinnerFuel;
Spinner spinnerStatus;
Spinner spinnerEPC;
DatabaseReference databaseProperties;
ListView listViewProperties;
List<Property> propertyList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_property);
databaseProperties = FirebaseDatabase.getInstance().getReference("properties");
editTextProperty = (EditText) findViewById(R.id.editTextProperty);
editTextPostcode = (EditText) findViewById(R.id.editTextPostcode);
editTextBedrooms = (EditText) findViewById(R.id.editTextBedrooms);
editTextBathrooms = (EditText) findViewById(R.id.editTextBathrooms);
buttonAddProperty = (Button) findViewById(R.id.buttonAddProperty);
spinnerStatus = (Spinner) findViewById(R.id.spinnerStatus);
spinnerEPC = (Spinner) findViewById(R.id.spinnerEPC);
spinnerFuel = (Spinner) findViewById(R.id.spinnerFuel);
listViewProperties = (ListView) findViewById(R.id.listViewProperties);
propertyList = new ArrayList<>();
buttonAddProperty.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addProperty();
}
});
listViewProperties.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Property property = propertyList.get(position);
Intent intent = new Intent(getApplicationContext(), AddTenantsActivity.class);
intent.putExtra(PROPERTY_ID, property.getPropertyId());
intent.putExtra(PROPERTY_NAME, property.getPropertyAddress());
startActivity(intent);
}
});
listViewProperties.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Property property = propertyList.get(position);
showUpdateDialog(property.getPropertyId(), property.getPropertyAddress(), property.getPropertyPostcode(), property.getPropertyBedrooms(), property.getPropertyBathrooms(), property.getPropertyStatus(), property.getPropertyEPC(), property.getPropertyFuel());
return false;
}
});
}
#Override
protected void onStart() {
super.onStart();
databaseProperties.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
propertyList.clear();
for(DataSnapshot propertySnapshot : dataSnapshot.getChildren()){
Property property = propertySnapshot.getValue(Property.class);
propertyList.add(property);
}
PropertyList adapter = new PropertyList (PropertyActivity.this, propertyList);
listViewProperties.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void showUpdateDialog(final String id, String propertyAddress, String propertyPostcode, String propertyBedrooms, String propertyBathrooms, String propertyStatus, final String propertyId, String propertyName) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.update_dialog, null);
dialogBuilder.setView(dialogView);
final EditText editTextName = (EditText) dialogView.findViewById(R.id.editTextName);
final Button buttonUpdate = (Button) dialogView.findViewById(R.id.buttonUpdate);
final Spinner spinnerFuel = (Spinner) dialogView.findViewById(R.id.spinnerFuel);
final Button buttonDelete = (Button) dialogView.findViewById(R.id.buttonDelete);
dialogBuilder.setTitle("Updating Property " + propertyName);
final AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
buttonUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = editTextName.getText().toString().trim();
String postcode = editTextPostcode.getText().toString().trim();
String bedrooms = editTextBedrooms.getText().toString().trim();
String bathrooms = editTextBathrooms.getText().toString().trim();
String status = spinnerStatus.getSelectedItem().toString();
String epc = spinnerEPC.getSelectedItem().toString();
String fuel = spinnerFuel.getSelectedItem().toString();
if(TextUtils.isEmpty(name)){
editTextName.setError("Name Required");
return;
}
updateProperty(propertyId, status, postcode, bedrooms, bathrooms, id, name, epc, fuel);
alertDialog.dismiss();
}
});
buttonDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deleteProperty(propertyId);
}
});
}
private void deleteProperty(String propertyId) {
DatabaseReference drProperty = FirebaseDatabase.getInstance().getReference("properties").child(propertyId);
DatabaseReference drTenants = FirebaseDatabase.getInstance().getReference("tenants").child(propertyId);
drProperty.removeValue();
drTenants.removeValue();
Toast.makeText(this, "Property has been deleted", Toast.LENGTH_LONG).show();
}
private boolean updateProperty(String propertyId, String status, String postcode, String bedrooms, String bathrooms, String id, String name, String epc, String fuel){
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("properties").child(id);
Property property = new Property (id, name, postcode, bedrooms, bathrooms, status, epc, fuel);
databaseReference.setValue(property);
Toast.makeText(this, "Property Updated Successfully", Toast.LENGTH_LONG).show();
return true;
}
private void addProperty(){
String address = editTextProperty.getText().toString().trim();
String postcode = editTextPostcode.getText().toString().trim();
String bedrooms = editTextBedrooms.getText().toString().trim();
String bathrooms = editTextBathrooms.getText().toString().trim();
String status = spinnerStatus.getSelectedItem().toString();
String epc = spinnerEPC.getSelectedItem().toString();
String fuel = spinnerFuel.getSelectedItem().toString();
if(!TextUtils.isEmpty(address)){
String id = databaseProperties.push().getKey();
Property property = new Property (id, address, postcode, bedrooms, bathrooms, status, epc, fuel);
databaseProperties.child(id).setValue(property);
Toast.makeText(this, "Property Added", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(this, "You must enter a property", Toast.LENGTH_LONG).show();
}
}
}
Property.java
package com.example.benchalmers.myapplication;
/**
* Created by benchalmers on 21/02/2018.
*/
public class Property {
String propertyId;
String propertyAddress;
String propertyPostcode;
String propertyFuel;
String propertyBedrooms;
String propertyBathrooms;
String propertyEPC;
String propertyStatus;
public Property(String id, String address, String postcode, String bedrooms, String bathrooms, String status, String epc, String fuel ) {
this.propertyId = propertyId;
this.propertyAddress = propertyAddress;
this.propertyPostcode = postcode;
this.propertyFuel = propertyFuel;
this.propertyBedrooms = bedrooms;
this.propertyBathrooms = bathrooms;
this.propertyEPC = epc;
this.propertyStatus = status;
}
public String getPropertyId() {
return propertyId;
}
public String getPropertyAddress() {
return propertyAddress;
}
public String getPropertyPostcode() {
return propertyPostcode;
}
public String getPropertyFuel() {
return propertyFuel;
}
public String getPropertyBedrooms() {
return propertyBedrooms;
}
public String getPropertyBathrooms() {
return propertyBathrooms;
}
public String getPropertyEPC() {
return propertyEPC;
}
public String getPropertyStatus() {
return propertyStatus;
}
}
PropertyList.java
package com.example.benchalmers.myapplication;
import android.app.Activity;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
public class PropertyList extends ArrayAdapter<Property> {
private Activity context;
private List<Property> propertyList;
public PropertyList(Activity context, List<Property> propertyList) {
super(context, R.layout.property_list_layout, propertyList);
this.context = context;
this.propertyList = propertyList;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.property_list_layout, null, true);
TextView textViewProperty = (TextView) listViewItem.findViewById(R.id.textViewProperty);
TextView textViewPostcode = (TextView) listViewItem.findViewById(R.id.textViewPostcode);
TextView textViewBedrooms = (TextView) listViewItem.findViewById(R.id.textViewBedrooms);
TextView textViewBathrooms = (TextView) listViewItem.findViewById(R.id.textViewBathrooms);
TextView textViewStatus = (TextView) listViewItem.findViewById(R.id.textViewStatus);
TextView textViewEPC = (TextView) listViewItem.findViewById(R.id.textViewEPC);
TextView textViewFuel = (TextView) listViewItem.findViewById(R.id.textViewFuel);
Property property = propertyList.get(position);
textViewProperty.setText(property.getPropertyAddress());
textViewPostcode.setText(property.getPropertyPostcode());
textViewBedrooms.setText(property.getPropertyBedrooms());
textViewBathrooms.setText(property.getPropertyBathrooms());
textViewStatus.setText(property.getPropertyStatus());
textViewEPC.setText(property.getPropertyEPC());
textViewFuel.setText(property.getPropertyFuel());
return listViewItem;
}
}
Firebase requires a no-argument constructor in your Property class so that you can use getValue(Property.class). So add this constructor to your Property class:
public Property() {}
Related
I want to create a way which will add item to cart by creating a child cart the in that child it will retrieve current username and then under that it will save all the details of added item
this is the code of the fragment in which cart button is available (course = description,email = price,purl = url of image)
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
public class descfragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
String name, course, email, purl;
public descfragment() {
}
public descfragment(String name, String course, String email, String purl) {
this.name = name;
this.course = course;
this.email = email;
this.purl = purl;
}
public static descfragment newInstance(String param1, String param2) {
descfragment fragment = new descfragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_descfragment, container, false);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AppCompatActivity activity =(AppCompatActivity)getContext();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.wrapper,new recfragment()).addToBackStack(null).commit();
}
});
ImageView imageholder = view.findViewById(R.id.imageholder);
TextView nameholder = view.findViewById(R.id.nameholder);
TextView courseholder = view.findViewById(R.id.courseholder);
TextView emailholder = view.findViewById(R.id.emailholder);
Button cart = view.findViewById(R.id.cartt);
TextView addItem = view.findViewById(R.id.addIteam);
TextView removeItem = view.findViewById(R.id.removeItem);
TextView quantity = view.findViewById(R.id.quantity);
final int[] totalquantity = {1};
nameholder.setText(name);
courseholder.setText(course);
emailholder.setText(email);
if (imageholder != null) {
Glide.with(getContext()).load(purl).into(imageholder);
}
Glide.with(getContext()).load(purl).into(imageholder);
//changing static getemail to int type
//for openig cart
//setting click on textview for increasing the quantity
addItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(totalquantity[0] < 10){
totalquantity[0]++;
quantity.setText(String.valueOf(totalquantity[0]));
}
}
});
removeItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(totalquantity[0] > 1) {
totalquantity[0]--;
quantity.setText(String.valueOf(totalquantity[0]));
}
}
});
return view;
}
#Override
public void onResume() {
super.onResume();
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener((v, keyCode, event) -> {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
AppCompatActivity activity = (AppCompatActivity) getContext();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.wrapper, new recfragment()).addToBackStack(null).commit();
return true;
}
return false;
});
}
}
this is the register activity code in this activity we have the username which needed to be retirived
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.foodcourt.MainActivity;
import com.example.foodcourt.R;
import com.google.android.material.textfield.TextInputLayout;
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;
public class register extends AppCompatActivity {
Button button5;
//create obj of Databaserefrence to access firebase RealTime Database
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReferenceFromUrl("https://url of firebase database/");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
final TextInputLayout nameLayout = findViewById(R.id.Name);
final TextInputLayout phoneLayout = findViewById(R.id.phone);
final TextInputLayout passwordLayout = findViewById(R.id.password);
final TextInputLayout repassLayout = findViewById(R.id.repass);
final Button signup = findViewById(R.id.sign);
final EditText name = nameLayout.getEditText();
final EditText phone = phoneLayout.getEditText();
final EditText password = passwordLayout.getEditText();
final EditText repass = repassLayout.getEditText();
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//get data from editTexts into string
final String nameTxt = name.getText().toString();
final String phoneTxt = phone.getText().toString();
final String passwordTxt = password.getText().toString();
final String repassTxt = repass.getText().toString();
//Check if user filled all details before sending data to firebase
if (nameTxt.isEmpty() || phoneTxt.isEmpty() || passwordTxt.isEmpty() || repassTxt.isEmpty()) {
Toast.makeText(register.this, "Please fill all fields", Toast.LENGTH_SHORT).show();
}
//check if pass are matching
else if (!passwordTxt.equals(repassTxt)) {
Toast.makeText(register.this, "PASSWORDS ARE NOT MATCHING", Toast.LENGTH_SHORT).show();
} else {
databaseReference.child("users").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
//check if phone number is registered before \
if (snapshot.hasChild(phoneTxt)) {
Toast.makeText(register.this, "Already registered", Toast.LENGTH_SHORT).show();
} else {
//sending data to Firebase
//using phoneNumbers
databaseReference.child("users").child(phoneTxt).child("name").setValue(nameTxt);
databaseReference.child("users").child(phoneTxt).child("phone").setValue(phoneTxt);
databaseReference.child("users").child(phoneTxt).child("password").setValue(passwordTxt);
Toast.makeText(register.this, "REGISTERED SUCCESFULLY", Toast.LENGTH_SHORT).show();
startActivity(new Intent(register.this, MainActivity.class));
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
});
}
}
I followed some tutorials but they were for firestore.
I have a 2 radioButtons in my layout. One is for yes and the other is for no when asked if insured or not. When I click my save button and the data posts to firestore, it shows both NO INSURED and YES INSURED. The way I have my code set up is why it's that way but what I want to do is have one source where if the person clicks yes or no then in firestore I will have Insured : Yes or Insured : No. I will post my code down below
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.Toast;
import com.google.android.gms.dynamic.ObjectWrapper;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.firestore.FirebaseFirestore;
import java.util.HashMap;
import java.util.Map;
public class ProviderSignUp extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private static final String TAG = "MainActivity";
private static final String KEY_FNAME = "First Name";
private static final String KEY_LNAME = "Last Name";
private static final String KEY_ADDRESS = "Address";
private static final String KEY_SPINNER_VALUE = "Spinner Value";
private static final String KEY_FIXED= "Fixed Rate";
private static final String KEY_HOURLY = "Hourly Rate";
private static final String KEY_AGE_VALE= "Age Value";
private static final String KEY_DOLLAR_VALUE = "Dollar Value";
private static final String KEY_YES_INSURED = "Yes Insured";
private static final String KEY_NO_INSURED = "No Insured";
private EditText fName;
private EditText lName;
private EditText address;
private Spinner my_spinner;
private RadioButton fixedRadioButton;
private RadioButton hourlyRadioButton;
private EditText ageEditText;
private EditText dollarEditText;
private RadioButton yesButton;
private RadioButton noButton;
// Reference to firestore database
private FirebaseFirestore db = FirebaseFirestore.getInstance();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.provider_signup);
Spinner spinner = findViewById(R.id.mySpinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.provider_choices, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
// FireStore Storage for Provider
fName = findViewById(R.id.firstName);
lName = findViewById(R.id.lastName);
address = findViewById(R.id.Address);
my_spinner = (Spinner)findViewById(R.id.mySpinner);
fixedRadioButton = findViewById(R.id.fixedRadioButton);
hourlyRadioButton = findViewById(R.id.hourlyRadioButton);
ageEditText = findViewById(R.id.ageEditText);
dollarEditText = findViewById(R.id.dollarEditText);
yesButton = findViewById(R.id.yesRadioButton);
noButton = findViewById(R.id.noRadioButton);
}
#Override
public void onBackPressed() {
startActivity(new Intent(ProviderSignUp.this,PreSignUp.class));
finish();
}
// These two methods below are for the spinner in the ProviderSignUp
#Override
// Will show a toast message after user selects spinner item
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
String text = adapterView.getItemAtPosition(position).toString();
Toast.makeText(adapterView.getContext(), text, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
String fname = fName.getText().toString();
String lname = lName.getText().toString();
String my_address = address.getText().toString();
String spinner = my_spinner.getSelectedItem().toString();
String fixed_radioButton = fixedRadioButton.getText().toString();
String hourly_Radiobutton = hourlyRadioButton.getText().toString();
String age = ageEditText.getText().toString();
String dollar = dollarEditText.getText().toString();
String yes_button = yesButton.getText().toString();
String no_button = noButton.getText().toString();
Map<String,Object> myMap = new HashMap<String,Object>();
myMap.put(KEY_FNAME,fname);
myMap.put(KEY_LNAME,lname);
myMap.put(KEY_ADDRESS, my_address);
myMap.put(KEY_FIXED, fixed_radioButton);
myMap.put(KEY_HOURLY, hourly_Radiobutton);
myMap.put(KEY_AGE_VALE, age);
myMap.put(KEY_DOLLAR_VALUE, dollar);
myMap.put(KEY_YES_INSURED, yes_button);
myMap.put(KEY_NO_INSURED, no_button);
myMap.put(KEY_SPINNER_VALUE , spinner);
db.collection("demoProviders").document("First Provider")
.set(myMap).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(ProviderSignUp.this, "User Saved", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ProviderSignUp.this, "Error!", Toast.LENGTH_SHORT).show();
Log.d(TAG, e.toString());
}
});
}
}
First thing first,
When I click my save button and the data posts to firestore
This is not happening according to your code. You should use OnClickListener method to implement your thought. I suggest going through this documentation.
Second thing second,
Hope, you are using RadioGroup for your RadioButton. That won't allow more than one RadioButton to be selected at a single time. Here is how you can implement RadioGroup.
Last thing last,
Use a single key to store a boolean value instead of storing multiple key-value pairs for RadioButton state in Firestore. Try this :
if (radioGroup.getCheckedRadioButtonId() == R.id.yesRadioButton){
myMap.put("isInsured", true);
} else {
myMap.put("isInsured", false);
}
instead of this :
myMap.put(KEY_YES_INSURED, yes_button);
myMap.put(KEY_NO_INSURED, no_button);
If you do all the mentioned steps correctly your database should store one value for your RadioButton states. Try and let us know if this worked or not.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I am encountering an error here. I have designed an app, which involves a User Registration Page and Login Page. User Registration is happening successfully, with data also getting added and Posted to SQLITE.
However, during LOGIN, I am facing an issue. I have to open a new page, once the user logsin. But, the error which I am facing, due to sharedpreference is null pointer exception.
This is my login page , and after I hit the login button, I am encountering the error.
com.example.dell.digitalwallet E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.dell.digitalwallet, PID: 3206
java.lang.NullPointerException: Attempt to invoke interface method 'boolean android.content.SharedPreferences.contains(java.lang.String)' on a null object reference
at com.example.dell.digitalwallet.Login$1.onClick(Login.java:56)
at android.view.View.performClick(View.java:6597)
at android.view.View.performClickInternal(View.java:6574)
at android.view.View.access$3100(View.java:778)
at android.view.View$PerformClick.run(View.java:25881)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6649)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:826)
06-02 12:39:50.866 3206-3206/com.example.dell.digitalwallet I/Process: Sending signal. PID: 3206 SIG: 9
I have created the following classes:
Login.java
package com.example.dell.digitalwallet;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Login extends AppCompatActivity {
private static TextView username;
private static TextView password;
private static EditText User_Name;
private static EditText User_Password;
private static Button login_btn, Registration, passwd_btn, Add_Person;
private SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Click_Button();
}
public void Click_Button() {
username = (TextView)findViewById(R.id.User_Name);
password = (TextView)findViewById(R.id.Password);
Registration = (Button) findViewById(R.id.button_registration);
login_btn = (Button)findViewById(R.id.button_login);
passwd_btn=(Button) findViewById(R.id.button_password);
User_Name = (EditText) findViewById(R.id.Name);
User_Password = (EditText) findViewById(R.id.User_Password);
Add_Person = (Button) findViewById(R.id.add_person);
login_btn.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
String username = User_Name.getText().toString();
String password = User_Password.getText().toString();
// Validate if username, password is filled
if(username.trim().length() > 0 && password.trim().length() > 0){
String uName = null;
String uPassword =null;
if (sharedPreferences.contains(username))
{
uName = sharedPreferences.getString(username,"");
}
if (sharedPreferences.contains(password))
{
uPassword = sharedPreferences.getString(password, "");
}
if (username.equals(uName) && password.equals(uPassword)){
Toast.makeText(Login.this,"User and Password is correct",
Toast.LENGTH_SHORT).show();
//Starting the User's Home Page
Add_Person.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Login.this, Parson_Details.class));
}
});
} else {
Toast.makeText(Login.this,"User and Password is not correct",
Toast.LENGTH_SHORT).show();
}
}
}
}
);
Registration.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Login.this, Users.class));
}
});
passwd_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Login.this, Password.class));
}
}
);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_login, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Parson_Details.java
package com.example.dell.digitalwallet;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.telephony.PhoneNumberFormattingTextWatcher;
import android.text.TextUtils;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
import android.widget.Toast;
import java.lang.String;
public class Parson_Details extends AppCompatActivity {
private String FirstName;
private String MiddleName;
private String LastName;
private String Address;
private int PhoneNumber;
private int TotalCrBal;
private int TotalDbBal;
private static TextView First_Name;
private static TextView Middle_Name;
private static TextView Last_Name;
private static TextView Address_Person;
private static TextView Phone_Number;
private static TextView Total_Cr_Bal;
private static TextView Total_Db_Bal;
private static Button Save;
private static EditText First_N;
private static EditText Middle_N;
private static EditText Last_N;
private static EditText Addr;
private static EditText Phone_N;
private static EditText Cr_Bal;
private static EditText Db_Bal;
private static Button save;
public String getFirst_Name() {return FirstName;}
public void setFirst_Name(String FirstName) {this.FirstName = FirstName;}
public String getMiddle_Name() {return MiddleName;}
public void setMiddle_Name(String Middle_Name) {this.MiddleName = Middle_Name;}
public String getLast_Name() {return LastName;}
public void setLast_Name(String Last_Name) {this.LastName = Last_Name;}
public String getAddress() {return Address;}
public void setAddress(String Address) {this.Address = Address;}
public int getPhone_Number() {return PhoneNumber;}
public void setPhone_Number(int Phone_Number) {this.PhoneNumber = Phone_Number;}
public int getTotal_Cr_Bal() {return TotalCrBal;}
public void setTotal_Cr_Bal(int TotalCrBal) {this.TotalCrBal = TotalCrBal;}
public int getTotalDbBal() {return TotalDbBal;}
public void setTotalDbBal(int TotalDbBal) {this.TotalDbBal = TotalDbBal;}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homescreen);
getSupportActionBar().hide();
Click_Save_Button();
}
public void Click_Save_Button() {
First_Name = (TextView) findViewById(R.id.First_Name);
Middle_Name = (TextView)findViewById(R.id.Middle_Name);
Last_Name = (TextView) findViewById(R.id.Last_Name);
Address_Person= (TextView) findViewById(R.id.Address);
Phone_Number=(TextView) findViewById(R.id.Phone_Number);
Total_Cr_Bal = (TextView) findViewById(R.id.Total_Cr_Bal);
Total_Db_Bal = (TextView) findViewById(R.id.Total_Db_Bal);
Save = (Button) findViewById(R.id.save);
First_N = (EditText) findViewById(R.id.First_N);
Middle_N = (EditText)findViewById(R.id.Middle_N);
Last_N = (EditText) findViewById(R.id.Last_N);
Addr = (EditText)findViewById(R.id.Addr);
Phone_N=(EditText) findViewById(R.id.Phone_N);
Cr_Bal = (EditText) findViewById(R.id.Cr_Bal);
Db_Bal = (EditText) findViewById(R.id.Db_Bal);
Save = (Button) findViewById(R.id.save);
}
}
Parson_Details.java is not complete. I need to first reach to the homescreen of the added user, once the login button is clicked, and here, a new activity, called Add_Person has to be launched.
What exactly am I doing wrong?
Above Click_Button() method , past that
sharedPrefernces = PreferenceManager.getDefaultSharedPreferences(this);
You have not initialized SharedPreferences object means its null. First initialize it like this SharedPreferences sharedPrefernces = getActivity().getPreferences(Context.MODE_PRIVATE);
Write these line before calling your Click_Button Function
I have 2 different Fragments and in first Fragment, I am adding a new student entry to my custom Student ArrayList. I also have a ListView to show my student list in my second Fragment. However, when I go to my second Fragment, it doesn't update the latest ListView. So my question is that how can I update my ListView after I change my Fragment tab?
registerBtn simply adds a new entry to my studentsArrayList.
At first, I tried to use "Get" button to update my ListView but it didn't work. What I want to do is that refreshing my ListView whenever I pass to my StudentsFragment.
RegisterFragment.java:
package com.rawsly.android.schoolprogram;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Random;
public class RegisterFragment extends Fragment {
private static final String TAG = "RegisterFragment";
public ArrayList<Students> studentsArrayList = new ArrayList<>();
private ArrayList<Long> idList = new ArrayList<>();
private TextView studentID;
private Button registerBtn, clearBtn, exitBtn;
private EditText editName, editLastName, editGender, editFaculty, editDepartment, editAdvisor;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.register_fragment, container, false);
studentID = (TextView) view.findViewById(R.id.studentID);
studentID.setText(String.valueOf(generateID()));
editName = (EditText) view.findViewById(R.id.editName);
editLastName = (EditText) view.findViewById(R.id.editLastName);
editGender = (EditText) view.findViewById(R.id.editGender);
editFaculty = (EditText) view.findViewById(R.id.editFaculty);
editDepartment = (EditText) view.findViewById(R.id.editDepartment);
editAdvisor = (EditText) view.findViewById(R.id.editAdvisor);
registerBtn = (Button) view.findViewById(R.id.registerBtn);
registerBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String id = studentID.getText().toString();
String name = editName.getText().toString();
String lastName = editLastName.getText().toString();
String gender = editGender.getText().toString();
String faculty = editFaculty.getText().toString();
String department = editDepartment.getText().toString();
String advisor = editAdvisor.getText().toString();
studentsArrayList.add(new Students(id, name, lastName, gender, faculty, department, advisor));
Toast.makeText(getContext(), "New entry added.", Toast.LENGTH_SHORT).show();
}
});
clearBtn = (Button) view.findViewById(R.id.clearBtn);
clearBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editName.setText(null);
editLastName.setText(null);
editGender.setText(null);
editFaculty.setText(null);
editDepartment.setText(null);
editAdvisor.setText(null);
studentID.setText(String.valueOf(generateID()));
}
});
exitBtn = (Button) view.findViewById(R.id.exitBtn);
exitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
System.exit(1);
}
});
return view;
}
// Generates a random ID.
public long generateID() {
Random rnd = new Random();
char [] digits = new char[11];
digits[0] = (char) (rnd.nextInt(9) + '1');
for(int i=1; i<digits.length; i++) {
digits[i] = (char) (rnd.nextInt(10) + '0');
}
long result = Long.parseLong(new String(digits));
if(idList.contains(result)) {
return generateID();
} else {
return result;
}
}
}
StudentsFragment.java:
package com.rawsly.android.schoolprogram;
import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class StudentsFragment extends Fragment {
private static final String TAG = "StudentsFragment";
private EditText txtSearch;
private ListView studentsListView;
private Button getStudents, updateStudent, deleteStudent, exitBtn;
public StudentsAdapter adapter;
public ArrayList<Students> studentsArrayList = new ArrayList<>();;
public int selectedItem = -1; // to update or delete the data
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.students_fragment, container, false);
// Dummy Data
studentsArrayList.add(new Students("1122334455", "Ahmet", "Özdemir", "Male", "Mühendislik ve Doğa Bilimleri", "Bilgisayar Mühendisliği", "Tuğba Yıldız"));
studentsArrayList.add(new Students("1234567890", "Ezgi", "İmamoğlu", "Female", "Mühendislik ve Doğa Bilimleri", "Bilgisayar Mühendisliği", "Tuğba Yıldız"));
studentsArrayList.add(new Students("0123456789", "Enise", "Usta", "Female", "Sosyal ve Beşeri Bilimler Fakültesi", "Uluslararası İlişkiler", "Murat Orhun"));
studentsArrayList.add(new Students("1122445588", "Sinem", "Ünver", "Female", "Mühendislik ve Doğa Bilimleri", "Endüstri Mühendisliği", "Zehra Yılmaz"));
studentsArrayList.add(new Students("2546882547", "Zehra", "Gürçay", "Female", "Mühendislik ve Doğa Bilimleri", "Endüstri Mühendisliği", "Şule Gündüz"));
adapter = new StudentsAdapter(getContext(), studentsArrayList);
studentsListView = (ListView) view.findViewById(R.id.studentsListView);
studentsListView.setAdapter(adapter);
studentsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
selectedItem = position;
Toast.makeText(getContext(), "Selected entry: " + (selectedItem+1), Toast.LENGTH_LONG).show();
}
});
// Opens a dialog window
getStudents = (Button) view.findViewById(R.id.getStudents);
getStudents.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
adapter.notifyDataSetChanged();
studentsListView.invalidate();
}
}); // end of the add action
// To delete the selected School object
deleteStudent = (Button) view.findViewById(R.id.deleteStudent);
deleteStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(selectedItem == -1) {
Toast.makeText(getContext(), "Please, select an entry first.", Toast.LENGTH_SHORT).show();
} else {
studentsArrayList.remove(selectedItem);
selectedItem = -1;
adapter.notifyDataSetChanged();
Toast.makeText(getContext(), "Selected entry is deleted.", Toast.LENGTH_SHORT).show();
}
}
}); // end of the delete action
// To exit the program
exitBtn = (Button) view.findViewById(R.id.exitBtn);
exitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
System.exit(1);
}
}); // end of the exit action
// To update the selected School object
updateStudent = (Button) view.findViewById(R.id.updateStudent);
updateStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(selectedItem == -1) {
Toast.makeText(getContext(), "Please, select an entry first.", Toast.LENGTH_SHORT).show();
} else {
final Dialog dialog = new Dialog(getContext());
dialog.setContentView(R.layout.update_student);
dialog.setTitle("Update An Entry");
// Dialog components - EditText, Button
String id = studentsArrayList.get(selectedItem).id;
String name = studentsArrayList.get(selectedItem).name;
String lastName = studentsArrayList.get(selectedItem).lastName;
String gender = studentsArrayList.get(selectedItem).gender;
String faculty = studentsArrayList.get(selectedItem).faculty;
String department = studentsArrayList.get(selectedItem).department;
String advisor = studentsArrayList.get(selectedItem).advisor;
final TextView studentID = (TextView) dialog.findViewById(R.id.studentID);
final EditText editName = (EditText) dialog.findViewById(R.id.editName);
final EditText editLastName = (EditText) dialog.findViewById(R.id.editLastName);
final EditText editGender = (EditText) dialog.findViewById(R.id.editGender);
final EditText editFaculty = (EditText) dialog.findViewById(R.id.editFaculty);
final EditText editDepartment = (EditText) dialog.findViewById(R.id.editDepartment);
final EditText editAdvisor = (EditText) dialog.findViewById(R.id.editAdvisor);
studentID.setText(id);
editName.setText(name);
editLastName.setText(lastName);
editGender.setText(gender);
editFaculty.setText(faculty);
editDepartment.setText(department);
editAdvisor.setText(advisor);
Button updateStudent = (Button) dialog.findViewById(R.id.updateStudent);
Button clearStudent = (Button) dialog.findViewById(R.id.clearStudent);
Button cancelStudent = (Button) dialog.findViewById(R.id.cancelStudent);
// Updates the selected School object
updateStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String id = studentID.getText().toString();
String name = editName.getText().toString();
String lastName = editLastName.getText().toString();
String gender = editGender.getText().toString();
String faculty = editFaculty.getText().toString();
String department = editDepartment.getText().toString();
String advisor = editAdvisor.getText().toString();
studentsArrayList.get(selectedItem).setId(id);
studentsArrayList.get(selectedItem).setName(name);
studentsArrayList.get(selectedItem).setLastName(lastName);
studentsArrayList.get(selectedItem).setGender(gender);
studentsArrayList.get(selectedItem).setFaculty(faculty);
studentsArrayList.get(selectedItem).setDepartment(department);
studentsArrayList.get(selectedItem).setAdvisor(advisor);
adapter.notifyDataSetChanged();
Toast.makeText(getContext(), "An entry is updated.", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
// Clears all fields
clearStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editName.setText(null);
editLastName.setText(null);
editGender.setText(null);
editFaculty.setText(null);
editDepartment.setText(null);
editAdvisor.setText(null);
}
});
// Dismisses the dialog
cancelStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog.show();
adapter.notifyDataSetChanged(); // notifying adapter about changes
}
}
}); // end of the update action
return view;
}
}
"Troubleshooting
If calling notifyDataSetChanged() doesn't work all the layout methods won't help either. Believe me the ListView was properly updated. If you fail to find the difference you need to check where the data in your adapter comes from.
If this is just a collection you're keeping in memory check that you actually deleted from or added the item(s) to the collection before calling the notifyDataSetChanged().
If you're working with a database or service backend you'll have to call the method to retrieve the information again (or manipulate the in memory data) before calling the notifyDataSetChanged().
The thing is this notifyDataSetChanged only works if the dataset has changed. So that is the place to look if you don't find changes coming through. Debug if needed."
duplicate: How to refresh Android listview?
I am trying to create a time line to represent all the added announcement in CardView ,
I follow every single things in this tutorial
https://www.youtube.com/watch?v=WmPGLoB28T8
but an exception throw when I was trying to retrieve the data from firebase cant now why and how to handle it :
MyHolder :
package com.volunteer.android.HolderClasses;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.volunteer.android.R;
public class AnnouncementHolder extends RecyclerView.ViewHolder {
public TextView orgtname ;
public TextView Evenname;
public CardView HomeCard ;
public TextView Start;
public TextView City;
public TextView Field;
public TextView moreinfo;
public TextView contactInfo;
public ImageView pic ;
public ImageView report ;
FirebaseAuth mAuth ;
DatabaseReference reportRef ;
public AnnouncementHolder(View view){
super(view);
mAuth=FirebaseAuth.getInstance();
reportRef= FirebaseDatabase.getInstance().getReference().child("Reports");
reportRef.keepSynced(true);
HomeCard=(CardView)view.findViewById(R.id.CardviewHome);
orgtname = (TextView) view.findViewById(R.id.textViewOragName);
Evenname = (TextView) view.findViewById(R.id.textViewEventName);
Start = (TextView) view.findViewById(R.id.TextViewDate);
City = (TextView) view.findViewById(R.id.TextViewCity);
Field = (TextView) view.findViewById(R.id.TextViewField);
moreinfo = (TextView) view.findViewById(R.id.TextViewPost);
contactInfo = (TextView) view.findViewById(R.id.contact);
pic =(ImageView)view.findViewById(R.id.ImagproSe);
report=(ImageView)view.findViewById(R.id.report_btn);
}
public void setPost_key(final String postKey){
reportRef.addValueEventListener(new com.google.firebase.database.ValueEventListener() {
#Override
public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {
if(dataSnapshot.child(postKey).hasChild(mAuth.getCurrentUser().getUid())){
report.setImageResource(R.drawable.ic_link);
}
else {
report.setImageResource(R.mipmap.ic_report_black_24dp);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
MyAdapter:
[package com.volunteer.android.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.google.firebase.auth.FirebaseAuth;
import com.volunteer.android.HolderClasses.AnnouncementHolder;
import com.volunteer.android.R;
import com.volunteer.android.data.Announcement;
import com.volunteer.android.data.Constants;
import java.util.ArrayList;
/**
* Created by macbookpro on 8/20/16 AD.
*/
public class AnnouncementAdapter extends RecyclerView.Adapter<AnnouncementHolder> {
Context c;
ArrayList<Announcement> Announcements = new ArrayList<>();
String Uid;
Firebase announcRef ;
Firebase reportRef ;
FirebaseAuth mAuth ;
// final String AnnKey ;
private boolean mProccesLike=false ;
public AnnouncementAdapter(Context c, ArrayList<Announcement> Announcements , String Uid){
this.c=c;
this.Announcements=Announcements;
this.Uid=Uid;
// expRef=new Firebase(Constants.USER_ECPERIENCE_PATH);
mAuth=FirebaseAuth.getInstance();
reportRef=new Firebase(Constants.FIREBASE_URL+"/Reports");
}
#Override
public void onBindViewHolder(AnnouncementHolder holder, int position) {
final Announcement announcement = Announcements.get(position);
holder.orgtname.setText((Announcements.get(position)).getOrgName());
holder.Evenname.setText((Announcements.get(position)).getEventName());
holder.contactInfo.setText((Announcements.get(position)).getContact());
holder.Field.setText((Announcements.get(position)).getField());
holder.Start.setText((Announcements.get(position)).getStartDate());
holder.moreinfo.setText((Announcements.get(position)).getMoreInfo());
holder.City.setText((Announcements.get(position)).getCity());
// holder.setPost_key(announcement.getAnnId());
holder.report.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mProccesLike=true ;
reportRef.addValueEventListener(new com.firebase.client.ValueEventListener() {
#Override
public void onDataChange(com.firebase.client.DataSnapshot dataSnapshot) {
if (mProccesLike){
if (dataSnapshot.child(announcement.getAnnId()).hasChild(mAuth.getCurrentUser().getUid())){
reportRef.child(announcement.getAnnId()).child(mAuth.getCurrentUser().getUid()).removeValue();
mProccesLike=false ;
}else {
reportRef.child(announcement.getAnnId()).child(mAuth.getCurrentUser().getUid()).setValue("True");
mProccesLike=false ;
}
}}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
});
}
public void animate(RecyclerView.ViewHolder viewHolder) {
final Animation animAnticipateOvershoot = AnimationUtils.loadAnimation(c, R.anim.anticipateovershoot_interpolator);
viewHolder.itemView.setAnimation(animAnticipateOvershoot);
}
#Override
public AnnouncementHolder onCreateViewHolder (ViewGroup parent, int viewType){
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view_home, parent, false);
AnnouncementHolder holder =new AnnouncementHolder(v);
return holder;
}
#Override
public int getItemCount() {
return Announcements.size(); //mAssignments.size();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
// Insert a new item to the RecyclerView on a predefined position
public void insert(Announcement announcement, int position) {
Announcements.add(position, announcement);
notifyItemInserted(position);
}
// Remove a RecyclerView item containing a specified Data object
public void remove(Announcement announcement) {
int position = Announcements.indexOf(announcement);
Announcements.remove(position);
notifyItemRemoved(position);
}
}][1]
Saving method :
public void saveAnnouncement (View view){
org=editTextOrg.getText().toString().trim();
if (org.length()>300){
return;
}
Event=editTextEvent.getText().toString().trim();
if (Event.length()>300){
return;
}
sDate=editTextSd.getText().toString().trim();
if (sDate.length()>300){
return;}
info=editTextInfo.getText().toString().trim();
if (info.length()>300){
return;
}
contact=editTextContat.getText().toString().trim();
if (contact.length()>300){
return;
}
if (cityName==null){
return;
}
if (Feild==null){
return;
}
sDate=editTextSd.getText().toString().trim();
Announcement announcement = new Announcement(Uid,"" ,org, Event, sDate, cityName,Feild , info , contact );
//Map<String, Object> map = new HashMap<>();
// map.put("announcement",announcement);
mRef.child("Announcement").push().setValue(announcement);
The Retriving class :
package com.volunteer.android.Fragment;
/**
* Created by macbookpro on 8/23/16 AD.
*/
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.firebase.client.ChildEventListener;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.google.firebase.auth.FirebaseAuth;
import com.volunteer.android.R;
import com.volunteer.android.adapter.AnnouncementAdapter;
import com.volunteer.android.data.Announcement;
import com.volunteer.android.data.Constants;
import java.util.ArrayList;
/**
* Created by jnoo1 on 8/11/2016.
*/
public class Home extends Fragment {
RecyclerView rv ;
ArrayList<Announcement> announcements = new ArrayList<>();
AnnouncementAdapter adapter ;
Firebase myRef ;
FloatingActionButton AddAnouncement ;
FirebaseAuth mAuth ;
String Uid ;
public Home(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view =inflater.inflate(R.layout.fragment_etailse,container,false);
Firebase.setAndroidContext(getActivity());
myRef = new Firebase(Constants.FIREBASE_URL);
rv =(RecyclerView)view.findViewById(R.id.recyclerViewHome);
rv.setLayoutManager(new LinearLayoutManager(getActivity()));
AddAnouncement=(FloatingActionButton) view.findViewById(R.id.fab1);
mAuth=FirebaseAuth.getInstance();
Uid=mAuth.getCurrentUser().getUid();
adapter=new AnnouncementAdapter(getActivity(),announcements,Uid);
rv.setAdapter(adapter);
RefreshData();
return view ;
}
public void RefreshData (){
myRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
getUpdates(dataSnapshot);}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
getUpdates(dataSnapshot);}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
getUpdates(dataSnapshot);}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {}
#Override
public void onCancelled(FirebaseError firebaseError) {}
}); }
private void getUpdates (DataSnapshot dataSnapshot ){
announcements.clear();
for (DataSnapshot Ds : dataSnapshot.getChildren())
{
Announcement announcement=new Announcement();
announcement.setOrgName( Ds.getValue(Announcement.class).getOrgName());
announcement.setEventName(Ds.getValue(Announcement.class).getEventName());
announcement.setCity(Ds.getValue(Announcement.class).getCity());
announcement.setField(Ds.getValue(Announcement.class).getField());
announcement.setStartDate(Ds.getValue(Announcement.class).getStartDate());
announcement.setMoreInfo(Ds.getValue(Announcement.class).getMoreInfo());
announcement.setContact(Ds.getValue(Announcement.class).getContact());
// announcement.setAnnId((String) Ds.getKey());
//exp.setCity((String) dataSnapshot.child("city").getValue());
announcements.add(announcement);
}
if (announcements.size()>0){
adapter=new AnnouncementAdapter(getActivity(),announcements,Uid);
rv.setAdapter(adapter); }
else {
Toast.makeText(getActivity() ," No thing to show ", Toast.LENGTH_SHORT).show(); } }
}
The error crash my app evrytime :
09-15 17:11:35.622 5862-5884/com.volunteer.android I/DynamiteModule: Considering local module com.google.android.gms.tagmanager:3 and remote module com.google.android.gms.tagmanager:3
09-15 17:11:35.622 5862-5884/com.volunteer.android I/DynamiteModule: Selected local version of com.google.android.gms.tagmanager
09-15 17:11:35.648 5862-5884/com.volunteer.android W/GoogleTagManager: Tag Manager's event handler WILL NOT be installed (no container loaded)
09-15 17:11:35.648 5862-5884/com.volunteer.android I/GoogleTagManager: Tag Manager initilization took 23ms
09-15 17:11:35.819 5862-5862/com.volunteer.android D/FirebaseCrashApiImpl: throwable com.firebase.client.FirebaseException: Failed to bounce to type
09-15 17:11:35.849 5862-5862/com.volunteer.android E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.volunteer.android, PID: 5862
com.firebase.client.FirebaseException: Failed to bounce to type
at com.firebase.client.DataSnapshot.getValue(DataSnapshot.java:183)
at com.volunteer.android.Fragment.Home.getUpdates(Home.java:107)
at com.volunteer.android.Fragment.Home.access$000(Home.java:32)
at com.volunteer.android.Fragment.Home$1.onChildAdded(Home.java:85)
at com.firebase.client.core.ChildEventRegistration.fireEvent(ChildEventRegistration.java:48)
at com.firebase.client.core.view.DataEvent.fire(DataEvent.java:45)
at com.firebase.client.core.view.EventRaiser$1.run(EventRaiser.java:38)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "UserInformation" (class com.volunteer.android.data.Announcement), not marked as ignorable (11 known properties: , "contact", "moreInfo", "eventName", "city", "orgName", "startDate", "uid", "field", "annId", "picture", "key"])
at [Source: java.io.StringReader#1a04a2ef; line: 1, column: 21] (through reference chain: com.volunteer.android.data.Announcement["UserInformation"])
at com.fasterxml.jackson.databind.DeserializationContext.reportUnknownProperty(DeserializationContext.java:555)
at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:708)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1160)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:315)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:121)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2888)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2034)
at com.firebase.client.DataSnapshot.getValue(DataSnapshot.java:181)
at com.volunteer.android.Fragment.Home.getUpdates(Home.java:107)
at com.volunteer.android.Fragment.Home.access$000(Home.java:32)
at com.volunteer.android.Fragment.Home$1.onChildAdded(Home.java:85)
at com.firebase.client.core.ChildEventRegistration.fireEvent(ChildEventRegistration.java:48)
at com.firebase.client.core.view.DataEvent.fire(DataEvent.java:45)
at com.firebase.client.core.view.EventRaiser$1.run(EventRaiser.java:38)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
09-15 17:11:36.234 5993-5993/com.volunteer.android:background_crash W/DynamiteModule: Local module descriptor class for com.google.android.gms.crash not found.
package com.volunteer.android.data;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.firebase.database.Exclude;
/**
* Created by macbookpro on 8/10/16 AD.
*/
public class Announcement {
#JsonIgnore
private String Key ;
private String OrgName;
private String EventName;
private String StartDate;
private String City;
private String Field;
private String MoreInfo;
private String Contact;
private String Picture;
private String Uid;
private String AnnId ;
public Announcement (){
// defualt ;
}
public Announcement (String Uid, String AnnId ,String OrgName,String EventName,String StartDate,String City,String Field, String MoreInfo, String Contact){
this.Uid=Uid;
this.AnnId=AnnId;
this.OrgName=OrgName;
this.EventName=EventName;
this.StartDate=StartDate;
this.City=City;
this.Field=Field;
this.MoreInfo=MoreInfo;
this.Contact=Contact;
}
public void setAnnId (String AnnId){this.AnnId=AnnId;}
public String getAnnId (){return AnnId;}
public void setKey(String Key){
Key=Key;
}
#Exclude
public String getKey(){
return Key;
}
public void setUid (String Uid){this.Uid=Uid;}
public String getUid (){return Uid ; }
public void setOrgName(String orgName){
OrgName=orgName;
}
public String getOrgName(){
return OrgName;
}
public void setEventName(String EName){
EventName=EName;
}
public String getEventName(){
return EventName;
}
public void setStartDate(String Date){
StartDate= Date;
}
public String getStartDate(){
return StartDate;
}
public void setCity(String c){
City=c;
}
public String getCity(){
return City;
}
public void setField(String f){
Field=f;
}
public String getField(){
return Field;
}
public void setMoreInfo(String m){
MoreInfo=m;
}
public String getMoreInfo(){
return MoreInfo;
}
public void setContact(String Contact){
this.Contact=Contact;
}
public String getContact(){
return Contact;
}
public void setPicture(String p){
Picture=p;
}
public String getPicture(){
return Picture;
}
}