Hello I'm trying to put date and time pickers in one class.
Everything works fine when i call time picker but unfortunately if I click date calling button the time picker is also appears.
here is my code:
package com.example.aib.restauwacja;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;
import java.util.Calendar;
public class DateAndTimePicker extends ActionBarActivity {
EditText edit;
Button dateBtn;
Button timeBtn;
Button reserveBtn;
int year_x, mounth_x, day_x;
int hour_x, minute_x;
static final int DATE_DIALOG_ID = 0;
static final int TIME_DIALOG_ID = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.making_reservation);
final Calendar cal = Calendar.getInstance();
year_x = cal.get(Calendar.YEAR);
mounth_x = cal.get(Calendar.MONTH);
day_x = cal.get(Calendar.DAY_OF_MONTH);
showDateOnButtonClick();
showTimeOnButtonClick();
edit = (EditText) findViewById(R.id.amountEditText);
reserveBtn = (Button) findViewById(R.id.makeReservationButton);
reserveBtn.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
String amount = edit.getText().toString();
Toast.makeText(DateAndTimePicker.this, edit.getText(), Toast.LENGTH_SHORT).show();
}
}
);
}
public void showDateOnButtonClick() {
dateBtn = (Button)findViewById(R.id.datePickerButton);
dateBtn.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
}
);
}
private DatePickerDialog.OnDateSetListener dpickerListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
year_x = year;
mounth_x = monthOfYear + 1;
day_x = dayOfMonth;
Toast.makeText(DateAndTimePicker.this, day_x + "/" + mounth_x + "/" + year_x, Toast.LENGTH_SHORT).show();
}
};
public void showTimeOnButtonClick() {
timeBtn = (Button)findViewById(R.id.timePickerButton);
timeBtn.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(TIME_DIALOG_ID);
}
}
);
}
#Override
protected Dialog onCreateDialog(int id) {
if (id == TIME_DIALOG_ID)
return new TimePickerDialog(DateAndTimePicker.this, tpickerListener, hour_x, minute_x, true);
else if (id == DATE_DIALOG_ID)
return new DatePickerDialog(this, dpickerListener, year_x, mounth_x, day_x);
return null;
}
protected TimePickerDialog.OnTimeSetListener tpickerListener = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
hour_x = hourOfDay;
minute_x = minute;
Toast.makeText(DateAndTimePicker.this, hour_x + ":" + minute_x, Toast.LENGTH_SHORT).show();
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Use different id of DATE_DIALOG_ID and TIME_DIALOG_ID;
I think you need to give different id's for DATE_DIALOG_ID and TIME_DIALOG_ID.
check these fields once.
static final int DATE_DIALOG_ID = 0;
static final int TIME_DIALOG_ID = 1;
Related
These two classes send methods and variables back and forth to each other and my code says there's no errors, but the program won't open and I can't figure out why
Here's the first class, TopLevelActivity
package com.example.oife;
import android.media.Image;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ShareActionProvider;
import android.widget.TextView;
import android.content.Intent;
import android.view.View;
import java.text.SimpleDateFormat;
public class TopLevelActivity extends Activity {
TextView mText = (TextView) findViewById(R.id.calendarView);
private ShareActionProvider shareActionProvider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_oife);
long date = System.currentTimeMillis();
TextView displayDate = (TextView) findViewById(R.id.displayDate);
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy");
String dateString = sdf.format(date);
displayDate.setText(dateString);
}
public void onPostClick (View view) {
Intent intent = new Intent(this, PostActivity.class);
startActivity(intent);
}
//call onHomeClick() method when the button is clicked
public void onHomeClick (View view){
Intent intent = new Intent(this,TopLevelActivity.class);
startActivity(intent);
}
//call onMoreClick() method when the button is clicked
public void onMoreClick(View view){
Intent intent = new Intent(this, MoreActivity.class);
startActivity(intent);
}
public TextView getMainText(){
return mText;
}
public void setMText(TextView t){
mText.setText(t.getText());
}
}
Here's the second class, PostActivity
This class is where most of the functions from the other one are accessed
package com.example.oife;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.content.Intent;
import android.view.View;
public class PostActivity extends Activity {
private TextView pDisplayDate;
private Button pPickDate;
private int pYear;
private int pMonth;
private int pDay;
private TextView mainText;
static final int DATE_DIALOG_ID = 0;
private TextView name = (TextView) findViewById(R.id.name);
private TextView day;
TopLevelActivity top = new TopLevelActivity();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
/** Capture our View elements */
pDisplayDate = (TextView) findViewById(R.id.displayDate);
pPickDate = (Button) findViewById(R.id.pickDate);
/** Listener for click event of the button */
pPickDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
/** Get the current date */
final Calendar cal = Calendar.getInstance();
pYear = cal.get(Calendar.YEAR);
pMonth = cal.get(Calendar.MONTH);
pDay = cal.get(Calendar.DAY_OF_MONTH);
/** Display the current date in the TextView */
// updateDisplay();
}
private void setMainText(){
TextView d = (TextView) findViewById(R.id.description);
mainText.setText(top.getMainText() + "/n/n" + name + "/n" + makeDay().getText() + "/n" + d.getText());
}
private TextView makeDay(){
TextView ToD;
RadioGroup t = (RadioGroup) findViewById(R.id.TOD);
int id = t.getCheckedRadioButtonId();
if(id == -1) {
ToD = null;
}
else{
ToD = (TextView) findViewById(id);
}
TextView wow;
RadioGroup g = (RadioGroup) findViewById(R.id.WoW);
id = g.getCheckedRadioButtonId();
if (id == -1){
//no item selected
}
else{
wow = (TextView) findViewById(id);
}
TextView d = (TextView) findViewById(R.id.displayDate);
String s = String.valueOf(d);
String j;
if (ToD.getText().equals("Morning")){
j = "9:00";
}
else if(ToD.getText().equals("Midday")){
j = "12:00";
}
else if (ToD.getText().equals("Evening")){
j = "5:00";
}
else {
j = "10:00";
}
TextView time = new TextView(this);
time.setText( j + " " + s);
return time;
}
private DatePickerDialog.OnDateSetListener pDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
pYear = year;
pMonth = monthOfYear;
pDay = dayOfMonth;
updateDisplay();
displayToast();
}
};
private void updateDisplay() {
pDisplayDate.setText(
new StringBuilder()
// Month is 0 based so add 1
.append(pMonth + 1).append("/")
.append(pDay).append("/")
.append(pYear).append(" "));
}
private void updateMainDisplay(){
setMainText();
top.setMText(mainText);
}
private void displayToast() {
Toast.makeText(this, new StringBuilder().append("Date choosen is ").append(pDisplayDate.getText()), Toast.LENGTH_SHORT).show();}
/** Create a new dialog for date picker */
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this,
pDateSetListener,
pYear, pMonth, pDay);
}
return null;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_post, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onCreateClick(View view){
Intent intent = new Intent(this, TopLevelActivity.class);
updateMainDisplay();
startActivity(intent);
}
}
call code like this after you call setContentView:
Activity 1:
TextView mText = (TextView) findViewById(R.id.calendarView);
Activity 2:
private TextView name = (TextView) findViewById(R.id.name);
you did that wrong in both Activitys. You call findViewById in the member section of your Activitys and at this point the Activity dont know anything about the layout file.
That must leads to a NullpointerException.
I have an issue where I have a listview, go to another activity to attach uservalues which than implements those values to the listview. However, if I go back to that activity and attach a new set of values, when I return to my listview activity, the new values are implemented but the old values have been removed. Would an sqlite database solve this problem? Or does it have something to do with the actual list being recreate?
ListActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.personalproject.peter.timerapp.TestingForAlarmData.TestAlarm;
import java.util.ArrayList;
import java.util.List;
public class ListOfAlarms extends ActionBarActivity {
private static final int RESULT = 1000;
List<TestAlarm> alarms = new ArrayList<>();
String title;
int totalTime;
ListView listOfAlarms;
ArrayAdapter<TestAlarm> alarmArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_of_alarms);
final TextView emptyViewForList = (TextView) findViewById(R.id.emptyTextViewForList);
listOfAlarms = (ListView) findViewById(R.id.listView);
alarmArrayAdapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1, alarms);
listOfAlarms.setAdapter(alarmArrayAdapter);
// if(listOfAlarms.getCount() <= 0){
// emptyViewForList.setText("No Alarms Currently Available");
// listOfAlarms.setEmptyView(emptyViewForList);
// }
listOfAlarms.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
alarms.get(position);
Intent clockDownActivity = new Intent(ListOfAlarms.this, CountDownAct.class);
clockDownActivity.putExtra("Title", title);
clockDownActivity.putExtra("totalTime", totalTime);
startActivity(clockDownActivity);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_list_of_alarms, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void goToFillOut(View view) {
Intent goingToFillOut = new Intent(this, Test.class);
startActivityForResult(goingToFillOut, RESULT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == RESULT && resultCode == RESULT_OK){
title = data.getStringExtra("title");
totalTime = data.getIntExtra("totalTime", 0);
alarms.add(new TestAlarm(title, totalTime));
alarmArrayAdapter.notifyDataSetChanged();
}
}
}
SecondActivity
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Test extends ActionBarActivity {
private static final String LOGTAG = "Test.class";
private static final long timeInterval = 1000;
private Button complete;
private EditText titleEditText;
private EditText hourEditText;
private EditText minuteEditText;
private EditText secondEditText;
public static int hour;
public static int minute;
public static int second;
public static String title;
public int actualTimeFiniliazedInMilliSeconds;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
titleEditText = (EditText) findViewById(R.id.titleEditText);
hourEditText = (EditText) findViewById(R.id.hourEditText);
minuteEditText = (EditText) findViewById(R.id.minuteEditText);
secondEditText = (EditText) findViewById(R.id.secondEditText);
complete = (Button) findViewById(R.id.completeButton);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void saveTimer(View view) {
if(titleEditText.getText().toString().isEmpty() || hourEditText.getText().toString().isEmpty()
|| minuteEditText.getText().toString().isEmpty() || secondEditText.getText().toString().isEmpty()) {
Toast.makeText(this, "Oops you forgot one", Toast.LENGTH_LONG).show();
return;
}
// complete.setVisibility(View.GONE);
title = titleEditText.getText().toString();
hour = Integer.parseInt(hourEditText.getText().toString().trim());
minute = Integer.parseInt(minuteEditText.getText().toString().trim());
second = Integer.parseInt(secondEditText.getText().toString().trim());
hour *= 3600000;
minute *= 60000;
second *= 1000;
actualTimeFiniliazedInMilliSeconds = hour + minute + second;
Intent intent = new Intent(Test.this, ListOfAlarms.class);
intent.putExtra("title", title);
intent.putExtra("totalTime", actualTimeFiniliazedInMilliSeconds);
setResult(RESULT_OK, intent);
finish();
}
}
Alarm.java
public class TestAlarm {
public String title;
public int totalTime;
public TestAlarm (String title, int totalTime) {
this.title = title;
this.totalTime = totalTime;
}
#Override
public String toString() {
return title;
}
}
Simply try the following steps,don't need to use SqliteDB in this situation.
Create a Singleton class
Eg :
public class Singleton {
private static Singleton uniqInstance;
private List<TestAlarm> mAlarms = new ArrayList<>();
private Singleton() {
}
public static synchronized Singleton getInstance() {
if (uniqInstance == null) {
uniqInstance = new Singleton();
}
return uniqInstance;
}
public void setAllarms(List<TestAlarm> alarms){
this.mAlarms = alarms;
}
public List<TestAlarm> getAllarms(){
return this.mAlarms;
}
}
Save the allarms on the singleton class when navigating to another activity
listOfAlarms.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Singleton .getInstance().setAllarms(alarms); // Save the Collection
alarms.get(position);
Intent clockDownActivity = new Intent(ListOfAlarms.this, CountDownAct.class);
clockDownActivity.putExtra("Title", title);
clockDownActivity.putExtra("totalTime", totalTime);
startActivity(clockDownActivity);
}
});
on the onActivityResult retrieve the saved collection from singleton class
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == RESULT && resultCode == RESULT_OK){
title = data.getStringExtra("title");
totalTime = data.getIntExtra("totalTime", 0);
Singleton.getInstance().getAllarms().add(new TestAlarm(title, totalTime));
this.alarms = Singleton.getInstance().getAllarms();
alarmArrayAdapter.notifyDataSetChanged();
}
}
What is happening is that when you leave and come back to the activity, Android is recreating the activity and listview. So you need some way to save the data over this change.
Using a sqlite database would solve the problem, since the databse would be permanent storage, and would save the information long term (for example, if the user shuts off the phone).
Another solution would be to implement onSaveInstanceState and onRestoreInstanceState, which will save information over changing activities (or orientation). If they shut off the phone the information would be lost.
From your question it doesn't sound like you need to keep information really long term, and implementing onSaveInstanceState is less work than sqlite.
You are creating a new instance of the Activity with
Intent intent = new Intent(Test.this, ListOfAlarms.class);
So everything is recreated.
To avoid this, you need to use an empty constructor when creating the Intent that will be sent back to the starting activity.
Intent intent = new Intent(); // this should be empty
intent.putExtra("title", title);
intent.putExtra("totalTime", actualTimeFiniliazedInMilliSeconds);
setResult(RESULT_OK, intent);
finish();
See Going back to previous activity with different Intent value
and
The documentation
I have an application that populates a ListView with user input data from another Activity ; however, whenever I enter that data into the second Activity then return to the ListView activity, I see it populated with the values I entered. But, if I return to the second activity again, enter the values, and go back to the ListView activity, I see the new values updated but the old ones have disappeared.
Now, I don't know if I'm not updating the listview correctly or if I need to use SQLite databases to store this data or shared preferences in order to update the listview to new data while containing the previous information.
Thanks for any help.
ListActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.personalproject.peter.timerapp.TestingForAlarmData.TestAlarm;
import java.util.ArrayList;
import java.util.List;
public class ListOfAlarms extends ActionBarActivity {
private static final int RESULT = 1000;
List<TestAlarm> alarms = new ArrayList<>();
String title;
int totalTime;
ListView listOfAlarms;
ArrayAdapter<TestAlarm> alarmArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_of_alarms);
final TextView emptyViewForList = (TextView) findViewById(R.id.emptyTextViewForList);
listOfAlarms = (ListView) findViewById(R.id.listView);
alarmArrayAdapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1, alarms);
listOfAlarms.setAdapter(alarmArrayAdapter);
// if(listOfAlarms.getCount() <= 0){
// emptyViewForList.setText("No Alarms Currently Available");
// listOfAlarms.setEmptyView(emptyViewForList);
// }
listOfAlarms.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
alarms.get(position);
Intent clockDownActivity = new Intent(ListOfAlarms.this, CountDownAct.class);
clockDownActivity.putExtra("Title", title);
clockDownActivity.putExtra("totalTime", totalTime);
startActivity(clockDownActivity);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_list_of_alarms, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void goToFillOut(View view) {
Intent goingToFillOut = new Intent(this, Test.class);
startActivityForResult(goingToFillOut, RESULT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == RESULT && resultCode == RESULT_OK){
title = data.getStringExtra("title");
totalTime = data.getIntExtra("totalTime", 0);
alarms.add(new TestAlarm(title, totalTime));
alarmArrayAdapter.notifyDataSetChanged();
}
}
}
SecondActivity
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Test extends ActionBarActivity {
private static final String LOGTAG = "Test.class";
private static final long timeInterval = 1000;
private Button complete;
private EditText titleEditText;
private EditText hourEditText;
private EditText minuteEditText;
private EditText secondEditText;
public static int hour;
public static int minute;
public static int second;
public static String title;
public int actualTimeFiniliazedInMilliSeconds;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
titleEditText = (EditText) findViewById(R.id.titleEditText);
hourEditText = (EditText) findViewById(R.id.hourEditText);
minuteEditText = (EditText) findViewById(R.id.minuteEditText);
secondEditText = (EditText) findViewById(R.id.secondEditText);
complete = (Button) findViewById(R.id.completeButton);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void saveTimer(View view) {
if(titleEditText.getText().toString().isEmpty() || hourEditText.getText().toString().isEmpty()
|| minuteEditText.getText().toString().isEmpty() || secondEditText.getText().toString().isEmpty()) {
Toast.makeText(this, "Oops you forgot one", Toast.LENGTH_LONG).show();
return;
}
// complete.setVisibility(View.GONE);
title = titleEditText.getText().toString();
hour = Integer.parseInt(hourEditText.getText().toString().trim());
minute = Integer.parseInt(minuteEditText.getText().toString().trim());
second = Integer.parseInt(secondEditText.getText().toString().trim());
hour *= 3600000;
minute *= 60000;
second *= 1000;
actualTimeFiniliazedInMilliSeconds = hour + minute + second;
Intent intent = new Intent(Test.this, ListOfAlarms.class);
intent.putExtra("title", title);
intent.putExtra("totalTime", actualTimeFiniliazedInMilliSeconds);
setResult(RESULT_OK, intent);
finish();
}
}
Alarm.java
public class TestAlarm {
public String title;
public int totalTime;
public TestAlarm (String title, int totalTime) {
this.title = title;
this.totalTime = totalTime;
}
#Override
public String toString() {
return title;
}
}
I am quite new to programming Android (7 months), and I am having a problem with creating an app.
What I am trying to do is create a "Person Detail" test app for my own Android learning, by having EditText on the Main Activity with TextViews next to them (displaying default values at first), open up another activity called EditData (with a button on the main) which displays the values the user entered into the EditText (via Parcelable), return back to the Main Activty (via another button) and have those entered values displayed in the TextViews next to the EditText (upon a "Update Info" button click) instead of the default ones. I have managed to get everything working right except for displaying the changed values. Everything checks out, no errors in LogCat, but when the user / I clicks the update button, what shows are the default values. Can someone help me?
Here is my Main Activity code:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
final Person firstPerson = new Person();
TextView displayName, displayAge, displayHeight, displayWeight;
EditText editName, editAge, editHeight, editWeight;
Button editActivity, update;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
instantiateUi();
editActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firstPerson.setPersonName(editName.getText().toString());
firstPerson.setPersonAge(Integer.parseInt(editAge.getText().toString()));
firstPerson.setPersonHeight(Integer.parseInt(editHeight.getText().toString()));
firstPerson.setPersonWeight(Integer.parseInt(editWeight.getText().toString()));
Intent editIntent = new Intent(MainActivity.this, EditData.class);
editIntent.putExtra("First_Person_Data", firstPerson);
MainActivity.this.startActivity(editIntent);
}
});
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
displayName.setText(firstPerson.getPersonName());
displayAge.setText(String.valueOf(firstPerson.getPersonAge()));
// String.valueOf is needed to set int for TextViews
displayHeight.setText(String.valueOf(firstPerson.getPersonHeight()));
displayWeight.setText(String.valueOf(firstPerson.getPersonWeight()));
}
});
}
private void instantiateUi() {
editName = (EditText)findViewById(R.id.edit_name);
editAge = (EditText)findViewById(R.id.edit_age);
editHeight = (EditText)findViewById(R.id.edit_height);
editWeight = (EditText)findViewById(R.id.edit_weight);
displayName = (TextView)findViewById(R.id.display_name);
displayAge = (TextView)findViewById(R.id.display_age);
displayHeight = (TextView)findViewById(R.id.display_height);
displayWeight = (TextView)findViewById(R.id.display_weight);
editActivity = (Button)findViewById(R.id.edit_activity);
update = (Button)findViewById(R.id.update_info);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
}
My EditData activity code:
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class EditData extends ActionBarActivity {
TextView changedName, changedAge, changedHeight, changedWeight;
Button MainActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_activity);
Person incomingObject = getIntent().getParcelableExtra("First_Person_Data");
instantiateUi();
changedName.setText(incomingObject.getPersonName());
changedAge.setText(String.valueOf(incomingObject.getPersonAge()));
changedHeight.setText(String.valueOf(incomingObject.getPersonHeight()));
changedWeight.setText(String.valueOf(incomingObject.getPersonWeight()));
MainActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent EditActivity = new Intent(EditData.this, MainActivity.class);
EditData.this.startActivity(EditActivity);
}
});
}
private void instantiateUi() {
changedName = (TextView)findViewById(R.id.changed_name);
changedAge = (TextView)findViewById(R.id.changed_age);
changedHeight = (TextView)findViewById(R.id.changed_height);
changedWeight = (TextView)findViewById(R.id.changed_weight);
MainActivity = (Button)findViewById(R.id.main_activity);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.edit_data_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And my Parcelable class used for transferring data values:
import android.os.Parcel;
import android.os.Parcelable;
public class Person implements Parcelable{
String personName;
int personAge, personHeight, personWeight;
public Person(){
personName = "No Name!";
personAge = 0;
personHeight = 0;
personWeight = 0;
}
public Person(String pName, int pAge, int pHeight, int pWeight) {
personName = pName;
personAge = pAge;
personHeight = pHeight;
personWeight = pWeight;
}
public Person(Parcel in) {
personName = in.readString();
personAge = in.readInt();
personHeight = in.readInt();
personWeight = in.readInt();
}
public String getPersonName() {
return personName;
}
public void setPersonName(String personName) {
this.personName = personName;
}
public int getPersonAge() {
return personAge;
}
public void setPersonAge(int personAge) {
this.personAge = personAge;
}
public int getPersonHeight() {
return personHeight;
}
public void setPersonHeight(int personHeight) {
this.personHeight = personHeight;
}
public int getPersonWeight() {
return personWeight;
}
public void setPersonWeight(int personWeight) {
this.personWeight = personWeight;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(personName);
dest.writeInt(personAge);
dest.writeInt(personHeight);
dest.writeInt(personWeight);
}
public static final Parcelable.Creator<Person> CREATOR =
new Parcelable.Creator<Person>() {
#Override
public Person createFromParcel(Parcel in) {
return new Person(in);
}
#Override
public Person[] newArray(int size) {
return new Person[size];
}
};
}
Sorry if there are problems, this is my first question and I would very much appreciate what help you can give to a noob C0D3R :P
You shouldn't start variable names with capital letters. Your button MainActivity is very confusing. Better name it something like btMainActivity or something like that.
It think your problem is, that you forget to put an extra to your MainActivity, like you did when starting EditData:
editActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firstPerson.setPersonName(editName.getText().toString());
firstPerson.setPersonAge(Integer.parseInt(editAge.getText().toString()));
firstPerson.setPersonHeight(Integer.parseInt(editHeight.getText().toString()));
firstPerson.setPersonWeight(Integer.parseInt(editWeight.getText().toString()));
Intent editIntent = new Intent(MainActivity.this, EditData.class);
editIntent.putExtra("First_Person_Data", firstPerson);
MainActivity.this.startActivity(editIntent);
}
});
MainActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent EditActivity = new Intent(EditData.this, MainActivity.class);
// put your extra here
EditData.this.startActivity(EditActivity);
}
});
For what you want, you could also use startActivityForResult. Take a look at it! You should also check out AndroidAnnotations. It can safe you a lot of code and time. I can't imagine making an Android app without it anymore.
I'm building an app that displays a date picker and a time picker on the click of two seperate buttons. I first added in the time picker and it was all working fine, I then proceeded to add the date picker which also works fine. The problem here being that when I added in the date picker, it casused the time picker to stop working. I know they both work and i'm 90% sure it is because of the structure of my code but being that i'm completely new to android and java development I can't work out where i'm going wrong. Any help would be appreciated.
Thanks
Code below:
package com.cam.datetime;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
public class SettingsScreen extends Activity {
private TextView tvDisplayTime;
private TimePicker timePicker1;
private Button btnChangeTime;
private int hour;
private int minute;
static final int TIME_DIALOG_ID = 999;
Button change_date_but;
TextView display_txt;
public static final int Date_dialog_id = 1;
// date
private int mYear;
private int mMonth;
private int mDay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen_settings);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setCurrentTimeOnView();
addListenerOnButton();
final EditText inputTxt1 = (EditText) findViewById(R.id.conPhoneNum);
Button saveBtn1 = (Button) findViewById(R.id.btnSave1);
change_date_but = (Button) findViewById(R.id.change_button_id);
display_txt = (TextView) findViewById(R.id.display_id);
change_date_but = (Button) findViewById(R.id.change_button_id);
change_date_but.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
DatePickerDialog DPD = new DatePickerDialog(
SettingsScreen.this, mDateSetListener, mYear, mMonth, mDay);
DPD.show();
}
final Calendar c = Calendar.getInstance();{
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);}
void updateDisplay1() {
}
});
saveBtn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String phoneNum1 = inputTxt1.getText().toString();
savenum1(phoneNum1);
//Intent passIntent = new Intent();
//passIntent.putExtra("phoneNum", phoneNum1);
}
});
Button homeButton = (Button) findViewById(R.id.btnHome);
homeButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View view) {
startHome();
}
});
Button retTimeBtn = (Button) findViewById(R.id.btnRetTime);
retTimeBtn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View view) {
//returnTime();
}
});
}
//display current time
public void setCurrentTimeOnView() {
tvDisplayTime = (TextView) findViewById(R.id.tvTime);
timePicker1 = (TimePicker) findViewById(R.id.timePicker1);
final Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
minute = c.get(Calendar.MINUTE);
// set current time into textview
tvDisplayTime.setText(
new StringBuilder().append(pad(hour))
.append(":").append(pad(minute)));
// set current time into timepicker
timePicker1.setCurrentHour(hour);
timePicker1.setCurrentMinute(minute);
}
private Object pad(int minute2) {
// TODO Auto-generated method stub
return null;
}
public void addListenerOnButton() {
btnChangeTime = (Button) findViewById(R.id.btnChangeTime);
btnChangeTime.setOnClickListener(new OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
showDialog(TIME_DIALOG_ID);
}
});
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case TIME_DIALOG_ID:
OnTimeSetListener timePickerListener = null;
// set time picker as current time
return new TimePickerDialog(this,
timePickerListener, hour, minute,false);
}
return null;
}
#Override
#Deprecated
protected void onPrepareDialog(int id, Dialog dialog) {
// TODO Auto-generated method stub
super.onPrepareDialog(id, dialog);
((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay);
}
private DatePickerDialog.OnDateSetListener mDateSetListener = new
DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
updateDisplay();
}
};
private void updateDisplay() {
// TODO Auto-generated method stub
display_txt.setText(new StringBuilder()
// Month is 0 based so add 1
.append(mMonth + 1).append("-").append(mDay).append("-")
.append(mYear));
}
public void startHome() {
Intent launchHome = new Intent();
launchHome.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
launchHome.setClassName(this,"com.cam.datetime.MainActivity");
startActivity(launchHome);
}
public void savenum1(String phoneNum1) {
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage("Saved " + phoneNum1);
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//dismiss the dialog
}
});
dlgAlert.create().show();
}
public void returnTime(){
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("", null, "#TU?", null, null);
}
}
Give this a try:
import java.util.Calendar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
public class SettingsScreen extends Activity {
private TextView tvDisplayTime;
private TimePicker timePicker1;
private Button btnChangeTime;
private int hour;
private int minute;
static final int TIME_DIALOG_ID = 999;
Button change_date_but;
TextView display_txt;
public static final int Date_dialog_id = 1;
// date
private int mYear;
private int mMonth;
private int mDay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen_settings);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
final EditText inputTxt1 = (EditText) findViewById(R.id.conPhoneNum);
Button saveBtn1 = (Button) findViewById(R.id.btnSave1);
setCurrentTimeOnView();
//addListenerOnButton();
change_date_but = (Button) findViewById(R.id.change_button_id);
display_txt = (TextView) findViewById(R.id.display_id);
change_date_but = (Button) findViewById(R.id.change_button_id);
Button retTimeBtn = (Button) findViewById(R.id.btnRetTime);
Button homeButton = (Button) findViewById(R.id.btnHome);
btnChangeTime = (Button) findViewById(R.id.btnChangeTime);
change_date_but.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
OnDateSetListener mDateSetListener = null;
DatePickerDialog DPD = new DatePickerDialog(
SettingsScreen.this, mDateSetListener, mYear, mMonth, mDay);
DPD.show();
}
final Calendar c = Calendar.getInstance();{
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);}
/*void updateDisplay1() {
}*/
});
saveBtn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String phoneNum1 = inputTxt1.getText().toString();
savenum1(phoneNum1);
//Intent passIntent = new Intent();
//passIntent.putExtra("phoneNum", phoneNum1);
}
});
homeButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View view) {
startHome();
}
});
retTimeBtn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View view) {
//returnTime();
}
});
btnChangeTime.setOnClickListener(new OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
showDialog(TIME_DIALOG_ID);
}
});
}
//display current time
public void setCurrentTimeOnView() {
tvDisplayTime = (TextView) findViewById(R.id.tvTime);
timePicker1 = (TimePicker) findViewById(R.id.timePicker1);
final Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
minute = c.get(Calendar.MINUTE);
// set current time into textview
tvDisplayTime.setText(
new StringBuilder().append(pad(hour))
.append(":").append(pad(minute)));
// set current time into timepicker
timePicker1.setCurrentHour(hour);
timePicker1.setCurrentMinute(minute);
}
private Object pad(int minute2) {
// TODO Auto-generated method stub
return null;
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case TIME_DIALOG_ID:
OnTimeSetListener timePickerListener = null;
// set time picker as current time
return new TimePickerDialog(this,
timePickerListener, hour, minute,false);
}
return null;
}
/*
#Override
#Deprecated
protected void onPrepareDialog(int id, Dialog dialog) {
// TODO Auto-generated method stub
super.onPrepareDialog(id, dialog);
((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay);
}
private DatePickerDialog.OnDateSetListener mDateSetListener = new
DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
updateDisplay();
}
};
private void updateDisplay() {
// TODO Auto-generated method stub
display_txt.setText(new StringBuilder()
// Month is 0 based so add 1
.append(mMonth + 1).append("-").append(mDay).append("-")
.append(mYear));
}
*/
public void startHome() {
Intent launchHome = new Intent();
launchHome.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
launchHome.setClassName(this,"com.becatech.gsmzonecontroller.MainActivity");
startActivity(launchHome);
}
public void savenum1(String phoneNum1) {
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage("Saved " + phoneNum1);
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//dismiss the dialog
}
});
dlgAlert.create().show();
}
public void returnTime(){
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("", null, "#TU?", null, null);
}
}