Android list app using GSON - java

I am making a FuelLog app keep a log of fuel fill-ups at gas stations. I am having troubles using GSON to save things into the list as strings. The reason why I am saving an object is because each object (FuelLog) has many attributes including: "Gas Type", "Odometer Reading". etc. I would like to show those attributes on the list rather than "com.example.arshadhusain.fuelTracker.FuelLog#b1a33588" for example. Soon I would also like to edit these list items as well.
Here's how the list looks like so far.
Here's the class for the FuelLog:
public class FuelLog {
public String date;
public String station;
public String odometer;
public String fuelGrade;
public String fuelAmount;
public String fuelUnitCost;
public String fuelCost;
public FuelLog (String date, String station, String odometer, String fuelGrade, String fuelAmount, String fuelUnitCost, String fuelCost) {
this.date = date;
this.station = station;
this.odometer = odometer;
this.fuelGrade = fuelGrade;
this.fuelAmount = fuelAmount;
this.fuelUnitCost = fuelUnitCost;
this.fuelCost = fuelCost;
}
}
Here's the class that saves each log and updates the list (a prompt open for the user to add the attributes).
public class MainActivity extends Activity implements AdapterView.OnItemClickListener {
private Button button;
private EditText editTextMainScreen;
private ListView oldTweetsList;
private static final String FILENAME = "FuelTracker.sav";
private ArrayList<FuelLog> FuelLogs = new ArrayList<FuelLog>();
ArrayAdapter<FuelLog> adapter;
final Context context = this;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// components from main.xml
button = (Button) findViewById(R.id.button);
//editTextMainScreen = (EditText) findViewById(R.id.editTextResult);
oldTweetsList = (ListView) findViewById(R.id.oldTweetsList);
loadFromFile();
adapter = new ArrayAdapter<FuelLog>(this,
R.layout.list_item, FuelLogs);
oldTweetsList.setAdapter(adapter);
oldTweetsList.setOnItemClickListener(this);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// get prompts.xml view
LayoutInflater layoutInflater = LayoutInflater.from(context);
View promptView = layoutInflater.inflate(R.layout.prompts, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set prompts.xml to be the layout file of the alertdialog builder
alertDialogBuilder.setView(promptView);
final EditText input = (EditText) promptView.findViewById(R.id.userInput);
final EditText input1 = (EditText) promptView.findViewById(R.id.userInput1);
final EditText input2 = (EditText) promptView.findViewById(R.id.userInput2);
final EditText input3 = (EditText) promptView.findViewById(R.id.userInput3);
final EditText input4 = (EditText) promptView.findViewById(R.id.userInput4);
final EditText input5 = (EditText) promptView.findViewById(R.id.userInput5);
final EditText input6 = (EditText) promptView.findViewById(R.id.userInput6);
// setup a dialog window
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// get user input and set it to result
//editTextMainScreen.setText(input.getText());
setResult(RESULT_OK);
String station = input.getText().toString();
String odometer = input1.getText().toString();
String fuelGrade = input2.getText().toString();
String fuelAmount = input3.getText().toString();
String fuelUnitCost = input4.getText().toString();
String fuelCost = input5.getText().toString();
String date = input6.getText().toString(); //Date
FuelLog log = new FuelLog(date, station, odometer, fuelGrade, fuelAmount, fuelUnitCost, fuelCost);
FuelLogs.add(log);
adapter.notifyDataSetChanged();
saveInFile();
finish();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create an alert dialog
AlertDialog alertD = alertDialogBuilder.create();
alertD.show();
}
});
}

You can just Override toString() method in your FuelLog class like this:
#Override
public String toString() {
return "date = " + date + " station = " + station; // ...etc
}
or
Create custom adapter and in getView() method set you fields;

You can get rid off the problem by just overriding the ToString method of the class FuelLog, if you dont do that, the the list is printing out the hashcode of every FuelLog object added to your list.

Related

Save data from Main activity to a ListView activity

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

Spinner string not retrieved and passed to volleyrequest

I am wanting to get the string value from the spinner. I am currently using Volley in passing data but then it wasn't successful then. This is my RegisterActivity class:
public class RegUserPassClient extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reg_user_pass_client);
final Spinner spinner = findViewById(R.id.genderSpinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.genderString, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
final EditText regUserClient= (EditText) findViewById(R.id.regUserClient);
final EditText regPassClient= (EditText) findViewById(R.id.regPassClient);
final EditText regClientName = (EditText) findViewById(R.id.registerClientName);
final EditText regClientNumber = (EditText) findViewById(R.id.registerClientNumber);
final EditText regClientAddress = (EditText) findViewById(R.id.registerClientAddress);
final EditText regClientOccupation = (EditText) findViewById(R.id.registerClientOccupation);
final EditText regClientGender = (EditText) findViewById(R.id.registerClientGender);
final EditText regClientBirthDate = (EditText) findViewById(R.id.registerClientBirthDate);
final TextView clientUser = (TextView) findViewById(R.id.clientUserType);
final Button regClientBtn = (Button) findViewById(R.id.regClient);
final CheckBox toggle = (CheckBox) findViewById(R.id.checkBoxLog);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b){
regPassClient.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
}else{
regPassClient.setTransformationMethod(PasswordTransformationMethod.getInstance());
}
}
});
regClientBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = regUserClient.getText().toString();
final String password = regPassClient.getText().toString();
final String name = regClientName.getText().toString();
final String number = regClientNumber.getText().toString();
final String gender = spinner.toString();
final String address = regClientAddress.getText().toString();
final String occupation = regClientOccupation.getText().toString();
final String birthDate = regClientBirthDate.getText().toString();
final String userType = clientUser.getText().toString();
if(!username.isEmpty() && !password.isEmpty() &&
!name.isEmpty() && !address.isEmpty() &&
!occupation.isEmpty() && !gender.isEmpty() &&
!birthDate.isEmpty() && !number.isEmpty()) {
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
Intent intent = new Intent(RegUserPassClient.this, LoginRegister.class);
RegUserPassClient.this.startActivity(intent);
Toast.makeText(RegUserPassClient.this,"SuccessFully Registered! Log in your details now!",Toast.LENGTH_LONG).show();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(RegUserPassClient.this);
builder.setMessage("Username Has already been taken!")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegUserPassClientRequest registerRequest = new RegUserPassClientRequest(username, password, name, number, gender, address, occupation, birthDate, userType, responseListener);
RequestQueue queue = Volley.newRequestQueue(RegUserPassClient.this);
queue.add(registerRequest);
}else if(username.isEmpty()){
regUserClient.setError("Please insert a username");
}else if(password.isEmpty()){
regPassClient.setError("Please put your password");
}else if(name.isEmpty()){
regClientName.setError("Please input your name");
}else if(number.isEmpty()){
regClientNumber.setError("Put your phone number please");
}else if(address.isEmpty()){
regClientGender.setError("Please state your gender");
}else if(occupation.isEmpty()){
regClientAddress.setError("Please put your address");
}else if(gender.isEmpty()){
regClientOccupation.setError("Please state occupation");
}else if(birthDate.isEmpty()){
regClientBirthDate.setError("Please select your Birth Date");
}
}
});
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int i, long l) {
final String text = parent.getItemAtPosition(i).toString();
Toast.makeText(parent.getContext(), text, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
My functions for getting the spinner value are under the volleyrequest. I guess that is where my code is wrong but I don't really know what to put and where is the wrong thing.
It was just
final String gender = spinner.getSelectedItem().toString();
after all! Thanks anyways for viewing guys!

Sending radio button values in Android

Here is my AddLift.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_lift);
final EditText Origin = (EditText)findViewById(R.id.addOrigin);
final EditText Destination =
(EditText)findViewById(R.id.addDestination);
final EditText Time = (EditText)findViewById(R.id.setTime);
final EditText Seats = (EditText)findViewById(R.id.numOfSeats);
final RadioGroup DriverLifter = (RadioGroup)findViewById(driverLifter);
final RadioButton selectedButton =
(RadioButton)findViewById(selectedButton);
Button submit = (Button)findViewById(R.id.submitButton);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String addOrigin = Origin.getText().toString();
String addDestination = Destination.getText().toString();
String setTime = Time.getText().toString();
String numOfSeats = Seats.getText().toString();
int selectedId = DriverLifter.getCheckedRadioButtonId();
selectedButton = (RadioButton)findViewById(selectedId);
Intent intent = new Intent(AddLift.this, ViewLiftBoard.class);
intent.putExtra("ORIGIN", addOrigin);
intent.putExtra("DESTINATION", addDestination);
intent.putExtra("TIME", setTime);
intent.putExtra("SEATS", numOfSeats);
intent.putExtra("RADIO", driverLifter);
startActivity(intent);
}
});
And here is my ViewLiftBoard.java:
public class ViewLiftBoard extends AppCompatActivity {
String Origin;
String Destination;
String Time;
String Seats;
int DriverLifter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_lift_board);
Origin = getIntent().getExtras().getString("ORIGIN");
Destination = getIntent().getExtras().getString("DESTINATION");
Time = getIntent().getExtras().getString("TIME");
Seats = getIntent().getExtras().getString("SEATS");
DriverLifter = getIntent().getExtras().getInt("RADIO");
TextView textView = (TextView)findViewById(R.id.textView);
textView.setText("Origin:"+ "
"+Origin+'\n'+"Destination:"+""+Destination+'\n'+"Time:"+"
"+Time+'\n'+"Number of Seats:"+" "+Seats+'\n'+"Type:"+" "+DriverLifter);
}
}
But when I run the app the "Type" comes up as a number rather than the value of the selected radio button? Any help would be great
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_lift);
final EditText Origin = (EditText)findViewById(R.id.addOrigin);
final EditText Destination =
(EditText)findViewById(R.id.addDestination);
final EditText Time = (EditText)findViewById(R.id.setTime);
final EditText Seats = (EditText)findViewById(R.id.numOfSeats);
final RadioGroup DriverLifter = (RadioGroup)findViewById(driverLifter);
final RadioButton selectedButton =
(RadioButton)findViewById(selectedButton);
Button submit = (Button)findViewById(R.id.submitButton);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String addOrigin = Origin.getText().toString();
String addDestination = Destination.getText().toString();
String setTime = Time.getText().toString();
String numOfSeats = Seats.getText().toString();
int selectedId = DriverLifter.getCheckedRadioButtonId();
selectedButton = (RadioButton)findViewById(selectedId);
String selectedradio=selectedButton.gettex();
Intent intent = new Intent(AddLift.this, ViewLiftBoard.class);
intent.putExtra("ORIGIN", addOrigin);
intent.putExtra("DESTINATION", addDestination);
intent.putExtra("TIME", setTime);
intent.putExtra("SEATS", numOfSeats);
intent.putExtra("RADIO", selectedradio);
startActivity(intent);
}
});
ViewLiftBoard.java:
public class ViewLiftBoard extends AppCompatActivity {
String Origin;
String Destination;
String Time;
String Seats;
String DriverLifter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_lift_board);
Origin = getIntent().getExtras().getString("ORIGIN");
Destination = getIntent().getExtras().getString("DESTINATION");
Time = getIntent().getExtras().getString("TIME");
Seats = getIntent().getExtras().getString("SEATS");
DriverLifter = getIntent().getExtras().getString("RADIO");
TextView textView = (TextView)findViewById(R.id.textView);
textView.setText("Origin:"+ "
"+Origin+'\n'+"Destination:"+""+Destination+'\n'+"Time:"+"
"+Time+'\n'+"Number of Seats:"+" "+Seats+'\n'+"Type:"+" "+DriverLifter);
}
}
If you want to get text from selected radio button, you can use next combination:
RadioGroup driverLifter = (RadioGroup)findViewById(R.id.driverLifter);
String selectedButtonText = ((RadioButton)findViewById(driverLifter.getCheckedRadioButtonId())).getText().toString();
By the way, according to Java naming conventions, your variables should start from lower case.
That's because you are retrieving an Integer DataType from the intent extra
DriverLifter= getIntent().getExtras().getInt("RADIO");
To solve your problem you have to put this extra as a string in the intent, so instead of doing this :
intent.putExtra("RADIO", driverLifter);
Do this :
intent.putExtra("RADIO", (RadioButton) findValueById(DriverLifter .getCheckedRadioButton()). getText(). toString()) ;
And extract the Extra like this :
DriverLifter= getIntent().getExtras().getString("RADIO");

Firebase Database Data Returning Null When Reading

I am not sure why, I have explored both .setValue() and .updateChildren() methods, but for whatever reason when I read data from firebase it is returning null. Here is how I write to Firebase:
Model Poll Class:
#IgnoreExtraProperties
public class Poll {
private String question;
private String image_URL;
public Poll() {
}
public Poll(String Question, String Image_URL) {
this.question = Question;
this.image_URL = Image_URL;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getImage_URL() {
return image_URL;
}
public void setImage_URL(String image_URL) {
this.image_URL = image_URL;
}
#Exclude
public Map<String, Object> toMap(){
HashMap<String, Object> result = new HashMap<>();
result.put("question", question);
result.put("image_URL", image_URL);
return result;
}
}
*I am following the documentation here with my .toMap() method and use of .updateChildren()
Here is where I create my Firebase references and write to the database:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create);
mStorage = FirebaseStorage.getInstance();
mStorageRef = mStorage.getReferenceFromUrl("gs://firebase-fan-polls.appspot.com");
mBaseRef = FirebaseDatabase.getInstance().getReference();
mPollsRef = mBaseRef.child("Polls");
mAddImageButton = (FloatingActionButton) findViewById(R.id.add_image_button);
mAddAnswersButton = (ImageView) findViewById(R.id.add_answers_button);
mImagePreview = (ImageView) findViewById(R.id.preview_image);
mCreatePollQuestion = (EditText) findViewById(R.id.create_poll_question_editText);
mCreatePollAnswerCounter = (TextView) findViewById(R.id.create_poll_answer_counter_TextView);
mEditTextAnswerLayout = (ViewGroup) findViewById(R.id.create_poll_questions_answer_layout);
mSubmitPollCreation = (FloatingActionButton) findViewById(R.id.submit_poll_FAB);
mNumberOfPollAnswersCreatedByUser = 2;
mAnswerChoices = new ArrayList<>();
mCreatePollAnswerCounter.setText(String.valueOf(mNumberOfPollAnswersCreatedByUser));
for (int i = 0; i < mNumberOfPollAnswersCreatedByUser; i++) {
createAnswerChoice(i + 1);
}
mAddAnswersButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mNumberOfPollAnswersCreatedByUser++;
if (mNumberOfPollAnswersCreatedByUser > 5) {
Toast.makeText(getApplicationContext(), R.string.max_create_answers, Toast.LENGTH_SHORT).show();
return;
}
createAnswerChoice(mNumberOfPollAnswersCreatedByUser);
mCreatePollAnswerCounter.setText(String.valueOf(mNumberOfPollAnswersCreatedByUser));
}
});
mSubmitPollCreation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//TODO: Need to check if poll requirements are added, i.e. Question, Answer, ......
//check if image has been loaded first
if (resultImageURL == null) {
Toast.makeText(getApplicationContext(), getResources().getString(R.string.no_image_selected), Toast.LENGTH_LONG).show();
return;
}
Poll poll = new Poll(mCreatePollQuestion.getText().toString(), resultImageURL);
Map <String, Object> pollMap = poll.toMap();
String key = mBaseRef.child("Polls").push().getKey();
Map<String, Object> childUpdates = new HashMap<String, Object>();
childUpdates.put("/Polls/" + key, pollMap);
mBaseRef.updateChildren(childUpdates);
if (mNumberOfPollAnswersCreatedByUser > 5) {
Toast.makeText(getApplicationContext(), getResources().getText(R.string.poll_answers_greater_than_five), Toast.LENGTH_LONG).show();
mNumberOfPollAnswersCreatedByUser = 5;
}
Intent toHomeActivity = new Intent(CreateActivity.this, HomeActivity.class);
toHomeActivity.putExtra("viewpager_position", 2);
startActivity(toHomeActivity);
}
});
Everything is writing to Firebase correctly, as I can see it in the database in my console. I try and read it from this activity:
public class PollFragment extends Fragment {
#Bind(R.id.comment_label_counter)
TextView mCommentCounter;
#Bind(R.id.comments_label_icon)
ImageView mCommentsLabelIcon;
private DatabaseReference mBaseRef;
private DatabaseReference mPollsRef;
private DatabaseReference mSelectedPollRef;
private RadioGroup mPollQuestionRadioGroup;
private RadioGroup.LayoutParams mParams;
//static
private TextView mCommentsLabel;
private TextView mTotalVoteCounter;
private TextView mSelectedVote;
private TextView mYourVotelabel;
private ViewPager mViewPager;
private int mPagerCurrentPosition;
private static final String VOTE_COUNT_LABEL = "Vote_Count";
private static final String QUESTION_LABEL = "question";
private static final String ANSWERS_LABEL = "Answers";
private static final String POLL_LABEL = "Poll";
private static final String IMAGE_URL = "image_URL";
//all date items; dynamic
private DateFormat mDateFormat;
private Date mDate;
private String mCurrentDateString;
private TextView mPollQuestion;
private ArrayList<RadioButton> mPollAnswerArrayList;
private HorizontalBarChart mPollResults;
ArrayList<BarEntry> pollResultChartValues;
private BarDataSet data;
private ArrayList<IBarDataSet> dataSets;
private ValueEventListener valueEventListener;
private String pollID;
private int mPollIndex;
private ProgressBar mProgressBar;
private OnFragmentInteractionListener mListener;
public PollFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #return A new instance of fragment PollFragment.
*/
// TODO: Rename and change types and number of parameters
// TODO: Decide where to add comments button;
public static PollFragment newInstance(String pollIndex) {
PollFragment fragment = new PollFragment();
Bundle args = new Bundle();
args.putString("POLL_ID", pollIndex);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//TODO: check navigation to see if there are different ID's being generated from trending, following, and new fragments
Bundle args = getArguments();
String pollID = args.getString("POLL_ID");
Log.v("TAG", "THE PASSED ID Is " + pollID);
mBaseRef = FirebaseDatabase.getInstance().getReference();
mPollsRef = mBaseRef.child(POLL_LABEL);
mSelectedPollRef = mPollsRef.child(pollID);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO: Add Fragment Code to check if savedInstanceState == null; add at Activity Level?
// Inflate the layout for this fragment
final ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_poll, container, false);
ButterKnife.bind(this, rootView);
getActivity().setTitle(R.string.todays_polls_title);
//Initialize Poll Results Bar Chart and set to Invisible
mPollResults = (HorizontalBarChart) rootView.findViewById(R.id.poll_results_chart);
mPollResults.setBackgroundColor(getResources().getColor(R.color.white));
mPollResults.setNoDataTextDescription(getResources().getString(R.string.no_results_description));
mPollResults.setVisibility(View.INVISIBLE);
mTotalVoteCounter = (TextView) rootView.findViewById(R.id.total_vote_counter);
mCommentCounter = (TextView) rootView.findViewById(R.id.comment_label_counter);
mCommentCounter = (TextView) rootView.findViewById(R.id.comment_label_counter);
mProgressBar = (ProgressBar) rootView.findViewById(R.id.progress_bar_white);
mPollQuestion = (TextView) rootView.findViewById(R.id.poll_question);
mPollQuestion.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.poll_question_text_size));
mPollQuestionRadioGroup = (RadioGroup) rootView.findViewById(R.id.poll_question_group);
mSelectedPollRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.v("TAG", dataSnapshot.getKey());
//add question
String pollQuestion = (String) dataSnapshot.child(QUESTION_LABEL).getValue();
Log.v("TAG", "THE POLL QUESTION IS " + pollQuestion);
mPollQuestion.setText(pollQuestion);
mPollQuestion.setTypeface(null, Typeface.BOLD);
//add image
String pollImageURL = (String) dataSnapshot.child(IMAGE_URL).getValue();
Log.v("TAG", "THE POLL IMAGE URL IS" + pollImageURL);
Picasso.with(getActivity())
.load(pollImageURL)
.fit()
.placeholder(R.drawable.loading_spinner_white)
.into((ImageView) rootView.findViewById(R.id.poll_image));
Finally, here is my Firebase Database:
Careless mistake:
private static final String POLL_LABEL = "Poll";
Should be:
private static final String POLL_LABEL = "Polls";
The first choice was not the correct Firebase referencing thus causing the error.

Changing page values based on a button press

What I'm trying to make happen
User clicks babyOneButton
babyOneButton sets the profile_selected attribute in the GENERAL_PREFERENCES.xml shared preferences file
babyOneButton checks if the XML file exists
(1) If it does, send the user the to the page to edit the profile
(2) If it doesn't, send the user to the page to create a new profile
On either page, 'BABY_ONE_PROFILE.xml' data would be shown.
What it's actually doing:
User clicks babyOneButton
Sometimes after pressing submit on NewChildProfile, the name will show up on MainActivity where baby2's name should be?
No matter if the XML file exists or not, the user is always sent to the page to make a new profile. (If I switch the if/else statements around they'll always be sent to the manage page, so I'm assuming my way of finding if the profile exists isn't correct).
BABY_TWO_PROFILE is always the data shown on NewBabyProfile.
MainActivity.java
public class MainActivity extends Activity {
SharedPreferences generalPrefs;
SharedPreferences.Editor generalPrefsEditor;
public static String profileSelected;
public static String babyOneName;
public static String babyTwoName;
File file1, file2, file3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
file1 = new File("/data/data/com.parentingreminders/shared_prefs/BABY_ONE_PROFILE.XML");
file2 = new File("/data/data/com.parentingreminders/shared_prefs/BABY_TWO_PROFILE.XML");
String BABY_ONE_PROFILE = getString(R.string.baby_one_profile);
String BABY_TWO_PROFILE = getString(R.string.baby_two_profile);
SharedPreferences babyOneProfile = getSharedPreferences(BABY_ONE_PROFILE, 0);
SharedPreferences babyTwoProfile = getSharedPreferences(BABY_TWO_PROFILE, 0);
String babyOneName = babyOneProfile.getString("name", "name");
TextView babyOneNameOutput = (TextView) findViewById(R.id.baby_1_name);
babyOneNameOutput.setText(babyOneName.substring(0,1).toUpperCase() + babyOneName.substring(1));
String babyTwoName = babyTwoProfile.getString("name", "name");
TextView babyTwoNameOutput = (TextView) findViewById(R.id.baby_2_name);
babyTwoNameOutput.setText(babyTwoName.substring(0,1).toUpperCase() + babyTwoName.substring(1));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.new_baby_profile, menu);
return true;
}
public void babyOneButtonClick(View view) {
profileSelected = "1";
generalPrefs = getSharedPreferences(getString(R.string.general_preferences), Context.MODE_PRIVATE);
generalPrefsEditor = generalPrefs.edit();
generalPrefsEditor.putString("profile_selected", profileSelected).commit();
if (file1.exists()) {
Intent goToManageBaby1 = new Intent(this, ManageBaby1.class);
startActivity(goToManageBaby1);
} else {
Intent goToNewBabyProfile = new Intent(this, NewBabyProfile.class);
startActivity(goToNewBabyProfile);
}
}
public void babyTwoButtonClick(View view) {
profileSelected = "2";
generalPrefs = getSharedPreferences(getString(R.string.general_preferences), Context.MODE_PRIVATE);
generalPrefsEditor = generalPrefs.edit();
generalPrefsEditor.putString("profile_selected", profileSelected).commit();
if (file2.exists()) {
Intent goToManageBaby1 = new Intent(this, ManageBaby1.class);
startActivity(goToManageBaby1);
} else {
Intent goToNewBabyProfile = new Intent(this, NewBabyProfile.class);
startActivity(goToNewBabyProfile);
}
}}
NewBabyProfile.java
public class NewBabyProfile extends Activity {
public static String gender = "na";
public static String name = "na";
public static String dobMonth = "January";
public static String dobDay = "01";
public static String dobYear = "1900";
public static String feedingOz = "00";
public static String feedingHrs = "00";
public static String awakeHrs = "00";
public static int activeStartHour = 0;
public static int activeStartMinute = 0;
public static int activeEnd = 0;
public static String allDay = "no";
public static Spinner mSpinner;
public static int profileNumber;
public static String profileCreated;
public static String profileSelected;
SharedPreferences babyProfile, generalPrefs;
SharedPreferences.Editor editor, generalPrefsEditor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_baby_profile);
mSpinner = (Spinner) findViewById(R.id.dob_month);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.months_array, 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
mSpinner.setAdapter(adapter);
generalPrefs = getSharedPreferences(getString(R.string.general_preferences), Context.MODE_PRIVATE);
generalPrefsEditor = generalPrefs.edit();
// SharedPreferences initializations
profileSelected = generalPrefs.getString("profile_selected", "profileSelected");
if (profileSelected == "1") {
babyProfile = getSharedPreferences(getString(R.string.baby_one_profile), 0);
}
if (profileSelected == "2"){
babyProfile = getSharedPreferences(getString(R.string.baby_two_profile), 0);
}
editor = babyProfile.edit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.new_baby_profile, menu);
return true;
}
public void onRadioButtonClicked(View genderSelection){
boolean checked = ((RadioButton) genderSelection).isChecked();
switch(genderSelection.getId()) {
case R.id.gender_boy:
if (checked)
gender = "boy";
break;
case R.id.gender_girl:
if (checked)
gender = "girl";
break;
}
}
public void submitNewBabyProfile(View view) {
// Submit name
EditText nameInput = (EditText)findViewById(R.id.name_input);
name = nameInput.getText().toString().trim();
editor.putString("name",name).commit();
// Submit gender
editor.putString("gender",gender).commit();
// Submit date of birth
String dobMonth = mSpinner.getSelectedItem().toString();
editor.putString("dob_month",dobMonth).commit();
EditText dobDayInput = (EditText)findViewById(R.id.dob_day);
dobDay = dobDayInput.getText().toString().trim();
editor.putString("dob_day",dobDay).commit();
EditText dobYearInput = (EditText)findViewById(R.id.dob_year);
dobYear = dobYearInput.getText().toString().trim();
editor.putString("dob_year",dobYear).commit();
// Submit feeding information
EditText feedingOzInput = (EditText)findViewById(R.id.feeding_oz_input);
feedingOz = feedingOzInput.getText().toString().trim();
editor.putString("feeding_oz_input",feedingOz).commit();
EditText feedingHrInput = (EditText)findViewById(R.id.feeding_hr_input);
feedingHrs = feedingHrInput.getText().toString().trim();
editor.putString("feeding_hr_input",feedingHrs).commit();
// Submit nap information
EditText awakeInput = (EditText)findViewById(R.id.awake_input);
awakeHrs = awakeInput.getText().toString().trim();
editor.putString("awake_input",awakeHrs).commit();
// Submit notification active times
// Return to main activity
Intent goToMainActivity = new Intent(this, MainActivity.class);
startActivity(goToMainActivity);
}
}
Not sure that's the problem but you should never set absolute path strings, as you cannot know the root data path on all Android devices
Look at this : Android basics data storage
The filenames for the SharedPreferences are internal, that's why there's an API. Try replacing
if (file2.exists())
with this
if(babyTwoProfile.contains("name"))

Categories

Resources