Arraylist keeps overwriting the last entry i added - java

sorry for troubling you, i am new at android, and i need a little help. I am doing a simple ampplication in which you sign up some people to a club. What it keeps happening is that the last person i add to the arraylist overwries the old one. I really donĀ“t know what it could be. If you can help i would be grateful.
AltaSocio.java
package com.example.polideportivo1;
import java.text.DateFormat;
import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
public class AltaSocio extends Activity {
Socios nuevosSocio = new Socios(0,"","","","","","","","",0,0,"");
VariablesGlobales vb = new VariablesGlobales();
private EditText editDocumento;
private EditText editApellido;
private EditText editNombre;
private CheckBox checkBoxM;
private CheckBox checkBoxF;
private EditText editCivil;
private Spinner Nacionalidad;
private EditText Nacimiento;
private EditText Domicilio;
private Spinner Localidad;
private EditText Celular;
private EditText TelFijo;
private EditText Correo;
String miNacionalidad;
String miLocalidad;
ArrayList<Socios> socios = vb.getSocios();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alta_socio2);
editDocumento = (EditText)findViewById(R.id.editDocumento);
editApellido = (EditText)findViewById(R.id.editApellido);
editNombre = (EditText)findViewById(R.id.editNombre);
editCivil = (EditText)findViewById(R.id.editCivil);
Nacimiento = (EditText)findViewById(R.id.editNacimiento);
Domicilio = (EditText)findViewById(R.id.editDomicilio);
Celular = (EditText)findViewById(R.id.editCelular);
TelFijo = (EditText)findViewById(R.id.editFijo);
Correo = (EditText)findViewById(R.id.editCorreo);
checkBoxM = (CheckBox)findViewById(R.id.checkM);
checkBoxF = (CheckBox)findViewById(R.id.checkF);
Nacionalidad = (Spinner)findViewById(R.id.spinnerNacionalidad);
Localidad = (Spinner)findViewById(R.id.spinnerLocalidad);
final Button BtnCrear = (Button)findViewById(R.id.botonCrear);
final Button BtnCerrar = (Button)findViewById(R.id.buttonAtras);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.Nacionalidad, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
Nacionalidad.setAdapter(adapter);
Nacionalidad.setOnItemSelectedListener(new OnItemSelectedListener () {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
parent.getItemAtPosition(pos);
miNacionalidad = Nacionalidad.getItemAtPosition(pos).toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
//another call
}
});
ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(this, R.array.Localidad, android.R.layout.simple_spinner_item);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_item);
Localidad.setAdapter(adapter2);
Localidad.setOnItemSelectedListener(new OnItemSelectedListener () {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
parent.getItemAtPosition(pos);
miLocalidad = Localidad.getItemAtPosition(pos).toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
//another call
}
});
}
public void grabar(View v) {
nuevosSocio.setCI(Integer.parseInt(editDocumento.getText().toString()));
nuevosSocio.setApellido(editApellido.getText().toString());
nuevosSocio.setNombre(editNombre.getText().toString());
nuevosSocio.setEstadoCivil(editCivil.getText().toString());
DateFormat formateador = new SimpleDateFormat("dd/MM/yyyy");
DateFormat DataSocio;
try {
String Fecha =(Nacimiento.getText().toString());
formateador.parse(Fecha);
nuevosSocio.setFechaNacimiento(Fecha);
}
catch (ParseException e)
{
Toast g = Toast.makeText(this, "Formato Fecha no valido", Toast.LENGTH_LONG);
}
//nuevosSocio.setFechaNacimiento(Fecha);
nuevosSocio.setDomicilio(Domicilio.getText().toString());
nuevosSocio.setTelefonoCelular(Integer.parseInt(Celular.getText().toString()));
nuevosSocio.setTelefonoFijo(Integer.parseInt(TelFijo.getText().toString()));
nuevosSocio.setCorreo(Correo.getText().toString());
if (checkBoxM.isChecked()) {
nuevosSocio.setSexo("Masculino");
} else {
nuevosSocio.setSexo("Femenino");
}
nuevosSocio.setNacionalidad(miNacionalidad);
nuevosSocio.setLocalidad(miLocalidad);
socios.add(nuevosSocio);
nuevosSocio = new Socios(0,"","","","","","","","",0,0,"");
Toast t = Toast.makeText(this, "Los datos fueron grabados",
Toast.LENGTH_SHORT);
t.show();
finish();
}
}
Socio.java
package com.example.polideportivo1;
import java.sql.Date;
import android.graphics.Bitmap;
import android.widget.CheckBox;
import android.widget.ImageView;
public class Socios {
private int CI;
private String Nombre;
private String Apellido;
private String Sexo;
private String EstadoCivil;
private String Nacionalidad;
private String FechaNacimiento;
private String Domicilio;
private String Localidad;
private int TelefonoCelular;
private int TelefonoFijo;
private String DireccionCorreo;
public Socios(int CI, String Nombre, String Apellido, String Sexo, String EstadoCivil,
String Nacionalidad, String FechaNacimiento, String Domicilio, String Localidad, int TelefonoCelular, int TelefonoFijo, String DireccionCorreo) {
this.CI = CI;
this.Nombre = Nombre;
this.Apellido = Apellido;
this.Sexo = Sexo;
this.EstadoCivil = EstadoCivil;
this.Nacionalidad = Nacionalidad;
this.FechaNacimiento = FechaNacimiento;
this.Domicilio = Domicilio;
this.Localidad = Localidad;
this.TelefonoCelular = TelefonoCelular;
this.TelefonoFijo = TelefonoFijo;
this.DireccionCorreo = DireccionCorreo;
}
public int obtenerCI() {
return CI;
}
public String obtenerNombre() {
return Nombre;
}
public String obtenerApellido() {
return Apellido;
}
public String obtenerSexo() {
return Sexo;
}
public void setSexo() {
this.Sexo = Sexo;
}
public String obtenerNacionalidad() {
return Nacionalidad;
}
public String obtenerEstadoCivil() {
return EstadoCivil;
}
public String obtenerFechaNacimiento() {
return FechaNacimiento;
}
public String obtenerDomicilio() {
return Domicilio;
}
public String obtenerLocalidad() {
return Localidad;
}
public int obtenerCelular() {
return TelefonoCelular;
}
public int obtenerTelefonoFijo() {
return TelefonoFijo;
}
public String obtenerCorreo() {
return DireccionCorreo;
}
public void setCI(int parseInt) {
this.CI = parseInt;
}
public void setApellido(String string) {
this.Apellido = string;
}
public void setNombre(String string) {
this.Nombre = string;
}
public void setEstadoCivil(String string) {
this.EstadoCivil = string;
}
public void setDomicilio(String string) {
this.Domicilio = string;
}
public void setTelefonoCelular(int parseInt) {
this.TelefonoCelular = parseInt;
}
public void setTelefonoFijo(int parseInt) {
this.TelefonoFijo = parseInt;
}
public void setCorreo(String string) {
this.DireccionCorreo = string;
}
public void setSexo(String string) {
this.Sexo = string;
}
public void setNacionalidad(String miNacionalidad) {
this.Nacionalidad = miNacionalidad;
}
public void setLocalidad(String miLocalidad) {
this.Localidad = miLocalidad;
}
public void setFechaNacimiento(String string) {
this.FechaNacimiento = string;
}
}

Every time you called the grabar to add the user you have to create a new Socio object. Using the same references will only change object's content

Related

trouble passing object between Activities using intent parcelable extra

In my case, there is a listVIew in the first activity and by clicking on a listItem it redirects to another activity which allows to edit to edit details of the particular object item. once the selected item is edited in the second activity I want it to be updated in the first activity as well. I have used parcelable extra to pass data between two activities.
The first activity passes data to the second activity correctly but when it comes to updating the listView in the first activity using updated data in the second activity it throws a NullPointerException saying that the received object is null.
Please help me figure this out. thanks in advance.
Parcelable object class
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import androidx.annotation.RequiresApi;
import java.io.Serializable;
public class Movie implements Parcelable {
private String title;
private int releasedYear;
private String director;
private String cast;
private int rating;
private String review;
private boolean favourite;
public Movie(String title, int releasedYear, String director, String cast, int rating, String review) {
this.title = title;
this.releasedYear = releasedYear;
this.director = director;
this.cast = cast;
this.rating = rating;
this.review = review;
}
public Movie(String title, int releasedYear, String director, String cast, int rating, String review, boolean favourite) {
this.title = title;
this.releasedYear = releasedYear;
this.director = director;
this.cast = cast;
this.rating = rating;
this.review = review;
this.favourite = favourite;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getReleasedYear() {
return releasedYear;
}
public void setReleasedYear(int releasedYear) {
this.releasedYear = releasedYear;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public String getCast() {
return cast;
}
public void setCast(String cast) {
this.cast = cast;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
public String getReview() {
return review;
}
public void setReview(String review) {
this.review = review;
}
public boolean isFavourite() {
return favourite;
}
public void setFavourite(boolean favourite) {
this.favourite = favourite;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.title);
dest.writeInt(this.releasedYear);
dest.writeString(this.director);
dest.writeString(this.cast);
dest.writeInt(this.rating);
dest.writeString(this.review);
dest.writeByte(this.favourite ? (byte) 1 : (byte) 0);
}
public void readFromParcel(Parcel source) {
this.title = source.readString();
this.releasedYear = source.readInt();
this.director = source.readString();
this.cast = source.readString();
this.rating = source.readInt();
this.review = source.readString();
this.favourite = source.readByte() != 0;
}
protected Movie(Parcel in) {
this.title = in.readString();
this.releasedYear = in.readInt();
this.director = in.readString();
this.cast = in.readString();
this.rating = in.readInt();
this.review = in.readString();
this.favourite = in.readByte() != 0;
}
public static final Creator<Movie> CREATOR = new Creator<Movie>() {
#Override
public Movie createFromParcel(Parcel source) {
return new Movie(source);
}
#Override
public Movie[] newArray(int size) {
return new Movie[size];
}
};
}
First activity
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import com.example.movietracker.database.CoreDatabase;
import java.util.ArrayList;
import java.util.List;
import static com.example.movietracker.database.Constants.TABLE_NAME;
import static com.example.movietracker.database.Constants.TITLE;
public class EditMovie extends AppCompatActivity {
private final int REQ_COE = 1;
CoreDatabase database;
List<Movie> movies;
Movie movieReturn;
RelativeLayout layout;
ListView listView;
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQ_COE) {
if (resultCode == RESULT_OK) {
movieReturn = getIntent().getParcelableExtra("movieReturn");
movies.add(movieReturn);
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_movie);
layout = findViewById(R.id.edit_relative_layout);
listView = findViewById(R.id.edit_listView);
movies = new ArrayList<>();
database = new CoreDatabase(this);
String query = "select * from "+ TABLE_NAME + " order by "+ TITLE + " ASC";
Cursor cursor = database.getData(query);
retrieveData(cursor);
System.out.println(movies.size());
MovieArrayAdapter adapter = new MovieArrayAdapter(this, movies);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(EditMovie.this, EditMovieItemView.class);
intent.putExtra("movie", movies.get(position));
startActivityForResult(intent, 1);
movies.remove(position);
adapter.notifyDataSetChanged();
System.out.println(movies.size());
}
});
}
public void retrieveData(Cursor cursor){
while (cursor.moveToNext()) {
String title = cursor.getString(1);
int year = cursor.getInt(2);
String director = cursor.getString(3);
String cast = cursor.getString(4);
int rating = cursor.getInt(5);
String review = cursor.getString(6);
boolean favourite = cursor.getInt(7) > 0;
movies.add(new Movie(title, year, director, cast, rating, review, favourite));
}
}
}
Second Activity
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputFilter;
import android.view.View;
import android.widget.CheckBox;
import android.widget.NumberPicker;
import android.widget.RatingBar;
import android.widget.Toast;
import com.example.movietracker.database.CoreDatabase;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import java.util.List;
public class EditMovieItemView extends AppCompatActivity {
CoreDatabase database;
Movie movie;
String pickedDate, defaultTitle;
String updatedTitle, updatedDirector, updatedCast, updatedReview;
int updatedYear, updatedRating;
CheckBox favourite;
TextInputLayout title, year, director, cast, review;
NumberPicker yearPicker;
RatingBar rating1, rating2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_movie_item_view);
database = new CoreDatabase(this);
favourite = findViewById(R.id.edit_fav_checkbox);
title = findViewById(R.id.edit_movie_title);
year = findViewById(R.id.edit_movie_year);
year.getEditText().setFilters(new InputFilter[]{new MinMaxFilter(1895, 2021)});
director = findViewById(R.id.edit_movie_director);
cast = findViewById(R.id.edit_movie_cast);
rating1 = findViewById(R.id.edit_ratingBar1);
rating2 = findViewById(R.id.edit_ratingBar2);
review = findViewById(R.id.edit_movie_review);
yearPicker = findViewById(R.id.edit_year_picker);
yearPicker.setMinValue(1895);
yearPicker.setMaxValue(2021);
yearPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
pickedDate = String.valueOf(picker.getValue());
year.getEditText().setText(pickedDate);
}
});
if (getIntent().getExtras() != null){
movie = getIntent().getParcelableExtra("movie");
}
title.getEditText().setText(movie.getTitle());
year.getEditText().setText(String.valueOf(movie.getReleasedYear()));
director.getEditText().setText(movie.getDirector());
cast.getEditText().setText(movie.getCast());
review.getEditText().setText(movie.getReview());
if (movie.getRating() <= 5){
rating1.setRating(movie.getRating());
rating2.setRating(0);
} else {
rating1.setRating(5);
rating2.setRating(movie.getRating() - 5);
}
favourite.setChecked(movie.isFavourite());
defaultTitle = title.getEditText().getText().toString();
}
public void updateMovie(View view){
updatedTitle = title.getEditText().getText().toString();
updatedYear = Integer.parseInt(year.getEditText().getText().toString());
updatedDirector = director.getEditText().getText().toString();
updatedCast = cast.getEditText().getText().toString();
updatedReview = review.getEditText().getText().toString();
updatedRating = (int) (rating1.getRating() + rating2.getRating());
database.updateAllData(updatedTitle, updatedYear, updatedDirector, updatedCast, updatedRating, updatedReview, favourite.isChecked(), defaultTitle);
Toast.makeText(getApplicationContext(), "Successfully updated!", Toast.LENGTH_SHORT).show();
movie.setTitle(updatedTitle);
movie.setReleasedYear(updatedYear);
movie.setDirector(updatedDirector);
movie.setCast(updatedCast);
movie.setRating(updatedRating);
movie.setReview(updatedReview);
movie.setFavourite(favourite.isChecked());
Intent returnIntent = new Intent();
returnIntent.putExtra("movieReturn", movie);
setResult(RESULT_OK, returnIntent);
finish();
}
}

How can I get the ID from a newly inserted row?

saveCourse() is supposed to kick off verifyMentor() to create and/or verify that the currently input information for a mentor is availble to be added to the CourseEntity constructor. mMentorViewModel.saveMentor(mMentor) is supposed to kick off saving the new mentor via the scheudler repository, and the scheudler repository used the MentorDAO from the database to insert the new mentor.
I read this method Android Room - Get the id of new inserted row with auto-generate, but I'm missing some fundamental knowledge of how to get the newly created mentor information.
package com.example.wguscheduler.activities;
import android.app.DatePickerDialog;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import com.example.wguscheduler.R;
import com.example.wguscheduler.entities.CourseEntity;
import com.example.wguscheduler.entities.MentorEntity;
import com.example.wguscheduler.entities.TermEntity;
import com.example.wguscheduler.viewmodel.CourseViewModel;
import com.example.wguscheduler.viewmodel.MentorViewModel;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
public class CourseAddActivity extends AppCompatActivity {
private static final String TAG = "CourseAddActivity";
private CourseViewModel mCourseViewModel;
private MentorViewModel mMentorViewModel;
private EditText mCourseTitle, mCourseStartDate, mCourseEndDate,mCourseNotes,
mMentorFirstName, mMentorLastName, mMentorEmail, mMentorPhone;
private MentorEntity mMentor;
private Calendar mEndCalendar = Calendar.getInstance();
private Calendar mStartCalendar = Calendar.getInstance();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_courses_add);
//initialize the tool bar
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
//initialize the view model
mCourseViewModel = new ViewModelProvider(this).get(CourseViewModel.class);
mMentorViewModel = new ViewModelProvider(this).get(MentorViewModel.class);
//initialize EditText views
mCourseTitle = findViewById(R.id.edit_course_add_title);
mCourseStartDate = findViewById(R.id.edit_course_add_start);
mCourseEndDate = findViewById(R.id.edit_course_add_end);
mCourseNotes = findViewById(R.id.edit_course_add_notes);
mMentorFirstName = findViewById(R.id.edit_mentor_add_first);
mMentorLastName = findViewById(R.id.edit_mentor_add_last);
mMentorEmail = findViewById(R.id.edit_mentor_add_email);
mMentorPhone = findViewById(R.id.edit_mentor_add_phone);
try {
loadStartDatePicker();
loadEndDatePicker();
} catch (ParseException e) {
e.printStackTrace();
}
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
saveCourse();
} catch (ParseException e) {
e.printStackTrace();
}
}
});
}
private void loadStartDatePicker() throws ParseException {
DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mStartCalendar.set(Calendar.YEAR, year);
mStartCalendar.set(Calendar.MONTH, monthOfYear);
mStartCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateStartLabel();
}
};
mCourseStartDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new DatePickerDialog(CourseAddActivity.this,date, mStartCalendar.get(Calendar.YEAR), mStartCalendar.get(Calendar.MONTH),
mStartCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
}
private void updateStartLabel() {
String myFormat = "MM/dd/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
mCourseStartDate.setText(sdf.format(mStartCalendar.getTime()));
}
private void loadEndDatePicker() throws ParseException {
DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mEndCalendar.set(Calendar.YEAR, year);
mEndCalendar.set(Calendar.MONTH, monthOfYear);
mEndCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateEndLabel();
}
};
mCourseEndDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new DatePickerDialog(CourseAddActivity.this,date, mEndCalendar.get(Calendar.YEAR), mEndCalendar.get(Calendar.MONTH),
mEndCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
}
private void updateEndLabel() {
String myFormat = "MM/dd/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
mCourseEndDate.setText(sdf.format(mEndCalendar.getTime()));
}
private void saveCourse() throws ParseException{
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
verifyMentor();
int termId = getIntent().getIntExtra("termId", 0);
//int mentorId = mMentor.getId();
String title = mCourseTitle.getText().toString();
String status = "Plan to Take";
Date start = formatter.parse(mCourseStartDate.getText().toString());
Date end = formatter.parse(mCourseEndDate.getText().toString());
String notes = mCourseNotes.getText().toString();
CourseEntity course = new CourseEntity(termId, mMentor.getId(), title, status, start, end, notes);
Log.d(TAG, "saveCourse: " + course.getCourse());
mCourseViewModel.saveCourse(course);
onSupportNavigateUp();
}
private void verifyMentor() {
String first = mMentorFirstName.getText().toString();
String last = mMentorLastName.getText().toString();
String phone = mMentorPhone.getText().toString();
String email = mMentorEmail.getText().toString();
mMentor = new MentorEntity(first, last, phone, email);
mMentorViewModel.saveMentor(mMentor);
}
// add support for going back a screen
#Override
public boolean onSupportNavigateUp(){
onBackPressed();
return true;
}
}
package com.example.wguscheduler.entities;
import androidx.annotation.NonNull;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.Ignore;
import androidx.room.PrimaryKey;
#Entity (tableName = "mentor_table")
public class MentorEntity {
#PrimaryKey(autoGenerate = true)
#NonNull
#ColumnInfo(name = "id")
private long mId;
#ColumnInfo(name = "first_name")
private String mFirstName;
#ColumnInfo(name = "last_name")
private String mLastName;
#ColumnInfo(name = "phone")
private String mPhone;
#ColumnInfo(name = "email")
private String mEmail;
public MentorEntity(long mId, String mFirstName, String mLastName, String mPhone, String mEmail) {
this.mId = mId;
this.mFirstName = mFirstName;
this.mLastName = mLastName;
this.mPhone = mPhone;
this.mEmail = mEmail;
}
#Ignore
public MentorEntity(String mFirstName, String mLastName, String mPhone, String mEmail) {
this.mId = this.mId;
this.mFirstName = mFirstName;
this.mLastName = mLastName;
this.mPhone = mPhone;
this.mEmail = mEmail;
}
public long getId() {
return mId;
}
public void setId(long mId) {
this.mId = mId;
}
public String getFirstName() {
return mFirstName;
}
public void setFirstName(String mFirstName) {
this.mFirstName = mFirstName;
}
public String getLastName() {
return mLastName;
}
public void setLastName(String mLastName) {
this.mLastName = mLastName;
}
public String getPhone() {
return mPhone;
}
public void setPhone(String mPhone) {
this.mPhone = mPhone;
}
public String getEmail() {
return mEmail;
}
public void setEmail(String mEmail) {
this.mEmail = mEmail;
}
public String getMentor() {
String mentor = String.format("\n" +
"\nMentorId: %s\n\r" +
"FirstName: %s\n\r" +
"LastName Id: %s\n\r" +
"Phone: %s\n\r" +
"Email: %s\n\r",
mId, mFirstName, mLastName, mPhone, mEmail);
return mentor;
}
}
package com.example.wguscheduler.dao;
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import androidx.room.Update;
import com.example.wguscheduler.entities.MentorEntity;
import java.util.List;
#Dao
public interface MentorDAO {
//CREATE
#Insert(onConflict = OnConflictStrategy.REPLACE)
void insertAll(List<MentorEntity> mentors);
#Insert(onConflict = OnConflictStrategy.REPLACE)
void insert(MentorEntity mentor);
//READ
#Query("SELECT * FROM mentor_table")
LiveData<List<MentorEntity>> getMentors();
#Query("SELECT * FROM mentor_table WHERE id MATCH :mentorId")
MentorEntity getMentor(long mentorId);
//UPDATE
#Update
void update(MentorEntity mentor);
//DELETE
#Delete
void delete(MentorEntity mentor);
}
package com.example.wguscheduler.viewmodel;
import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import com.example.wguscheduler.database.SchedulerRepository;
import com.example.wguscheduler.entities.MentorEntity;
import java.util.ArrayList;
import java.util.List;
public class MentorViewModel extends AndroidViewModel {
private SchedulerRepository mSchedulerRepository;
private LiveData<List<MentorEntity>> mAllMentors;
public MentorViewModel(#NonNull Application application) {
super(application);
mSchedulerRepository = SchedulerRepository.getInstance(application.getApplicationContext());
mAllMentors = mSchedulerRepository.getAllMentors();
}
public LiveData<List<MentorEntity>> getAllMentors(){
return mAllMentors;
}
public void addSampleData(){
mSchedulerRepository.addSampleData();
}
public void saveMentor(MentorEntity mMentor) {
mSchedulerRepository.saveMentor(mMentor);
}
}
package com.example.wguscheduler.database;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.room.TypeConverters;
import androidx.sqlite.db.SupportSQLiteDatabase;
import com.example.wguscheduler.dao.AssessmentDAO;
import com.example.wguscheduler.dao.CourseDAO;
import com.example.wguscheduler.dao.MentorDAO;
import com.example.wguscheduler.dao.TermDAO;
import com.example.wguscheduler.entities.AssessmentEntity;
import com.example.wguscheduler.entities.CourseEntity;
import com.example.wguscheduler.entities.MentorEntity;
import com.example.wguscheduler.entities.TermEntity;
import com.example.wguscheduler.utilities.Converters;
#Database(entities = {TermEntity.class,
AssessmentEntity.class,
CourseEntity.class,
MentorEntity.class},
version = 13)
#TypeConverters({Converters.class})
public abstract class SchedulerDatabase extends RoomDatabase {
public abstract CourseDAO courseDAO();
public abstract MentorDAO mentorDAO();
public abstract TermDAO termDAO();
public abstract AssessmentDAO assessmentDAO();
private static volatile SchedulerDatabase INSTANCE;
static SchedulerDatabase getDatabase(final Context context) {
if (INSTANCE == null) {
synchronized (SchedulerDatabase.class) {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
SchedulerDatabase.class,
"scheduler_database")
.fallbackToDestructiveMigration()
.addCallback(sRoomDatabaseCallback)
.build();
}
}
}
return INSTANCE;
}
//open the database
private static RoomDatabase.Callback sRoomDatabaseCallback = new RoomDatabase.Callback() {
#Override
public void onOpen(#NonNull SupportSQLiteDatabase db) {
super.onOpen(db);
//new PopulateSchedulerDatabase(INSTANCE).execute();
}
};
}
package com.example.wguscheduler.database;
import android.content.Context;
import android.util.Log;
import androidx.lifecycle.LiveData;
import com.example.wguscheduler.entities.AssessmentEntity;
import com.example.wguscheduler.entities.CourseEntity;
import com.example.wguscheduler.entities.MentorEntity;
import com.example.wguscheduler.entities.TermEntity;
import com.example.wguscheduler.utilities.CourseSampleData;
import com.example.wguscheduler.utilities.MentorSampleData;
import com.example.wguscheduler.utilities.TermSampleData;
import com.example.wguscheduler.utilities.AssessmentSampleData;
import java.text.ParseException;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class SchedulerRepository {
private static final String TAG = "SchedulerRepository";
private static SchedulerRepository mSchedulerRepository;
//data lists
private LiveData<List<TermEntity>> mAllTerms;
private LiveData<List<CourseEntity>> mAllCourses;
private LiveData<List<AssessmentEntity>> mAllAssessments;
private LiveData<List<MentorEntity>> mAllMentors;
private SchedulerDatabase mSchedulerDatabase;
//executor to run only one thread, in order
private Executor executor = Executors.newSingleThreadExecutor();
//singleton creation of the scheduler repository
public static SchedulerRepository getInstance(Context context){
if(mSchedulerRepository == null){
synchronized (SchedulerRepository.class) {
if(mSchedulerRepository == null) {
mSchedulerRepository = new SchedulerRepository(context);
}
}
}
return mSchedulerRepository;
}
private SchedulerRepository(Context context){
mSchedulerDatabase = SchedulerDatabase.getDatabase(context);
mAllTerms = mSchedulerDatabase.termDAO().getTerms();
mAllCourses = mSchedulerDatabase.courseDAO().getCourses();
mAllAssessments = mSchedulerDatabase.assessmentDAO().getAssessments();
mAllMentors = mSchedulerDatabase.mentorDAO().getMentors();
}
//CRUD
//create
public void saveTerm(TermEntity term){
executor.execute(new Runnable() {
#Override
public void run() {
mSchedulerDatabase.termDAO().insertTerm(term);
}
});
}
public void saveCourse(CourseEntity course) {
executor.execute(new Runnable() {
#Override
public void run() {
mSchedulerDatabase.courseDAO().insertCourse(course);
}
});
}
public void saveMentor(MentorEntity mMentor) {
executor.execute(new Runnable() {
#Override
public void run() {
mSchedulerDatabase.mentorDAO().insert(mMentor);
}
});
}
public void saveAssessment(AssessmentEntity assessment) {
executor.execute(new Runnable() {
#Override
public void run() {
mSchedulerDatabase.assessmentDAO().insert(assessment);
}
});
}
public void addSampleData() {
executor.execute(new Runnable(){
#Override
public void run(){
try {
mSchedulerDatabase.termDAO().insertAll(TermSampleData.getTerms());
mSchedulerDatabase.courseDAO().insertAll(CourseSampleData.getCourses());
mSchedulerDatabase.assessmentDAO().insertAll(AssessmentSampleData.getAssessments());
mSchedulerDatabase.mentorDAO().insertAll(MentorSampleData.getMentors());
Log.i(TAG, "addSampleData().run()" + CourseSampleData.getCourses());
} catch (ParseException e) {
e.printStackTrace();
}
}
});
}
//read
public LiveData<List<TermEntity>> getAllTerms() {
return mAllTerms;
}
public LiveData<List<CourseEntity>> getAllCourses(){ return mAllCourses;}
public LiveData<List<AssessmentEntity>> getAllAssessments() {
return mAllAssessments;
}
public LiveData<List<MentorEntity>> getAllMentors() {
return mAllMentors;
}
//delete
public void deleteTerm(int termId) {
executor.execute(new Runnable() {
#Override
public void run() {
mSchedulerDatabase.termDAO().deleteTerm(termId);
}
});
}
public void deleteCourse(int courseId) {
executor.execute(new Runnable() {
#Override
public void run() {
mSchedulerDatabase.courseDAO().deleteCourse(courseId);
}
});
}
public void deleteAssessment(int assessmentId) {
executor.execute(new Runnable() {
#Override
public void run() {
mSchedulerDatabase.assessmentDAO().deleteAssessment(assessmentId);
}
});
}
}
Have you tried changing void insert(MentorEntity mentor); to long insert(MentorEntity mentor);
long insert(MentorEntity mentor); // this will return the row id
List<Long> insertAll(List<MentorEntity> mentors); // will return row ids created

How to fix 'No properties to serialize found on class' error in a Java class?

This question is not a duplicate. I have tried other methods shown in answers, but they don't seem to work. I am trying to iterate through all the documents in my "users" collection to get everyone's user name, store it into an ArrayList, and display it in my listview.
My ERROR Shown Is
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.example, PID: 17169
java.lang.RuntimeException: No properties to serialize found on class com.example.example.Model
at com.google.firebase.firestore.util.CustomClassMapper$BeanMapper.<init>(com.google.firebase:firebase-firestore##21.3.1:714)
at com.google.firebase.firestore.util.CustomClassMapper.loadOrCreateBeanMapperForClass(com.google.firebase:firebase-firestore##21.3.1:377)
at com.google.firebase.firestore.util.CustomClassMapper.convertBean(com.google.firebase:firebase-firestore##21.3.1:540)
at com.google.firebase.firestore.util.CustomClassMapper.deserializeToClass(com.google.firebase:firebase-firestore##21.3.1:253)
at com.google.firebase.firestore.util.CustomClassMapper.convertToCustomClass(com.google.firebase:firebase-firestore##21.3.1:100)
at com.google.firebase.firestore.DocumentSnapshot.toObject(com.google.firebase:firebase-firestore##21.3.1:210)
at com.google.firebase.firestore.QueryDocumentSnapshot.toObject(com.google.firebase:firebase-firestore##21.3.1:116)
at com.google.firebase.firestore.DocumentSnapshot.toObject(com.google.firebase:firebase-firestore##21.3.1:188)
at com.google.firebase.firestore.QueryDocumentSnapshot.toObject(com.google.firebase:firebase-firestore##21.3.1:97)
at com.example.example.LeaderboardActivity$1.onSuccess(LeaderboardActivity.java:46)
at com.example.example.LeaderboardActivity$1.onSuccess(LeaderboardActivity.java:42)
at com.google.android.gms.tasks.zzn.run(Unknown Source:4)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
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:858)
My Leaderboard Class
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
public class LeaderboardActivity extends AppCompatActivity {
ArrayList<String> usersInfo = new ArrayList<>();
FirebaseFirestore fStore = FirebaseFirestore.getInstance();
FirebaseAuth fAuth= FirebaseAuth.getInstance();
String userID= fAuth.getCurrentUser().getUid();
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_leaderboard);
lv = findViewById(R.id.leaderboardlist);
CollectionReference cr = fStore.collection("users");
cr.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
for (QueryDocumentSnapshot documentSnapshot : queryDocumentSnapshots){ //Line 42
Model mod = documentSnapshot.toObject(Model.class);
String Name = mod.getName();
usersInfo.add(Name);
System.out.println(usersInfo); //Line 46
}
}
});
usersInfo.add("aggg");
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,usersInfo);
lv.setAdapter(adapter);
System.out.println(usersInfo);
final Context context = this;
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_arcade:
Intent intentSettings = new Intent(context, MenuActivity.class);
startActivity(intentSettings);
finish();
break;
case R.id.action_home:
Intent intentHome = new Intent(context, Menu2.class);
startActivity(intentHome);
finish();
break;
case R.id.action_account:
Intent intentAccount = new Intent(context, AccountActivity.class);
startActivity(intentAccount);
finish();
break;
}
return false;
}
});
}
}
My Model Class
import androidx.annotation.Keep;
import java.io.Serializable;#Keep
public class Model implements Serializable {
public static String Name;
public static String Email;
public static int Coin_Toss_High_Score;
public static int Rps_High_Score;
public static int TicTacToe_High_Score;
public Model() {}
public Model(String name, String email, int ticTacToe_High_Score, int coin_Toss_High_Score, int rps_High_Score){
this.Name = name;
this.Email = email;
this.TicTacToe_High_Score = ticTacToe_High_Score;
this.Coin_Toss_High_Score = coin_Toss_High_Score;
this.Rps_High_Score = rps_High_Score;
}
public static String getName() {
return Name;
}
public static String getEmail() {
return Email;
}
public static int getCoin_Toss_High_Score() {
return Coin_Toss_High_Score;
}
public static int getRps_High_Score() {
return Rps_High_Score;
}
public static int getTicTacToe_High_Score() {
return TicTacToe_High_Score;
}
public static void setName(String name) {
Name = name;
}
public static void setEmail(String email) {
Email = email;
}
public static void setCoin_Toss_High_Score(int coin_Toss_High_Score) {
Coin_Toss_High_Score = coin_Toss_High_Score;
}
public static void setRps_High_Score(int rps_High_Score) {
Rps_High_Score = rps_High_Score;
}
public static void setTicTacToe_High_Score(int ticTacToe_High_Score) {
TicTacToe_High_Score = ticTacToe_High_Score;
}
}
You need to Add this Gson library
implementation 'com.squareup.retrofit2:converter-gson:2.6.0'
then import java.io.Serializable;#Keep remove this and import this in your class
import com.google.gson.annotations.SerializedName
change this :
public static String Name;
public static String Email;
public static int Coin_Toss_High_Score;
public static int Rps_High_Score;
public static int TicTacToe_High_Score;
To this :
public String Name;
public String Email;
public int Coin_Toss_High_Score;
public int Rps_High_Score;
public int TicTacToe_High_Score;
Even i thing if you already have getter() setter() method this way even you are making it public you can access all this property through getter() and setter() method.
This should be like this:
public class Model implements Serializable {
private String Name;
private String Email;
private int Coin_Toss_High_Score;
private int Rps_High_Score;
private int TicTacToe_High_Score;
public Model(String name, String email, int coin_Toss_High_Score, int rps_High_Score, int ticTacToe_High_Score) {
Name = name;
Email = email;
Coin_Toss_High_Score = coin_Toss_High_Score;
Rps_High_Score = rps_High_Score;
TicTacToe_High_Score = ticTacToe_High_Score;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public int getCoin_Toss_High_Score() {
return Coin_Toss_High_Score;
}
public void setCoin_Toss_High_Score(int coin_Toss_High_Score) {
Coin_Toss_High_Score = coin_Toss_High_Score;
}
public int getRps_High_Score() {
return Rps_High_Score;
}
public void setRps_High_Score(int rps_High_Score) {
Rps_High_Score = rps_High_Score;
}
public int getTicTacToe_High_Score() {
return TicTacToe_High_Score;
}
public void setTicTacToe_High_Score(int ticTacToe_High_Score) {
TicTacToe_High_Score = ticTacToe_High_Score;
}
}

How to pass data collected in arraylist from json asset file in one activity having recyclerview to another activity again having recycler view?

I have an activity named Cardview Activity which has a recycler view associated with it and i am fetching data from a JSON asset file in that. But now when i click on an item of Cardview Activity, I want to send data related to that item only to another activity i.e. People_List_Activity which is again having a recyclerView.
CardViewActivity.java
package com.example.android.directory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
public class CardViewActivity extends AppCompatActivity {
Toolbar mActionBarToolbar;
private RecyclerView mainRecyclerView;
private RecyclerView.Adapter mainAdapter;
private RecyclerView.LayoutManager mainLayoutManager;
private static String LOG_TAG = "CardViewActivity";
EditText inputSearchMain;
private ArrayList<CategoryModel.CategoryList> categoryLists;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_card_view);
mActionBarToolbar = (Toolbar) findViewById(R.id.tool_bar);
mActionBarToolbar.setTitle("Telephone Directory");
mActionBarToolbar.setLogo(R.drawable.toolbar_logo);
mActionBarToolbar.setTitleMargin(5,2,2,2);
setSupportActionBar(mActionBarToolbar);
categoryLists=new ArrayList<CategoryModel.CategoryList>();
categoryLists.addAll(getmcategoryset());
mainRecyclerView=(RecyclerView)findViewById(R.id.recyclerView_Main);
mainRecyclerView.setHasFixedSize(true);
mainLayoutManager=new LinearLayoutManager(this);
mainRecyclerView.setLayoutManager(mainLayoutManager);
mainAdapter=new RecyclerViewAdapterMain(getmcategoryset());
mainRecyclerView.setAdapter(mainAdapter);
inputSearchMain = (EditText) findViewById(R.id.inputSearchMain);
addTextListener();
}
public void addTextListener(){
inputSearchMain.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence query, int start, int before, int count) {
query = query.toString().toLowerCase();
final ArrayList<CategoryModel.CategoryList> filteredList = new ArrayList<CategoryModel.CategoryList>();
for (int i = 0; i < categoryLists.size(); i++) {
final String text = categoryLists.get(i).getCategory_name().toLowerCase();
if (text.contains(query)) {
filteredList.add(categoryLists.get(i));
}
}
mainRecyclerView.setLayoutManager(new LinearLayoutManager(CardViewActivity.this));
mainAdapter = new RecyclerViewAdapterMain(filteredList);
mainRecyclerView.setAdapter(mainAdapter);
mainAdapter.notifyDataSetChanged(); // data set changed
}
});
}
private ArrayList<CategoryModel.CategoryList> getmcategoryset() {
try {
ArrayList<CategoryModel.CategoryList>categoryList = new ArrayList<CategoryModel.CategoryList>();
JSONObject jsonObject = new JSONObject(readJSONFromAsset());
JSONArray categoryArray = jsonObject.getJSONArray("Category");
Log.d("getmcategoryset", "category count: "+categoryArray.length());
for (int i = 0; i < categoryArray.length(); i++)
{
JSONObject job = categoryArray.getJSONObject(i);
int categoryId = job.getInt("Category_id");
String categoryName = job.getString("Category_name");
//this is for email array
ArrayList<String> emails = new ArrayList<>();
JSONArray emailArray = job.getJSONArray("Emails");
for (int j = 0; j< emailArray.length(); j++){
emails.add(emailArray.getString(j));
}
//This i for Epabx array
ArrayList<String> epabx = new ArrayList<>();
JSONArray epabxArray = job.getJSONArray("Epabx");
for (int j = 0; j < epabxArray.length(); j++){
epabx.add(epabxArray.getString(j));
}
//This i for Category_Fax array
ArrayList<String> category_Fax = new ArrayList<>();
JSONArray category_FaxJson = job.getJSONArray("Category_Fax");
for (int j = 0; j < category_FaxJson.length(); j++){
category_Fax.add(category_FaxJson.getString(j));
}
//This i for Persons array
ArrayList<CategoryModel.Persons> personsList = new ArrayList<>();
JSONArray personsArray = job.getJSONArray("Persons");
for (int j = 0; j < personsArray.length(); j++){
JSONObject jobIn = personsArray.getJSONObject(j);
int Person_ID = jobIn.getInt("Person_ID");
String Name = jobIn.getString("Name");
String Designation = jobIn.getString("Designation");
String Office_Phone = jobIn.getString("Office_Phone");
String Residence_Phone = jobIn.getString("Residence_Phone");
String VOIP = jobIn.getString("VOIP");
String Address = jobIn.getString("Address");
//this is for Fax array
ArrayList<String>Fax = new ArrayList<>();
JSONArray fax = jobIn.getJSONArray("Fax");
for (int k=0; k < fax.length(); k++)
{
// JSONObject jobI = fax.getString(k);
Fax.add(fax.getString(k));
}
String Ext = jobIn.getString("Ext");
personsList.add(new CategoryModel.Persons(Person_ID, Name, Designation, Office_Phone, Residence_Phone,
VOIP, Address, Fax, Ext));
}
//here your Category[] value store in categoryArrayList
categoryList.add(new CategoryModel.CategoryList(categoryId, categoryName, emails, epabx, category_Fax, personsList));
Log.i("categoryList size = ", ""+categoryArray.length());
}
if (categoryList != null)
{
Log.i("categoryList size = ", ""+categoryArray.length());
}
return categoryList;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onResume() {
super.onResume();
}
public String readJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("DirectoryData.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
}
RecyclerViewAdapterMain
package com.example.android.directory;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Created by Android on 3/17/2017.
*/
public class RecyclerViewAdapterMain extends RecyclerView.Adapter<RecyclerViewAdapterMain.CategoryObjectHolder> {
private static String LOG_TAG = "categoryRecyclrVwAdptr";
private ArrayList<CategoryModel.CategoryList> mcategoryset;
private static CategoryClickListener categoryClickListener;
public static class CategoryObjectHolder extends RecyclerView.ViewHolder {
TextView category_name;
public CategoryObjectHolder(View itemView){
super(itemView);
category_name=(TextView)itemView.findViewById(R.id.category_name);
/*category_emails=(TextView)itemView.findViewById(R.id.category_emails);
category_epabx=(TextView)itemView.findViewById(R.id.category_epabx);
category_fax=(TextView)itemView.findViewById(R.id.category_fax);*/
Log.i(LOG_TAG, "Adding Listener");
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(CardViewActivity.this,PeopleListActivity.class);
}
});
}
public RecyclerViewAdapterMain(ArrayList<CategoryModel.CategoryList> myDataset) {
mcategoryset = myDataset;
}
public CategoryObjectHolder onCreateViewHolder(ViewGroup parent,int viewType){
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view_row_main_activity,parent,false);
CategoryObjectHolder categoryObjectHolder=new CategoryObjectHolder(view);
return categoryObjectHolder;
}
#Override
public void onBindViewHolder(CategoryObjectHolder holder, int position) {
holder.category_name.setText(mcategoryset.get(position).getCategory_name());
}
public void addItem(CategoryModel.CategoryList dataObj, int index) {
mcategoryset.add(index, dataObj);
notifyItemInserted(index);
}
public void deleteItem(int index) {
mcategoryset.remove(index);
notifyItemRemoved(index);
}
#Override
public int getItemCount() {
return mcategoryset.size();
}
public interface CategoryClickListener {
public void onItemClick(int position, View v);
}
}
People_List_Activity.java
package com.example.android.directory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
public class PeopleListActivity extends AppCompatActivity {
Toolbar mActionBarToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_people_list);
mActionBarToolbar = (Toolbar) findViewById(R.id.tool_bar);
mActionBarToolbar.setTitle("Staff List");
mActionBarToolbar.setLogo(R.drawable.toolbar_logo);
mActionBarToolbar.setTitleMargin(5,2,2,2);
setSupportActionBar(mActionBarToolbar);
}
}
RecyclerViewAdapter_People.java
package com.example.android.directory;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* Created by Android on 3/20/2017.
*/
public class RecyclerViewAdapter_People extends RecyclerView.Adapter<RecyclerViewAdapter_People.PeopleObjectHolder> {
private static String TAG = "peopleRecyclrVwAdptr";
public static class PeopleObjectHolder extends RecyclerView.ViewHolder{
TextView peopleName,peopleDesignation;
public PeopleObjectHolder(View itemView) {
super(itemView);
peopleName=(TextView)itemView.findViewById(R.id.people_name);
peopleDesignation=(TextView)itemView.findViewById(R.id.people_designation);
Log.d(TAG, "PeopleObjectHolder: ");
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
}
#Override
public PeopleObjectHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_people_list_row,parent,false);
PeopleObjectHolder peopleObjectHolder=new PeopleObjectHolder(view);
return peopleObjectHolder;
}
#Override
public void onBindViewHolder(RecyclerViewAdapter_People.PeopleObjectHolder holder, int position) {
}
#Override
public int getItemCount() {
return 0;
}
}
CategoryModel.java:
package com.example.android.directory;
import java.util.ArrayList;
/**
* Created by Android on 3/17/2017.
*/
public class CategoryModel {
private ArrayList<CategoryList>categoryList;
public ArrayList<CategoryList> getCategoryList() {
return categoryList;
}
public void setCategoryList(ArrayList<CategoryList> categoryList) {
this.categoryList = categoryList;
}
public static class CategoryList{
private int Category_id;
private String Category_name;
private ArrayList<String>Emails;
private ArrayList<String>Epabx;
private ArrayList<String>Category_Fax;
private ArrayList<Persons> persons;
public CategoryList(int category_id, String category_name,
ArrayList<String> emails, ArrayList<String> epabx, ArrayList<String> category_Fax,
ArrayList<Persons> persons) {
Category_id = category_id;
Category_name = category_name;
Emails = emails;
Epabx = epabx;
Category_Fax = category_Fax;
this.persons = persons;
}
public int getCategory_id() {
return Category_id;
}
public void setCategory_id(int category_id) {
Category_id = category_id;
}
public String getCategory_name() {
return Category_name;
}
public void setCategory_name(String category_name) {
Category_name = category_name;
}
public ArrayList<String> getEmails() {
return Emails;
}
public void setEmails(ArrayList<String> emails) {
Emails = emails;
}
public ArrayList<String> getEpabx() {
return Epabx;
}
public void setEpabx(ArrayList<String> epabx) {
Epabx = epabx;
}
public ArrayList<String> getCategory_Fax() {
return Category_Fax;
}
public void setCategory_Fax(ArrayList<String> category_Fax) {
Category_Fax = category_Fax;
}
public ArrayList<Persons> getPersons() {
return persons;
}
public void setPersons(ArrayList<Persons> persons) {
this.persons = persons;
}
}
public static class Persons{
private int Person_ID;
private String Name;
private String Designation;
private String Office_Phone;
private String Residence_Phone;
private String VOIP;
private String Address;
private ArrayList<String>Fax;
private String Ext;
public Persons(int person_ID, String name, String designation, String office_Phone,
String residence_Phone, String VOIP, String address, ArrayList<String> fax, String ext) {
Person_ID = person_ID;
Name = name;
Designation = designation;
Office_Phone = office_Phone;
Residence_Phone = residence_Phone;
this.VOIP = VOIP;
Address = address;
Fax = fax;
Ext = ext;
}
public int getPerson_ID() {
return Person_ID;
}
public void setPerson_ID(int person_ID) {
Person_ID = person_ID;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getDesignation() {
return Designation;
}
public void setDesignation(String designation) {
Designation = designation;
}
public String getOffice_Phone() {
return Office_Phone;
}
public void setOffice_Phone(String office_Phone) {
Office_Phone = office_Phone;
}
public String getResidence_Phone() {
return Residence_Phone;
}
public void setResidence_Phone(String residence_Phone) {
Residence_Phone = residence_Phone;
}
public String getVOIP() {
return VOIP;
}
public void setVOIP(String VOIP) {
this.VOIP = VOIP;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
public ArrayList<String> getFax() {
return Fax;
}
public void setFax(ArrayList<String> fax) {
Fax = fax;
}
public String getExt() {
return Ext;
}
public void setExt(String ext) {
Ext = ext;
}
}
}
how can i send the Person_Id, Name and Designation to the People_List_Activity ? Please help as i am stuck in the code.
You can send using Intent , by passing your data in Bundle and then pass Bundle into Intent Extras.When you go form one Activity to another .
Intent intent=new Intent(CardViewActivity.this,PeopleListActivity.class);
Bundle bundle = new Bundle();
bundle.putString("key1",value1);
bundle.putString("key2",value2);
bundle.putString("key3",value3);
intent.putExtras(bundle)
startActvity(intent);
And You can retrieve Data in next Activity OnCreate():
Bundle bundle = getIntent().getExtras();
String value1 = bundle.getString("key1");
String value2 = bundle.getString("key2");
String value3 = bundle.getString("key3");

Android Parse.com error with ArrayAdapter[App crash]

I am having a problem using the ParseObject, first tried ListActivity but the app was crashing, then saw few posts on stack overflow didnt work either, few details about the Parse Class are
Class Name : Events
Fields: String event_name;
String date;
String time;
String event_venue;
String speaker;
int fee;
String event_description;
The error in the program persists when the i am trying to initialize Adapter.
My code is as Follows
Events.java
public class Events extends ParseObject {
private String event_name;
private String date;
private String time;
private String event_venue;
private String speaker;
private int fee;
private String event_description;
public Events(String event_name, String date, String time, String event_venue, String speaker, int fee, String event_description) {
this.event_name = event_name;
this.date = date;
this.time = time;
this.event_venue = event_venue;
this.speaker = speaker;
this.fee = fee;
this.event_description = event_description;
}
public String getEvent_name() {
return event_name;
}
public void setEvent_name(String event_name) {
this.event_name = event_name;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getEvent_venue() {
return event_venue;
}
public void setEvent_venue(String event_venue) {
this.event_venue = event_venue;
}
public String getSpeaker() {
return speaker;
}
public void setSpeaker(String speaker) {
this.speaker = speaker;
}
public int getFee() {
return fee;
}
public void setFee(int fee) {
this.fee = fee;
}
public String getEvent_description() {
return event_description;
}
public void setEvent_description(String event_description) {
this.event_description = event_description;
}
}
Events_Activity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseQuery;
import java.util.ArrayList;
import java.util.List;
public class Event_Activity extends AppCompatActivity {
private List<Events> mEvents= new ArrayList<Events>();
private String e_name;
private String e_date;
private String e_time;
private String e_venue;
private String e_speaker;
private int e_fee;
private String e_description;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_);
ParseQuery<Events> event_query = new ParseQuery<Events>("Events");
event_query.findInBackground(new FindCallback<Events>() {
#Override
public void done(List<Events> list, ParseException e) {
if(e != null){
Toast.makeText(Event_Activity.this,"Exception : "+e,Toast.LENGTH_LONG).show();
}
for (Events event : list){
e_name = event.getEvent_name();
e_date = event.getDate();
e_time = event.getTime();
e_venue = event.getEvent_venue();
e_speaker = event.getSpeaker();
e_fee = event.getFee();
e_description = event.getEvent_description();
Events new_event = new Events(e_name,e_date,e_time,e_venue,e_speaker,e_fee,e_description);
mEvents.add(new_event);
}
}
});
ArrayAdapter<Events> value = new ArrayAdapter<Events>(Event_Activity.this,android.R.layout.simple_list_item_1, android.R.id.text1, mEvents);
ListView v = (ListView)findViewById(R.id.eventlistView);
v.setAdapter(value);
activity_event_.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.cse.Event_Activity">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/eventlistView">
</ListView>
</RelativeLayout>

Categories