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();
}
}));
Related
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
I was working with android project these days, and It will finish soon, but I got stuck in my project. First, I want to create search activity which will be used for searching movies. The searching activity runs well, but whenever it comes to adding the selected movie, it shown me the error code below:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.idstream.pojo.Movies.setTitle(java.lang.String)' on a null object reference
at com.example.idstream.search.MoviesDetailActivity.addFavorite(MoviesDetailActivity.java:96)
at com.example.idstream.search.MoviesDetailActivity.access$100(MoviesDetailActivity.java:19)
at com.example.idstream.search.MoviesDetailActivity$1.onClick(MoviesDetailActivity.java:78)
This code has an error in this area:
Movies movies = getIntent().getParcelableExtra(EXTRA_TITLE);
movies.setTitle(getIntent().getStringExtra(EXTRA_TITLE));
movies.setRelease_info(getIntent().getStringExtra(EXTRA_RELEASE));
movies.setLanguage(getIntent().getStringExtra(EXTRA_LANGUAGE));
movies.setDescription(getIntent().getStringExtra(EXTRA_OVERVIEW));
movies.setPhotos(getIntent().getStringExtra(EXTRA_PHOTOS));
I've tried to add the selected movie to database in other activity, but it didn't mention any error. But when I tried to save the selected movie to database, it turns out an error. I also tried to send it to a toast, which I wanna make sure whether the value that I sent was successfully retrieved. The toast is successfully get the data.
Here is my SearchFragment.java:
public class SearchMovieFragment extends Fragment implements LoaderManager.LoaderCallbacks<ArrayList<Movies>> {
ListView lvMovieItems;
EditText txtTitleMovieInput;
ImageView imgMoviesSearch;
Button btnSearchMovie;
AdaptersMovie adaptersMovie;
MovieHelper movieHelper;
Boolean act = true;
Boolean insert = true;
Boolean delete = true;
private View mView;
public SearchMovieFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mView = inflater.inflate(R.layout.fragment_search_movie, container, false);
txtTitleMovieInput = (EditText)mView.findViewById(R.id.txtMovieTitle);
String mTitles = txtTitleMovieInput.getText().toString();
Bundle bundle = new Bundle();
bundle.putString(EXTRA_MOVIE, mTitles);
imgMoviesSearch = (ImageView)mView.findViewById(R.id.imgMovies);
btnSearchMovie = (Button) mView.findViewById(R.id.btn_search);
btnSearchMovie.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mTitleMovie = txtTitleMovieInput.getText().toString();
if(TextUtils.isEmpty(mTitleMovie)){
return;
}
Bundle bundle = new Bundle();
bundle.putString(EXTRA_MOVIE, mTitleMovie);
getLoaderManager().restartLoader(0, bundle, SearchMovieFragment.this);
}
});
getLoaderManager().initLoader(0, bundle, SearchMovieFragment.this);
adaptersMovie = new AdaptersMovie(getActivity());
adaptersMovie.notifyDataSetChanged();
lvMovieItems = (ListView)mView.findViewById(R.id.listMovies);
lvMovieItems.setAdapter(adaptersMovie);
lvMovieItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Movies item = (Movies)parent.getItemAtPosition(position);
Intent intent = new Intent(getActivity(), MoviesDetailActivity.class);
intent.putExtra(MoviesDetailActivity.EXTRA_MOVIE, item.getTitle());
intent.putExtra(MoviesDetailActivity.EXTRA_RELEASE, item.getRelease_info());
intent.putExtra(MoviesDetailActivity.EXTRA_LANGUAGE, item.getLanguage());
intent.putExtra(MoviesDetailActivity.EXTRA_OVERVIEW, item.getDescription());
intent.putExtra(MoviesDetailActivity.EXTRA_PHOTOS, item.getPhotos());
startActivity(intent);
}
});
return mView;
}
#NonNull
#Override
public Loader<ArrayList<Movies>> onCreateLoader(int id, #Nullable Bundle args) {
String temp = "";
if (args != null){
temp = args.getString(EXTRA_MOVIE);
}
return new MovieAsyncTaskLoader(getActivity(), temp);
}
#Override
public void onLoadFinished(#NonNull Loader<ArrayList<Movies>> loader, ArrayList<Movies> data) {
adaptersMovie.setData(data);
}
#Override
public void onLoaderReset(#NonNull Loader<ArrayList<Movies>> loader) {
adaptersMovie.setData(null);
}
}
My MoviesDetailActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movies_detail);
setTitle("Movie's Details");
tvTitles = findViewById(R.id.movieTitles);
tvReleased = findViewById(R.id.movieRelease);
tvLanguages = findViewById(R.id.movieLanguages);
tvDescription = findViewById(R.id.movieDescriptions);
imageMovies = findViewById(R.id.moviesImage);
progressBar = findViewById(R.id.progressMovie);
fav_moviesBtn = findViewById(R.id.fab_movie);
progressBar.setVisibility(View.VISIBLE);
String mvTitles = getIntent().getStringExtra(EXTRA_MOVIE);
String mvLanguages = getIntent().getStringExtra(EXTRA_LANGUAGE);
String mvOverview = getIntent().getStringExtra(EXTRA_OVERVIEW);
String mvRelease = getIntent().getStringExtra(EXTRA_RELEASE);
String mvPhotos = getIntent().getStringExtra(EXTRA_PHOTOS);
tvTitles.setText(mvTitles);
tvReleased.setText(mvRelease);
tvLanguages.setText(mvLanguages);
tvDescription.setText(mvOverview);
Glide.with(MoviesDetailActivity.this)
.load("https://image.tmdb.org/t/p/w185" + mvPhotos)
.placeholder(R.color.colorFreshOrange)
.dontAnimate()
.into(imageMovies);
movieHelper = new MovieHelper(MoviesDetailActivity.this);
movieHelper.open();
mMoviess = getIntent().getIntExtra(FAVOURITE,0);
fav_moviesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!isAdd) {
addFavorite();
Toast.makeText(MoviesDetailActivity.this, "Berhasil Ditambahkan", Toast.LENGTH_LONG).show();
fav_moviesBtn.setImageResource(R.drawable.ic_launcher_fav_yes_24_foreground);
} else {
removeFavorite();
Toast.makeText(MoviesDetailActivity.this, "Berhasil Dihapuskan", Toast.LENGTH_LONG).show();
fav_moviesBtn.setImageResource(R.drawable.ic_launcher_fav_no_24_foreground);
}
}
});
progressBar.setVisibility(View.GONE);
}
private void addFavorite() {
Movies movies = getIntent().getParcelableExtra(EXTRA_TITLE);
movies.setTitle(getIntent().getStringExtra(EXTRA_TITLE));
movies.setRelease_info(getIntent().getStringExtra(EXTRA_RELEASE));
movies.setLanguage(getIntent().getStringExtra(EXTRA_LANGUAGE));
movies.setDescription(getIntent().getStringExtra(EXTRA_OVERVIEW));
movies.setPhotos(getIntent().getStringExtra(EXTRA_PHOTOS));
movieHelper.insertMovie(movies);
}
private void removeFavorite() {
Movies movies = new Movies();
movies.setTitle(getIntent().getStringExtra(EXTRA_TITLE));
movies.setRelease_info(getIntent().getStringExtra(EXTRA_RELEASE));
movies.setLanguage(getIntent().getStringExtra(EXTRA_LANGUAGE));
movies.setDescription(getIntent().getStringExtra(EXTRA_OVERVIEW));
movies.setPhotos(getIntent().getStringExtra(EXTRA_PHOTOS));
movieHelper.deleteMovie(getIntent().getStringExtra(EXTRA_MOVIE));
}
}
And this one is my MovieHelper.java:
public Boolean getOne(String name){
String querySingleRecord = "SELECT * FROM " + DATABASE_TABLE + " WHERE " +DatabaseContract.MovieColoumn.TITLE+ " " + " LIKE " +"'"+name+"'" ;
Cursor cursor = database.rawQuery(querySingleRecord,null);
cursor.moveToFirst();
Log.d("cursor", String.valueOf(cursor.getCount()));
if (cursor.getCount() > 0 ){
return true;
}else if(cursor.getCount() == 0){
return false;
}
return false;
}
public long insertMovie(Movies mMovies){
ContentValues args = new ContentValues();
args.put(IDS,mMovies.getId());
args.put(DatabaseContract.MovieColoumn.TITLE,mMovies.getTitle());
args.put(DatabaseContract.MovieColoumn.RELEASE_INFO,mMovies.getRelease_info());
args.put(DatabaseContract.MovieColoumn.LANGUAGE,mMovies.getLanguage());
args.put(DatabaseContract.MovieColoumn.DESCRIPTION,mMovies.getDescription());
args.put(DatabaseContract.MovieColoumn.PHOTOS,mMovies.getPhotos());
return database.insert(DATABASE_TABLE,null,args);
}
I believe the problem is here:
Movies movies = getIntent().getParcelableExtra(EXTRA_TITLE);
movies.setTitle(getIntent().getStringExtra(EXTRA_TITLE));
Notice that you're using the same EXTRA_TITLE for both.
I think that what's happening is that getParcelableExtra() is returning null, because the implementation of Bundle (the extras) will catch the ClassCastException:
// ...
try {
return (T) o;
} catch (ClassCastException e) {
typeWarning(key, o, "Parcelable", e);
return null;
}
And then you get a NullPointerException when you try to call setTitle().
Instead, create a new Movies instance yourself:
Movies movies = new Movies();
movies.setTitle(getIntent().getStringExtra(EXTRA_TITLE));
Alternatively, you could implement the Parcelable interface in your Movies class, and then you wouldn't have to bother adding all of its fields one by one.
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.
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.
I have a splash screen using AsyncTask, it will download some data from database and store the data in ArrayList. This ArrayList will be used for RecyclerView in fragments of MainActivity.class.
The problem is when I run the app from Android Studio to my phone, everything works perfectly. But, when I destroy the app and run it manually from my phone it will display blank white screen and then it will crash. And if I run once again after it crashed, the app will work. So, this app will always work only if I run it from Android Studio or after it crashed.
The error says that it is caused by the empty list. If I'm not mistaken, I think the AsyncTask doesn't seem to work properly after the activity is destroyed. But I don't know how to fix it. Please help me to solve this problem.
SplashScreen.java
public class SplashScreenActivity extends AppCompatActivity {
public static Event event;
private static List<Feed> feedList;
private static List<Event> eventList;
private static List<Event> todayList;
private static List<Event> upcomingList;
private static List<Partner> partnerList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splashscreen);
Time today = new Time(Time.getCurrentTimezone());
today.setToNow();
Config.TODAY_DATE = String.valueOf(today.monthDay) + "-" + String.valueOf(today.month) + "-" + String.valueOf(today.year);
new DownloadData().execute("");
}
class DownloadData extends AsyncTask<String, Integer, String>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
startActivity(new Intent(getBaseContext(), WelcomeActivity.class));
finish();
}
#Override
protected String doInBackground(String... params) {
RequestHandler rh = new RequestHandler();
String JSON_STRING = rh.sendGetRequest(Config.URL_GET_ALL_DATA);
JSONObject jsonObject;
eventList = new ArrayList<>();
todayList = new ArrayList<>();
upcomingList = new ArrayList<>();
partnerList = new ArrayList<>();
feedList = new ArrayList<>();
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray getEvent = jsonObject.getJSONArray(Config.TAG_JSON_EVENT);
for (int i = 0; i < getEvent.length(); i++) {
int id = getEvent.getJSONObject(i).getInt(Config.TAG_ID);
int eoId = getEvent.getJSONObject(i).getInt(Config.TAG_EO_ID);
String eoName = getEvent.getJSONObject(i).getString(Config.TAG_EO_NAME);
String title = getEvent.getJSONObject(i).getString(Config.TAG_TITLE);
String day = getEvent.getJSONObject(i).getString(Config.TAG_DAY);
String date = getEvent.getJSONObject(i).getString(Config.TAG_DATE);
int price = getEvent.getJSONObject(i).getInt(Config.TAG_PRICE);
event = new Event(id, eoId, eoName, title, day, date, price);
eventList.add(event);
if(Config.TODAY_DATE.equals(event.getDate())){
todayList.add(event);
} else {
upcomingList.add(event);
}
}
JSONArray getPartner = jsonObject.getJSONArray(Config.TAG_JSON_PARTNER);
for (int i = 0; i < getPartner.length(); i++) {
int pId = getPartner.getJSONObject(i).getInt(Config.TAG_ID);
String pName = getPartner.getJSONObject(i).getString(Config.TAG_NAME);
String pEmail = getPartner.getJSONObject(i).getString(Config.TAG_EMAIL);
String pPhone = getPartner.getJSONObject(i).getString(Config.TAG_PHONE);
String pPhoto = getPartner.getJSONObject(i).getString(Config.TAG_PHOTO_URL);
Partner partner = new Partner(pId, pName, pEmail, pPhone, pPhoto);
partnerList.add(partner);
}
JSONArray getArticle = jsonObject.getJSONArray(Config.TAG_JSON_ARTICLE);
for (int i = 0; i < getArticle.length(); i++) {
int feedId = getArticle.getJSONObject(i).getInt(Config.TAG_ID);
String feedAuthor = getArticle.getJSONObject(i).getString(Config.TAG_FEED_AUTHOR);
String feedTitle = getArticle.getJSONObject(i).getString(Config.TAG_FEED_TITLE);
String feedContent = getArticle.getJSONObject(i).getString(Config.TAG_FEED_CONTENT);
String feedDate = getArticle.getJSONObject(i).getString(Config.TAG_FEED_DATE);
String feedThumbnail = getArticle.getJSONObject(i).getString(Config.TAG_FEED_THUMBNAIL);
Feed feed = new Feed(feedId, feedAuthor, feedTitle, feedContent, feedDate, feedThumbnail);
feedList.add(feed);
}
} catch (JSONException e) {
e.printStackTrace();
}
return JSON_STRING;
}
}
public static List<Feed> getFeedList(){ return feedList;}
public static List<Event> getEventList() {return eventList;}
public static List<Event> getTodayList() { return todayList;}
public static List<Event> getUpcomingList() { return upcomingList;}
public static List<Partner> getPartnerList() {return partnerList;}
}
DiscoverFragment.java
public class DiscoverFragment extends Fragment implements ViewPager.OnPageChangeListener, View.OnClickListener {
protected View view;
private LinearLayout pager_indicator;
private int dotsCount;
private ImageView[] dots;
private List<Feed> feedList;
private List<Event> eventList;
private List<Partner> partnerList;
public DiscoverFragment() {}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_discover, container, false);
RecyclerView recyclerViewEvent = (RecyclerView) view.findViewById(R.id.discover_event_recycler_view);
RecyclerView recyclerViewPartner = (RecyclerView) view.findViewById(R.id.discover_partner_recycler_view);
ClickableViewPager intro_images = (ClickableViewPager) view.findViewById(R.id.pager_introduction);
pager_indicator = (LinearLayout) view.findViewById(R.id.viewPagerCountDots);
eventList = SplashScreenActivity.getEventList();
partnerList = SplashScreenActivity.getPartnerList();
feedList = SplashScreenActivity.getFeedList();
EventAdapter eventAdapter = new EventAdapter(getContext(), eventList);
DiscoverPartnerAdapter discoverPartnerAdapter = new DiscoverPartnerAdapter(getContext(), partnerList);
DiscoverFeedAdapter mAdapter = new DiscoverFeedAdapter(getContext(), feedList);
final LinearLayoutManager layoutManagerEvent = new LinearLayoutManager(getContext());
final LinearLayoutManager layoutManagerPartner = new LinearLayoutManager(getContext());
layoutManagerEvent.setOrientation(LinearLayoutManager.HORIZONTAL);
layoutManagerPartner.setOrientation(LinearLayoutManager.HORIZONTAL);
addBottomDots(0);
intro_images.setAdapter(mAdapter);
intro_images.setCurrentItem(0);
intro_images.addOnPageChangeListener(this);
intro_images.setOnItemClickListener(new ClickableViewPager.OnItemClickListener() {
#Override
public void onItemClick(int position) {
Config.FEED_ID = position;
startActivity(new Intent(getContext(), ArticleActivity.class));
}
});
return view;
}
private void addBottomDots(int currentPage) {
dots = new ImageView[feedList.size()]; //the problem
pager_indicator.removeAllViews();
for (int i = 0; i < dots.length; i++) {
dots[i] = new ImageView(getContext());
dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
params.setMargins(4, 0, 4, 0);
pager_indicator.addView(dots[i], params);
}
if (dots.length > 0)
dots[currentPage].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
}
#Override
public void onClick(View v) {
switch (v.getId()) {
}
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
addBottomDots(position);
for (int i = 0; i < dotsCount; i++) {
dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));
}
dots[position].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
}
}
LogCat
01-29 00:40:57.565 32535-32535/com.irmaelita.esodiaapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.irmaelita.esodiaapp, PID: 32535
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at com.irmaelita.esodiaapp.fragment.DiscoverFragment.addBottomDots(DiscoverFragment.java:181)
at com.irmaelita.esodiaapp.fragment.DiscoverFragment.onCreateView(DiscoverFragment.java:158)
feedList is null. You create feedList instance when DownloadData task is executed. But you call feedList.size() in addBottomDots when fragment view should be created. So, most probably addBottomDots is called before DownloadData task is executed. You need to fix it.
The feedlist in your discover fragment is going empty while initializing. Please set a null check before doing so.It not about running from android studio.If I have understood it correctly you are trying to access a list from splasScreen activity after finishing it. ie in post execute you finish the current activity and the fragment is in main activity,so the list is going null.So if this is the case (and please correct me if not) then either download the data somewhere centrally or best way send it to main activity with intent and use it there. Also when running from android studio kill the app manually and run it again,while the phone is connected and see if it crashes in current scenario.
Send your data from doInBackground to MainActivity with sendBroadcast
Add broadcast method in DownloadData class
private void broadcast(SplashParcel parcel) {
Intent i = new Intent("splash_parcel");
i.putExtra("values", parcel);
sendBroadcast(i);
}
#Override
protected String doInBackground(String... params) {
// your code
// ..
try {
// your code
// ..
// send splashParcel to MainActivity
SplashParcel splashParcel = new SplashParcel(feedList, eventList, todayList, upcomingList, partnerList);
broadcast (splashParcel);
} catch (JSONException e) {
e.printStackTrace();
}
return JSON_STRING;
}
Add new class SplashParcel.java
public class SplashParcel implements Parcelable {
public static final Creator<SplashParcel> CREATOR = new Creator<SplashParcel>() {
#Override
public SplashParcel createFromParcel(Parcel in) {
return new SplashParcel(in);
}
#Override
public SplashParcel[] newArray(int size) {
return new SplashParcel[size];
}
};
private static List<Feed> _feedList;
private static List<Event> _eventList;
private static List<Event> _todayList;
private static List<Event> _upcomingList;
private static List<Partner> _partnerList;
protected SplashParcel(Parcel in) {
_feedList = new ArrayList<Feed>();
in.readList(_feedList, null);
_eventList = new ArrayList<Event>();
in.readList(_eventList, null);
_todayList = new ArrayList<Event>();
in.readList(_todayList, null);
_upcomingList = new ArrayList<Event>();
in.readList(_upcomingList, null);
_partnerList = new ArrayList<Partner>();
in.readList(_partnerList, null);
}
public SplashParcel(List<Feed> feedList, List<Event> eventList, List<Event> todayList, List<Event> upcomingList, List<Partner> partnerList) {
_feedList = feedList;
_eventList = eventList;
_todayList = todayList;
_upcomingList = upcomingList;
_partnerList = partnerList;
}
public SplashParcel() {
}
public List<Feed> getFeedList() {
return _feedList;
}
public void setFeedList(List<Feed> feedList) {
_feedList = feedList;
}
public List<Event> getEventList() {
return _eventList;
}
public void setEventList(List<Event> eventList) {
_eventList = eventList;
}
public List<Event> getTodayList() {
return _todayList;
}
public void setTodayList(List<Event> todayList) {
_todayList = todayList;
}
public List<Event> getUpcomingList() {
return _upcomingList;
}
public void setUpcomingList(List<Event> upcomingList) {
_upcomingList = upcomingList;
}
public List<Partner> getPartnerList() {
return _partnerList;
}
public void setPartnerList(List<Partner> partnerList) {
_partnerList = partnerList;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeList(_feedList);
parcel.writeList(_eventList);
parcel.writeList(_todayList);
parcel.writeList(_upcomingList);
parcel.writeList(_partnerList);
}
}
MainActivity.java
// member variable
private BroadcastReceiver _splashReceiver;
private Bundle _bundle = new Bundle();
#Override
protected void onResume() {
super.onResume();
splashReceiver();
}
// receive splashParcel from SplashScreenActivity
private void splashReceiver() {
if (_splashReceiver == null) {
_splashReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
SplashParcel splashParcel = intent.getParcelableExtra("values");
if (splashParcel != null) {
// save splashParcel into _budle
_bundle.putParcelable("splash_parcel", splashParcel);
}
}
};
registerReceiver(_splashReceiver, new IntentFilter("splash_parcel"));
}
}
//Send _bundle to DiscoverFragment
private void showDiscoverFragment(){
if(_bundle != null) {
// create instance of discoverFragment with passing _bundle as arguments
DiscoverFragment discoverFragment = new DiscoverFragment();
discoverFragment.setArguments(_bundle);
// replace activity_main.xml with discoverFragment
getSupportFragmentManager().beginTransaction().replace(R.id.main_container, discoverFragment).addBackStack(null).commit();
}
}
In onCreateView of DiscoverFragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
SplashParcel splashParcel = getArguments().getParcelable("splash_parcel");
if(splashParcel != null) {
// your splashParcel ready in here
List<Feed> feedList = splashParcel.getFeedList()
List<Event> eventList = splashParcel.getEventList()
List<Event> todayList = splashParcel.getTodayList();
List<Event> upcommingList = splashParcel.getUpcomingList();
List<Partner> partnerList = splashParcel.getPartnerList();
}
}