I have a MainAtivity which has some EditText and 2 button. Save button will save user input to ListView and List button to show ListView (which I display in second activity).
Is there anyway to collect data from multiple inputs then pass it to other activity. And after get that data how to combine it to a List item.
Please show me some code and explain cause I'm a beginner.
I have read some post and they suggest use startActivityForResult, intent, bundles but I still don't understand.
This is my Main class:
public class MainActivity extends AppCompatActivity {
String str, gender, vaccine, date;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button okay = (Button) findViewById(R.id.btnOk);
Button list = (Button) findViewById(R.id.btnList);
EditText name = (EditText) findViewById(R.id.inputName);
EditText address = (EditText) findViewById(R.id.inputAdd);
EditText phone = (EditText) findViewById(R.id.inputPhone);
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
RadioButton female = (RadioButton) findViewById(R.id.inputFemale);
RadioButton male = (RadioButton) findViewById(R.id.inputMale);
CheckBox first = (CheckBox)findViewById(R.id.inputFirst);
CheckBox second = (CheckBox)findViewById(R.id.inputSecond);
CheckBox third = (CheckBox)findViewById(R.id.inputThird);
EditText datefirst = (EditText) findViewById(R.id.dateFirst);
EditText datesecond = (EditText) findViewById(R.id.dateSecond);
EditText datethird = (EditText) findViewById(R.id.dateThird);
TextView result = (TextView)findViewById(R.id.textResult);
okay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(female.isChecked()) gender = female.getText().toString();
if(male.isChecked()) gender = male.getText().toString();
if(first.isChecked()) {
vaccine = first.getText().toString();
date = datefirst.getText().toString();
}
if(second.isChecked()) {
vaccine = second.getText().toString();
date = datesecond.getText().toString();
}
if(third.isChecked()) {
vaccine = third.getText().toString();
date = datethird.getText().toString();
}
str = name.getText().toString() + "\n" + address.getText().toString() + "\n" + phone.getText().toString() + "\n" +
gender + "\n" + vaccine + "\n" + date;
result.setText(str);
Toast.makeText(getApplicationContext(),result.getText().toString(),Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, PersonView.class);
intent.putExtra("NAME",name.getText().toString());
startActivity(intent);
}
});
list.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, PersonView.class);
startActivity(intent);
}
});
}
}
This is my ListView class:
public class PersonView extends AppCompatActivity {
ArrayList<Person> listPerson;
PersonListViewAdapter personListViewAdapter;
ListView listViewPerson;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
Intent intent = getIntent();
String message = intent.getStringExtra("NAME");
Button back = (Button) findViewById(R.id.btnBack);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(PersonView.this, MainActivity.class);
//startActivityForResult(intent,2);
}
});
listPerson = new ArrayList<>();
listPerson.add(new Person("Lieu Mai","25 Mac Dinh Chi", "0786867073", "female","3 injection", "24/07/2000"));
personListViewAdapter = new PersonListViewAdapter(listPerson);
listViewPerson = findViewById(R.id.listPerson);
listViewPerson.setAdapter(personListViewAdapter);
}
class Person {
String name, address, phone, gender, vaccine, date;
public Person( String name, String address, String phone, String gender, String vaccine, String date) {
this.name = name;
this.address = address;
this.phone = phone;
this.gender = gender;
this.vaccine = vaccine;
this.date = date;
}
}
class PersonListViewAdapter extends BaseAdapter {
final ArrayList<Person> listPerson;
PersonListViewAdapter(ArrayList<Person> listPerson) {
this.listPerson = listPerson;
}
#Override
public int getCount() {
return listPerson.size();
}
#Override
public Object getItem(int position) {
return listPerson.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View viewPerson;
if (convertView == null) {
viewPerson = View.inflate(parent.getContext(), R.layout.person_view, null);
} else viewPerson = convertView;
Person person = (Person) getItem(position);
((TextView) viewPerson.findViewById(R.id.txtName)).setText(String.format("Name: %s", person.name));
((TextView) viewPerson.findViewById(R.id.txtAddress)).setText(String.format("Address : %s", person.address));
((TextView) viewPerson.findViewById(R.id.txtPhone)).setText(String.format("Phone number: %s", person.phone));
((TextView) viewPerson.findViewById(R.id.txtGender)).setText(String.format("Gender: %s", person.gender));
((TextView) viewPerson.findViewById(R.id.txtVaccine)).setText(String.format("Vaccine: %s", person.vaccine));
((TextView) viewPerson.findViewById(R.id.txtDate)).setText(String.format("Date: %s", person.date));
return viewPerson;
}
}
}
You should look into the Singleton pattern. It is very simple as there is no external DB. What it essentially is a class that manages the data and lets other classes and activities use the data while not allowing duplication.
You have a model Person
public class Person {
private String name;
public String address;
...
constructors and getters and setters
Create a class PersonsSingelton something like this.
public class PersonManagerSingleton {
private PersonManagerSingleton() {
loadPersonsDataSet();
}
private static PersonManagerSingleton instance = null;
public static PersonManagerSingleton getInstance() {
// if there is a instance already created use that instance of create new instance
// instance created in MainActivity and you try to create a new instance in Details
// should not happen as that will cause data duplication.
if (instance == null) {
instance = new PersonManagerSingleton();
}
return instance;
}
private ArrayList<Person> personList = new ArrayList<Person>();
private void loadPersonsDataSet() {
this.personList.add(new Person(...));
this.personList.add(new Person(...));
this.personList.add(new Person(...));
this.personList.add(new Person(...));
}
public ArrayList<Person> getpersonList() {
return personList;
}
public Person getPersonByID(int PersonNumber) {
for (int i = 0; i < this.personList.size(); i++) {
Person curPerson = this.personList.get(i);
if (curPerson.getNumber() == PersonNumber) {
return curPerson;
}
}
return null;
}
// methods for adding a new person used in Activity with the form.
// other methods ...
}
This would be like a state in React. of the State Manager.
Your person adapter constructor has to accept an ArrayList<Person> listPerson. So modify the activity passing the data to pass only the position of the ListView clicked. You need to modify your Adapter for that.
Use the Singleton created to access the data.
PersonManagerSingleton personSingelton = PersonManagerSingleton.getInstance();
ArrayList<Person> listPerson = personSingelton.getPersonList();
PersonAdapter Person = new PersonAdapter(listPerson);
So now only things left is to modify the Persons adapter to pass position using Intent and nothing else. and then you can use the instance of Singleton in other files to access the data using the listPerson.get(position) and using getters and setters.
Link to a project like this.
https://github.com/smitgabani/anroid_apps_using_java/tree/main/pokemon_app
Related
I have two array lists, one for employees, another for their availabilities. The arrays are of different size. I don't see the problem with that when I'm using the array of the larger size in getItemCount():
#Override
public int getItemCount() {
return allEmployees.size();
}
I set recycler view to get all employee items, however my availability is a shorter list. If I have 6 availability's and 12 employees everything goes smooth on the first page as it only shows the 6 employees. But when I scroll down it will crash as there is a 7th employee but no 7th availability.
Recycler View :
public class RecycleViewAdapter extends RecyclerView.Adapter<RecycleViewAdapter.MyViewHolder> {
List<EmployeeModel> allEmployees;
List<AvailabilityModel> allAvailabilitys;
Context context;
public RecycleViewAdapter(List<EmployeeModel> allEmployees, List<AvailabilityModel> allAvailabilitys, Context context) {
this.allAvailabilitys = allAvailabilitys;
this.allEmployees = allEmployees;
this.context = context;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_view_employee, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
AvailabilityModel available = allAvailabilitys.get(position);
EmployeeModel employee = allEmployees.get(position);
holder.employeeID.setText(String.valueOf(allEmployees.get(position).getEID()));
holder.firstName.setText(allEmployees.get(position).getfName());
holder.lastName.setText(allEmployees.get(position).getlName());
//holder.position = position;
holder.employee = employee;
holder.editButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, EditEmployee.class);
intent.putExtra("Editing", employee);
context.startActivity(intent);
}
});
holder.availabilityButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, availability_screen_code.class);
intent.putExtra("Available", employee);
intent.putExtra("Days", available);
context.startActivity(intent);
}
});
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, ViewEmployee.class);
intent.putExtra("Viewing", employee);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return allEmployees.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
TextView firstName;
TextView lastName;
TextView employeeID;
int position;
ImageButton editButton;
ImageButton availabilityButton;
EmployeeModel employee;
ConstraintLayout parentLayout;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
firstName = itemView.findViewById(R.id.fNameView);
lastName = itemView.findViewById(R.id.lNameView);
employeeID = itemView.findViewById(R.id.eIDView);
editButton = itemView.findViewById(R.id.imageButton2);
availabilityButton = itemView.findViewById(R.id.imageButton4);
parentLayout = itemView.findViewById(R.id.parentLayout);
}
}
}
Where I'm using the position:
public class availability_screen_code extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private Spinner mondaySpinner, tuesdaySpinner, wednesdaySpinner, thursdaySpinner, fridaySpinner, saturdaySpinner, sundaySpinner;
// private String mondayChoice, tuesdayChoice, wednesdayChoice, thursdayChoice, fridayChoice, saturdayChoice, sundayChoice;
// private static final boolean [] choices = new boolean[6];
private ImageButton confirmation;
EmployeeDBAssist employeeDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.availability_screen);
mondaySpinner = findViewById(R.id.mondaySpinner);
tuesdaySpinner = findViewById(R.id.tuesdaySpinner);
wednesdaySpinner = findViewById(R.id.wednesdaySpinner);
thursdaySpinner = findViewById(R.id.thursdaySpinner);
fridaySpinner = findViewById(R.id.fridaySpinner);
saturdaySpinner = findViewById(R.id.saturdaySpinner);
sundaySpinner = findViewById(R.id.sundaySpinner);
confirmation = findViewById(R.id.confirm);
//this is linked to the recycler which gets an entire list of availability!
Bundle bundle = getIntent().getExtras();
AvailabilityModel available = (AvailabilityModel) getIntent().getSerializableExtra("Days");
EmployeeModel employee = (EmployeeModel) getIntent().getSerializableExtra("Available"); //this is where im using it
employeeDB = new EmployeeDBAssist(availability_screen_code.this);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.availableTimes, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//monday
mondaySpinner.setAdapter(adapter);
mondaySpinner.setOnItemSelectedListener(this);
String availableString = available.getMonday();
mondaySpinner.setSelection(getIndex(mondaySpinner, availableString));
Toast.makeText(this, availableString, Toast.LENGTH_SHORT).show();
//tuesday
tuesdaySpinner.setAdapter(adapter);
tuesdaySpinner.setOnItemSelectedListener(this);
//wednesday
wednesdaySpinner.setAdapter(adapter);
wednesdaySpinner.setOnItemSelectedListener(this);
//thursday
thursdaySpinner.setAdapter(adapter);
thursdaySpinner.setOnItemSelectedListener(this);
//friday
fridaySpinner.setAdapter(adapter);
fridaySpinner.setOnItemSelectedListener(this);
//saturday
saturdaySpinner.setAdapter(adapter);
saturdaySpinner.setOnItemSelectedListener(this);
//sunday
sundaySpinner.setAdapter(adapter);
sundaySpinner.setOnItemSelectedListener(this);
confirmation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AvailabilityModel availabilityModel;
try{
availabilityModel = new AvailabilityModel(-1, employee.getEID(), mondaySpinner.getSelectedItem().toString(), tuesdaySpinner.getSelectedItem().toString(), wednesdaySpinner.getSelectedItem().toString(), thursdaySpinner.getSelectedItem().toString(), fridaySpinner.getSelectedItem().toString(), saturdaySpinner.getSelectedItem().toString(), sundaySpinner.getSelectedItem().toString());
EmployeeDBAssist employeeDBAssist = new EmployeeDBAssist(availability_screen_code.this);
employeeDBAssist.updateAvailability(employee.getEID(),mondaySpinner.getSelectedItem().toString(), tuesdaySpinner.getSelectedItem().toString(), wednesdaySpinner.getSelectedItem().toString(), thursdaySpinner.getSelectedItem().toString(), fridaySpinner.getSelectedItem().toString(), saturdaySpinner.getSelectedItem().toString(), sundaySpinner.getSelectedItem().toString());
Toast.makeText(availability_screen_code.this, String.valueOf(employee.getEID()) + " " + mondaySpinner.getSelectedItem().toString()+ " " + tuesdaySpinner.getSelectedItem().toString()+ " " + wednesdaySpinner.getSelectedItem().toString()+ " " + thursdaySpinner.getSelectedItem().toString()+ " " + fridaySpinner.getSelectedItem().toString()+ " " + saturdaySpinner.getSelectedItem().toString()+ " " + sundaySpinner.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
boolean success = employeeDBAssist.addAvailability(availabilityModel);
}
catch (Exception e){
Toast.makeText(availability_screen_code.this, "Error Setting Availability", Toast.LENGTH_SHORT).show();
}
Intent i = new Intent(availability_screen_code.this,activity_main_code.class);
startActivity(i);
Toast.makeText(availability_screen_code.this, String.valueOf(employee.getEID()) + " " + mondaySpinner.getSelectedItem().toString()+ " " + tuesdaySpinner.getSelectedItem().toString()+ " " + wednesdaySpinner.getSelectedItem().toString()+ " " + thursdaySpinner.getSelectedItem().toString()+ " " + fridaySpinner.getSelectedItem().toString()+ " " + saturdaySpinner.getSelectedItem().toString()+ " " + sundaySpinner.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
}
});
}
availability table has 2 values and employees 7. In getItemCount I'm using the size of my employee table. However, I need to get the position of my availability so that I can use it in another class. It will only work for the first two entries. Once I scroll down it throws :
java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
Adding an availability for every employee would defeat the purpose of my project. How to solve this with the use of two separate arrays of different size?
You can check whether the corresponding AvailabilityModel exists before calling List#get(), if not, directly assign available to null. At the same time, you also need to perform a null check in intent.putExtra("Available", employee);.
Update I fixed the problem using a little bit of what #perfect puzzle said here's the solution
Here's the recyclerViewAdapter updated code
I first created an if statement to check whether the pointer was below the size of the availability list allAvailabilitys.size(), then created a null check within the intent.putExtra field as per #perfectpuzzle instruction
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
EmployeeModel employee;
AvailabilityModel available = null;
if(position < allAvailabilitys.size()){
available = allAvailabilitys.get(position);
employee = allEmployees.get(position);
holder.employeeID.setText(String.valueOf(allEmployees.get(position).getEID()));
holder.firstName.setText(allEmployees.get(position).getfName());
holder.lastName.setText(allEmployees.get(position).getlName());
holder.employee = employee;
} else{
employee = allEmployees.get(position);
holder.employeeID.setText(String.valueOf(allEmployees.get(position).getEID()));
holder.firstName.setText(allEmployees.get(position).getfName());
holder.lastName.setText(allEmployees.get(position).getlName());
holder.employee = employee;
}
EmployeeModel finalEmployee = employee;
holder.editButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, EditEmployee.class);
intent.putExtra("Editing", finalEmployee);
context.startActivity(intent);
}
});
EmployeeModel finalEmployee1 = employee;
AvailabilityModel finalAvailable = available;
holder.availabilityButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, availability_screen_code.class);
intent.putExtra("Available", finalEmployee1);
if(finalAvailable!= null){
intent.putExtra("Days", finalAvailable);
}
context.startActivity(intent);
}
});
EmployeeModel finalEmployee2 = employee;
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, ViewEmployee.class);
intent.putExtra("Viewing", finalEmployee2);
context.startActivity(intent);
}
});
}
}
Updated use of position
here I also check if available is null and I also created a function to translate a null into the default String used in my spinner.
Bundle bundle = getIntent().getExtras();
AvailabilityModel available = (AvailabilityModel) getIntent().getSerializableExtra("Days");
EmployeeModel employee = (EmployeeModel) getIntent().getSerializableExtra("Available");
employeeDB = new EmployeeDBAssist(availability_screen_code.this);
//setting elements in spinner
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.availableTimes, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//monday
mondaySpinner.setAdapter(adapter);
//tuesday
tuesdaySpinner.setAdapter(adapter);
//wednesday
wednesdaySpinner.setAdapter(adapter);
//thursday
thursdaySpinner.setAdapter(adapter);
//friday
fridaySpinner.setAdapter(adapter);
//saturday
saturdaySpinner.setAdapter(adapter);
//sunday
sundaySpinner.setAdapter(adapter);
if(available != null){
mondayChoice = getAvailableDay(available.getMonday());
mondaySpinner.setSelection(getIndex(mondaySpinner, mondayChoice));
tuesdayChoice = getAvailableDay(available.getTuesday());
tuesdaySpinner.setSelection(getIndex(tuesdaySpinner, tuesdayChoice));
wednesdayChoice = getAvailableDay(available.getWednesday());
wednesdaySpinner.setSelection(getIndex(wednesdaySpinner, wednesdayChoice));
thursdayChoice = getAvailableDay(available.getThursday());
thursdaySpinner.setSelection(getIndex(thursdaySpinner, thursdayChoice));
fridayChoice = getAvailableDay(available.getFriday());
fridaySpinner.setSelection(getIndex(fridaySpinner, fridayChoice));
saturdayChoice = getAvailableDay(available.getSaturday());
saturdaySpinner.setSelection(getIndex(saturdaySpinner, saturdayChoice));
sundayChoice = getAvailableDay(available.getSunday());
sundaySpinner.setSelection(getIndex(sundaySpinner, sundayChoice));
}
else{
Toast.makeText(this, "null field", Toast.LENGTH_SHORT).show();
}
}
Hope this can help someone out.
I am new to Firebase and I am trying to make an Android app where users can track workouts by creating activities and the activities are then stored in a database (Firebase). However, when I try to add each activity object to the database, only some of the fields are inserted. Please see relevant code below
Activity class
public class Activity {
private String workout, user, exercise, duration, weight, reps, date, activity_workout_user;
Activity(String workout, String user, String exercise, String duration, String weight, String reps, String date) {
this.workout = workout;
this.user = user;
this.exercise = exercise;
this.duration = duration;
this.weight = weight;
this.reps = reps;
this.date = date;
this.activity_workout_user = exercise + "_" + workout + "_" + user;
}
//getters and setters
}
AddActivity class
public class AddActivity extends AppCompatActivity {
FirebaseDatabase database;
DatabaseReference ref;
String user, workoutName, timeCreated;
Spinner AAexerciseSP;
EditText AArepsET, AAdurationET, AAweightET;
TextView AAworkoutNameTV, AAerrorsTV, AAinfoTV;
Button AAaddActivityBTN, AAsaveWorkoutBTN;
static ArrayList<Activity> activities;
int totalActivities = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
database = FirebaseDatabase.getInstance();
ref = database.getReference();
SQLquery = "";
activities = new ArrayList<>();
Intent intent = getIntent();
user = intent.getStringExtra("username");
workoutName = intent.getStringExtra("workout_name");
timeCreated = DateTime.TimeDate();
AAworkoutNameTV = findViewById(R.id.AAworkoutNameTV);
AAerrorsTV = findViewById(R.id.AAerrorsTV);
AAinfoTV = findViewById(R.id.AAinfoTV);
AAexerciseSP = findViewById(R.id.AAexerciseSP);
AAaddActivityBTN = findViewById(R.id.AAaddActivityBTN);
AAsaveWorkoutBTN = findViewById(R.id.AAsaveWorkoutBTN);
AArepsET = findViewById(R.id.AArepsET);
AAdurationET = findViewById(R.id.AAdurationET);
AAweightET = findViewById(R.id.AAweightET);
AAworkoutNameTV.setText(String.format("Workout name: %s", workoutName));
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.exercise_list, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
AAexerciseSP.setAdapter(adapter);
AAexerciseSP.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String item = (String) parent.getSelectedItem();
String[] array = getResources().getStringArray(R.array.cardio_exercises);
List<String> exercises = Arrays.asList(array);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public String selectedExercise(){
return (String) AAexerciseSP.getSelectedItem();
}
public void addActivity(View view){
String activityExercise = selectedExercise();
String activityUser = user;
String activityWorkout = workoutName;
String activityDuration = AAdurationET.getText().toString();
String activityReps = AArepsET.getText().toString();
String activityWeight = AAweightET.getText().toString();
String activityDate = DateTime.TimeDate();
Activity activity = new Activity(activityWorkout, activityUser, activityExercise,
activityDuration, activityWeight, activityReps, timeCreated);
activities.add(activity);
totalActivities += 1;
}
public void saveWorkout(View view){
for (Activity activity:activities){
String key = database.getReference("activities").push().getKey();
assert key != null;
ref.child("activities").child(key).setValue(activity);
}
Workout workout = new Workout(workoutName,user,timeCreated,"");
String key = database.getReference("workouts").push().getKey();
assert key != null;
ref.child("workouts").child(key).setValue(workout);
startActivity(new Intent(this, HomePage.class));
}
}
The insertion of each activity object into the database happens in the "saveWorkout" method, but instead of inserting all the fields from the class, only the "activity_workout_user" and "user" fields are inserted. Please see below for the snippet from the database.
Any help getting all the fields to be inserted would be greatly appreciated.
Thanks in advance,
Cheers
I would like to comment, but I am very new to stackoverflow, so I cant comment yet.
I just recently started to use Firebase myself and i didnt learn to use it 100% properly.
But I read, that when it comes to adding custom objects to the database, the objects should have an additional constructor without parameters and there should be getters and setters for every variable.
1. I have a ListView that contains images, persons names, persons birthdays. When the user click on an item a new activity will be launched to show the details of this item. In this activity i have created a Rating bar where the user are going to rate each item.
2. I have tried to use SharedPreferences to save the average calculated of rated items.I found that when i save the rates and launch the app again the values are not stored in SharedPreferences.
My main goal to achieve is to calculate the average of each rated items and save them in SharedPreferences.
3. Person Class:
public class PersonInfo {
private int image;
private String name;
private String birthday;
private float rating;
public PersonInfo(int image, String name, String birthday, float rating) {
this.image = image;
this.name = name;
this.birthday = birthday;
this.rating = rating;
}
public float getRating() {
return rating;
}
public void setRating(float rating) {
this.rating = rating;
}
public String getName(){
return name;
}
public int getImage() {
return image;
}
public void setName(String name) {
this.name = name;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
}
Person Adapter:
public class StudentsListAdapter extends ArrayAdapter<PersonInfo>{
private Context contxt;
private int rsrc;
private List<PersonInfo> persons;
private boolean isAdmin;
private TextView pName, pBirthday;
public StudentsListAdapter( Context context, int resource, List<PersonInfo> _persons, boolean _isAadmin) {
super(context, resource, _persons);
contxt = context;
rsrc = resource;
persons=_persons;
isAdmin = _isAadmin;
}
#NonNull
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(contxt);
View view = inflater.inflate(rsrc, null,false);
ImageView imageView = view.findViewById(R.id.imgP);
pName = view.findViewById(R.id.txtView2);
pBirthday = view.findViewById(R.id.txtView3);
PersonInfo p = persons.get(position);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent(contxt,ViewItems.class);
String name = persons.get(position).getName();
String birth = persons.get(position).getBirthday();
intent1.putExtra("name",name);
intent1.putExtra("birth",birth);
contxt.startActivity(intent1);
}
});
imageView.setImageDrawable(contxt.getResources().getDrawable(p.getImage()));
pBirthday.setText(p.getBirthday());
pName.setText(p.getName());
}
return view;
}
Rate Items:
public class ViewItems extends AppCompatActivity {
EditText edName;
TextView edBirth;
float myRating = 0;
Button svRate;
RatingBar rtBar;
String position;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_items);
edName = findViewById(R.id.st_editName);
edBirth = findViewById(R.id.tv_editDate);
rtBar = findViewById(R.id.ratingBar);
Bundle extras = getIntent().getExtras();
String name = extras.getString("name");
edName.setText(name);
edName.setEnabled(false);
edName.setTextColor(Color.BLACK);
String birth = extras.getString("birth");
edBirth.setText(birth);
edBirth.setEnabled(false);
edBirth.setTextColor(Color.BLACK);
ImageView image = (ImageView) findViewById(R.id.user_img);
image.setBackgroundResource(android.R.drawable.btn_star);
position = getIntent().getStringExtra("position");
rtBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
int rating1 = (int) rating;
String message = null;
myRating = ratingBar.getRating();
switch (rating1){
case 1:
message = "Sorry to hear that!";
break;
case 2:
message = "You always accept suggestions!";
break;
case 3:
message = "Good enough!";
break;
case 4:
message = "Great! Thank you!";
break;
case 5:
message = "Awesome! You are the best!";
break;
}
Toast.makeText(ViewItems.this, message, Toast.LENGTH_SHORT).show();
}
});
svRate = findViewById(R.id.sv_item);
svRate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i4 = new Intent(ViewItems.this, MainActivity.class);
SharedPreferences sharedPreferences = getSharedPreferences("SaveRating",Context.MODE_PRIVATE);
myRating = sharedPreferences.getFloat("rating_float", 0f);
float total = 0;
total += rtBar.getRating();
float average = total / 2;
rtBar.setRating(average);
startActivity(i4);
Toast.makeText(ViewItems.this, "Your rating is:" + (myRating), Toast.LENGTH_SHORT).show();
}
});
}
}
Main Activity:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private TextView edName,edBirth;
String position;
String ed_name;
String ed_birth;
String username, password;
ArrayList<PersonInfo> students;
ArrayList<PersonInfo> students1;
ListView listView1;
SharedPreferences sharedPref;
SharedPreferences.Editor editor;
float rtBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
students = new ArrayList<>();
students1 = new ArrayList<>();
Intent intent = getIntent();
if(getIntent() != null){
username = intent.getStringExtra("Username");
password = intent.getStringExtra("Password");
edName = findViewById(R.id.txtView2);
edBirth = findViewById(R.id.txtView3);
listView1 = (ListView) findViewById(R.id.li_view);
students1.add(new PersonInfo(android.R.drawable.btn_star, "Test1", "03/27/1998", 3));
students1.add(new PersonInfo(android.R.drawable.btn_star, "Test2", "03/27/1998",2));
students1.add(new PersonInfo(android.R.drawable.btn_star, "Test3", "03/27/1998",1));
students1.add(new PersonInfo(android.R.drawable.btn_star, "Test4", "03/27/1998",5));
test1 = new StudentsListAdapter(
this, R.layout.adapter_view_layout, students1, true);
listView1.setAdapter(test1);
if(username!= null && username.equals("test") && password != null && password.equals("123")){
Log.d(TAG, "onCreate: Started.");
ListView listView = (ListView) findViewById(R.id.li_view);
students.add(new PersonInfo(android.R.drawable.btn_star, "Test1", "03/27/1998", 3));
students.add(new PersonInfo(android.R.drawable.btn_star, "Test2", "03/27/1998",2));
students.add(new PersonInfo(android.R.drawable.btn_star, "Test3", "03/27/1998",1));
students.add(new PersonInfo(android.R.drawable.btn_star, "Test4", "03/27/1998",5));
test1 = new StudentsListAdapter(
this, R.layout.adapter_view_layout, students, true);
listView1.setAdapter(test1);
}
else if (username != null && username.equals("test2") && password != null && password.equals("1234"))
{
ListView listView = (ListView) findViewById(R.id.li_view);
students.add(new PersonInfo(android.R.drawable.btn_star, "Test1", "03/27/1998", 3));
students.add(new PersonInfo(android.R.drawable.btn_star, "Test2", "03/27/1998",2));
students.add(new PersonInfo(android.R.drawable.btn_star, "Test3", "03/27/1998",1));
students.add(new PersonInfo(android.R.drawable.btn_star, "Test4", "03/27/1998",5));
test1 = new StudentsListAdapter(
this, R.layout.adapter_view_layout, students,false);
listView1.setAdapter(test1);
}
SharedPreferences sharedPreferences = getSharedPreferences("SaveRating",Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putFloat("rating_float", rtBar);
editor.apply();
}
}
}
What am i doing wrong?
Any help will be greatly appreciated.
Thank you!
You dont even try to save anything. You just put rtBar
editor.putFloat("rating_float", rtBar);
that even not initialized but in case this is a primitive type of data float it have default value 0
I think you forgot to initialize rtBar, as #Eugene told you. You can initialize it by grabbing the average of all student:
for (PersonInfo personInfo : students) {
rtBar += personInfo.getRating();
}
// now store it in sharedPrefs
I am new to app development and so far my app is working as intended but only when I launch it on my device from Android Studio. For example, I have once instance variable that I give a value of 1 in the onCreate() method. When I launch the app from android studio on to my device, it works fine and the variable has a value of 1. However, when I launch it from my device without using android studio, the variable is given a value of 0. I have also found that I will get a bunch of NullPointerExceptions on variables that I know should have a value, and once again it works when launched from Android Studio, but not when launched from the device.
Here is MainActivity
public class MainActivity extends AppCompatActivity
{
private ArrayList<String> arrayList;
private ArrayList<ListItem> itemList;
private ArrayAdapter<String> adapter;
private EditText txtInput;
private int payRoll;
private String value;
private Intent mainToPayroll;
private int hours;
private int earnings;
private ArrayList<Integer> rollList;
private ArrayList<Integer> hourList;
private ArrayList<Integer> wageList;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rollList = new ArrayList<>(0);
hourList = new ArrayList<>(0);
wageList = new ArrayList<>(0);
payRoll = 1;
Bundle bun = getIntent().getExtras();
if(bun != null)
{
rollList = bun.getIntegerArrayList("rolls");
hourList = bun.getIntegerArrayList("hours");
wageList = bun.getIntegerArrayList("wages");
payRoll = bun.getInt("roll");
}
ListView listView = (ListView) findViewById(R.id.listv);
String[] items = {};
arrayList = new ArrayList<>(Arrays.asList(items));
itemList = new ArrayList<>(0);
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.txtitem, arrayList);
listView.setAdapter(adapter);
Button btAdd = (Button) findViewById(R.id.btadd);
mainToPayroll = new Intent(this, PayrollActivity.class);
if(rollList != null)
{
for (int i = 0; i < rollList.size(); i++) {
ListItem newItem = new ListItem(rollList.get(i), hourList.get(i), wageList.get(i));
arrayList.add(newItem.toString());
itemList.add(newItem);
adapter.notifyDataSetChanged();
}
rollList.clear();
hourList.clear();
wageList.clear();
}
btAdd.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
ListItem newItem = new ListItem(payRoll, 0, 0);
arrayList.add(newItem.toString());
itemList.add(newItem);
adapter.notifyDataSetChanged();
payRoll++;
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
value = (String)adapter.getItem(position);
ListItem item = itemList.get(position);
Bundle info = new Bundle();
info.putString("val", value);
info.putInt("hours", item.getHours());
info.putInt("wage", item.getWages());
info.putInt("pos", position);
if(itemList.size() > 0)
{
for (ListItem items : itemList)
{
rollList.add(items.getPayroll());
hourList.add(items.getHours());
wageList.add(items.getWages());
}
}
info.putIntegerArrayList("rolls", rollList);
info.putIntegerArrayList("hours", hourList);
info.putIntegerArrayList("wages", wageList);
info.putInt("roll", payRoll);
info.putBoolean("rest", restore);
mainToPayroll.putExtras(info);
startActivity(mainToPayroll);
}
});
}
This Activity is started whenever an item on the listview is clicked
public class PayrollActivity extends AppCompatActivity
{
private static TextView text;
private String payrollNumber;
private int payrollHrs;
private int payrollWages;
private int position;
private Intent payrollToMain;
private Button returnButton;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payroll);
final Bundle info = getIntent().getExtras();
System.out.print(getIntent().getType());
payrollNumber = info.getString("val");
payrollHrs = info.getInt("hours");
payrollWages = info.getInt("wage");
position = info.getInt("pos");
payrollToMain = new Intent(this, MainActivity.class);
returnButton = (Button) findViewById(R.id.btnRtrn);
returnButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Bundle thing = new Bundle();
thing.putIntegerArrayList("rolls", info.getIntegerArrayList("rolls"));
thing.putIntegerArrayList("hours", info.getIntegerArrayList("hours"));
thing.putIntegerArrayList("wages", info.getIntegerArrayList("wages"));
thing.putInt("roll", info.getInt("roll"));
thing.putBoolean("rest", info.getBoolean("rest"));
payrollToMain.putExtras(thing);
startActivity(payrollToMain);
}
});
text = (TextView) findViewById(R.id.title);
text.setText(payrollNumber);
}
public static void setLabelText(String val)
{
text.setText(val);
}
This is a class I created for the items that go on the listview
public class ListItem
{
private int payroll;
private int hrs;
private int wages;
public ListItem(int roll, int hours, int wag)
{
payroll = roll;
hrs = hours;
wages = wag;
}
public int getPayroll()
{
return payroll;
}
public int getHours()
{
return hrs;
}
public int getWages()
{
return wages;
}
public void setPayroll(int roll)
{
payroll = roll;
}
public void setHrs(int hours)
{
hrs = hours;
}
public void setWages(int wage)
{
wages = wage;
}
public String toString()
{
return "Payroll " + payroll + "\n" + hrs + " hours\n$" + wages;
}
I think your problem is this piece of code in your MainActivity:
Bundle bun = getIntent().getExtras();
if(bun != null)
{
rollList = bun.getIntegerArrayList("rolls");
hourList = bun.getIntegerArrayList("hours");
wageList = bun.getIntegerArrayList("wages");
payRoll = bun.getInt("roll");
}
The getIntent().getExtras() may return a non-null Bundle object but the bundle may not have the keys you are trying to access, in which case all your instance variables will be set to null or zero for int.
You can get around this by simply checking if a particular key exists in the bundle and only setting your variable if it does.
bun.containsKey()
Or you can initialize your variables if they are null after loading them from the bundle.
Try uninstalling the app completely from the device and then try again. This solves the issue at times.
Hi just to state i am a beginner android developer and my code may be a bit messy i also appreciate any help anyone can give me, i have implemented parcelable using this tutorial http://www.javacodegeeks.com/2014/01/android-tutorial-two-methods-of-passing-object-by-intent-serializableparcelable.html
i have Two activities activity A and activity B, the first displays a list of custom objects (properties) and the Property class implements parcelable
Activity A has a custom list and I want to add objects dynamically. In this activity I have a button that opens activity B where i input the information required to created a property object which i want to send back to activity A to be added to the list.
Before I implemented parcelable i was able to create the object with no issue but it was stuck in activity B and needs to be added to the list in activity A after implementing parcelable when i first try to open activity A i get an error that crashes my app i think it's because i've added Property mProperty = getIntent().getParcelableExtra(AddProperty.PAR_KEY); in the onCreate method in activity A which looks for an intent before ones been created in Activity B
public class Property implements Parcelable {
// have quit alot of fields so took them out to save space
public Property()
{
}
public Property(String postCode, String address, String county,int noRoom, int askPrice,
String eName,String agentName,String agentNumber, String time) {
this.postCode = postCode;
this.addressFirsLine = address;
this.county = county;
setNumberOfRoom(noRoom);
//numberOfRoom = 2;
setAskingPrice(askPrice);
//askingPrice = 0;
//setCurrentOffer(currentOff);
currentOffer = 0;
//setAgreedPrice(agreedPrice);
agreedPrice = 0;
// setRefurbCost(refurb);
//refurbCost = 2555;
setEstateAgent(eName,agentNumber ,agentName);
// estateAgent = null;
condition = false;
setTime(time);
}
public static final Creator<Property> CREATOR = new Creator<Property>() {
#Override
public Property createFromParcel(Parcel source) {
Property mProperty = new Property();
mProperty.postCode = source.readString() ;
mProperty.addressFirsLine = source.readString();
mProperty.county =source.readString() ;
mProperty.numberOfRoom = source.readInt();
mProperty.askingPrice = source.readInt();
mProperty.agentName = source.readString();
mProperty.agentNumber = source.readString();
mProperty.eName = source.readString();
return mProperty;
}
#Override
public Property[] newArray(int size) {
return new Property[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(postCode);
dest.writeString(addressFirsLine);
dest.writeString(county);
dest.writeInt(numberOfRoom);
dest.writeInt(askingPrice);
dest.writeString(agentName);
dest.writeString(agentNumber);
dest.writeString(eName);
dest.writeString(time);
}
}
the propery class also has full getters and setters.
the createViewing method is on activity B and is whats used to create the object and send the object back
public void CreateViewing(View view) {
String strPostCode,strAddressFirsLine,strCounty,strEstateAgent,strAgentName,strAgentPhone,strTime ;
int roomNO ;
int askingPrice2 ;
try{
strPostCode = postCode.getText().toString();
strAddressFirsLine=addressFirsLine.getText().toString();
strCounty = county.getText().toString();
roomNO = Integer.parseInt(roomNumber.getText().toString());
askingPrice2 = Integer.parseInt(askingPrice.getText().toString());
strEstateAgent=estateAgent.getText().toString();
strAgentName=agentName.getText().toString() ;
strAgentPhone=agentPhone.getText().toString() ;
strTime =time.getText().toString() ;
Property mProperty = new Property(strPostCode, strAddressFirsLine,
strCounty ,roomNO,askingPrice2,strEstateAgent ,strAgentName,strAgentPhone,
strTime ) ;
String r = mProperty.toString() ;
Intent mIntent = new Intent(this,ViewingSchedule.class);
Bundle mBundle = new Bundle();
mBundle.putParcelable(PAR_KEY,mProperty);
mIntent.putExtras(mBundle);
startActivity(mIntent);
Toast.makeText(AddProperty.this, r, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
this is the onCreate Method for activity A
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_viewing_schedule);
Toolbar toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Property mProperty = getIntent().getParcelableExtra(AddProperty.PAR_KEY);
Toast.makeText(ViewingSchedule.this,mProperty.toString(),Toast.LENGTH_SHORT).show();
Property[] propertyList = {new Property("SG1 1LS", "24 CrossGates", "Hertfordshire",2, 200000,"Connels","becky","078123456","9:00")};
//propertyList = mProperty ;
ListView listView1 = (ListView) findViewById(R.id.listView);
ArrayAdapter adapter = new myAdapter2(this,propertyList);
listView1.setAdapter(adapter);
listView1.setOnItemClickListener((new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String itemSelected = "You selected " +
String.valueOf(parent.getItemAtPosition(position));
Toast.makeText(ViewingSchedule.this, itemSelected, Toast.LENGTH_SHORT).show();
}
}));