Completing UI Activity assignment [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have a UI Lab for Android Programming that I'm trying to complete. I think I'm close, yet so far away. I have four activities that I'm working with but only three of them needed worked on. Here is what I have. I need help with what I'm missing.
Here's the first Activity which is AddToDoActivity
package course.labs.todomanager;
import java.util.Calendar;
import java.util.Date;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.TimePicker;
import course.labs.todomanager.ToDoItem.Priority;
import course.labs.todomanager.ToDoItem.Status;
public class AddToDoActivity extends Activity {
// 7 days in milliseconds - 7 * 24 * 60 * 60 * 1000
private static final int SEVEN_DAYS = 604800000;
private static final String TAG = "Lab-UserInterface";
private static String timeString;
private static String dateString;
private static TextView dateView;
private static TextView timeView;
private Date mDate;
private RadioGroup mPriorityRadioGroup;
private RadioGroup mStatusRadioGroup;
private EditText mTitleText;
private RadioButton mDefaultStatusButton;
private RadioButton mDefaultPriorityButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_todo);
mTitleText = (EditText) findViewById(R.id.title);
mDefaultStatusButton = (RadioButton) findViewById(R.id.statusNotDone);
mDefaultPriorityButton = (RadioButton) findViewById(R.id.medPriority);
mPriorityRadioGroup = (RadioGroup) findViewById(R.id.priorityGroup);
mStatusRadioGroup = (RadioGroup) findViewById(R.id.statusGroup);
dateView = (TextView) findViewById(R.id.date);
timeView = (TextView) findViewById(R.id.time);
// Set the default date and time
setDefaultDateTime();
// OnClickListener for the Date button, calls showDatePickerDialog() to show
// the Date dialog
final Button datePickerButton = (Button) findViewById(R.id.date_picker_button);
datePickerButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showDatePickerDialog();
}
});
// OnClickListener for the Time button, calls showTimePickerDialog() to show
// the Time Dialog
final Button timePickerButton = (Button) findViewById(R.id.time_picker_button);
timePickerButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showTimePickerDialog();
}
});
// OnClickListener for the Cancel Button,
final Button cancelButton = (Button) findViewById(R.id.cancelButton);
cancelButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
log("Entered cancelButton.OnClickListener.onClick()");
//TODO - Implement onClick().
Intent intent = new Intent setResult;
finish();
}
});
//OnClickListener for the Reset Button
final Button resetButton = (Button) findViewById(R.id.resetButton);
resetButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
log("Entered resetButton.OnClickListener.onClick()");
//TODO - Reset data fields to default values
setDefaultDateTime();
mTitleText.setText("");
mDefaultStatusButton.setChecked(true);
mDefaultPriorityButton.setChecked(true);
}
});
// OnClickListener for the Submit Button
// Implement onClick().
final Button submitButton = (Button) findViewById(R.id.submitButton);
submitButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
log("Entered submitButton.OnClickListener.onClick()");
// Gather ToDoItem data
//TODO - Get Priority
Priority priority = getPriority();
//TODO - Get Status
Status status = getStatus();
//TODO - Title
String titleString = mTitleText.getText().toString();
// Date
String fullDate = dateString + " " + timeString;
// Package ToDoItem data into an Intent
Intent data = new Intent();
ToDoItem.packageIntent(data, titleString, priority, status, fullDate);
//TODO - return data Intent and finish
setResult(Activity.RESULT_OK, data);
finish();
}
});
}
// Do not modify below here
// Use this method to set the default date and time
private void setDefaultDateTime() {
// Default is current time + 7 days
mDate = new Date();
mDate = new Date(mDate.getTime() + SEVEN_DAYS);
Calendar c = Calendar.getInstance();
c.setTime(mDate);
setDateString(c.get(Calendar.YEAR), c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH));
dateView.setText(dateString);
setTimeString(c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE),
c.get(Calendar.MILLISECOND));
timeView.setText(timeString);
}
private static void setDateString(int year, int monthOfYear, int dayOfMonth) {
// Increment monthOfYear for Calendar/Date -> Time Format setting
monthOfYear++;
String mon = "" + monthOfYear;
String day = "" + dayOfMonth;
if (monthOfYear < 10)
mon = "0" + monthOfYear;
if (dayOfMonth < 10)
day = "0" + dayOfMonth;
dateString = year + "-" + mon + "-" + day;
}
private static void setTimeString(int hourOfDay, int minute, int mili) {
String hour = "" + hourOfDay;
String min = "" + minute;
if (hourOfDay < 10)
hour = "0" + hourOfDay;
if (minute < 10)
min = "0" + minute;
timeString = hour + ":" + min + ":00";
}
private Priority getPriority() {
switch (mPriorityRadioGroup.getCheckedRadioButtonId()) {
case R.id.lowPriority: {
return Priority.LOW;
}
case R.id.highPriority: {
return Priority.HIGH;
}
default: {
return Priority.MED;
}
}
}
private Status getStatus() {
switch (mStatusRadioGroup.getCheckedRadioButtonId()) {
case R.id.statusDone: {
return Status.DONE;
}
default: {
return Status.NOTDONE;
}
}
}
// DialogFragment used to pick a ToDoItem deadline date
public static class DatePickerFragment extends DialogFragment implements
DatePickerDialog.OnDateSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
setDateString(year, monthOfYear, dayOfMonth);
dateView.setText(dateString);
}
}
// DialogFragment used to pick a ToDoItem deadline time
public static class TimePickerFragment extends DialogFragment implements
TimePickerDialog.OnTimeSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return
return new TimePickerDialog(getActivity(), this, hour, minute,
true);
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
setTimeString(hourOfDay, minute, 0);
timeView.setText(timeString);
}
}
private void showDatePickerDialog() {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");
}
private void showTimePickerDialog() {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "timePicker");
}
private void log(String msg) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i(TAG, msg);
}
}
Here's the second activity which is ToDoItem
package course.labs.todomanager;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.content.Intent;
// Do not modify
public class ToDoItem {
public static final String ITEM_SEP = System.getProperty("line.separator");
public enum Priority {
LOW, MED, HIGH
};
public enum Status {
NOTDONE, DONE
};
public final static String TITLE = "title";
public final static String PRIORITY = "priority";
public final static String STATUS = "status";
public final static String DATE = "date";
public final static String FILENAME = "filename";
public final static SimpleDateFormat FORMAT = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss", Locale.US);
private String mTitle = new String();
private Priority mPriority = Priority.LOW;
private Status mStatus = Status.NOTDONE;
private Date mDate = new Date();
ToDoItem(String title, Priority priority, Status status, Date date) {
this.mTitle = title;
this.mPriority = priority;
this.mStatus = status;
this.mDate = date;
}
// Create a new ToDoItem from data packaged in an Intent
ToDoItem(Intent intent) {
mTitle = intent.getStringExtra(ToDoItem.TITLE);
mPriority = Priority.valueOf(intent.getStringExtra(ToDoItem.PRIORITY));
mStatus = Status.valueOf(intent.getStringExtra(ToDoItem.STATUS));
try {
mDate = ToDoItem.FORMAT.parse(intent.getStringExtra(ToDoItem.DATE));
} catch (ParseException e) {
mDate = new Date();
}
}
public String getTitle() {
return mTitle;
}
public void setTitle(String title) {
mTitle = title;
}
public Priority getPriority() {
return mPriority;
}
public void setPriority(Priority priority) {
mPriority = priority;
}
public Status getStatus() {
return mStatus;
}
public void setStatus(Status status) {
mStatus = status;
}
public Date getDate() {
return mDate;
}
public void setDate(Date date) {
mDate = date;
}
// Take a set of String data values and
// package them for transport in an Intent
public static void packageIntent(Intent intent, String title,
Priority priority, Status status, String date) {
intent.putExtra(ToDoItem.TITLE, title);
intent.putExtra(ToDoItem.PRIORITY, priority.toString());
intent.putExtra(ToDoItem.STATUS, status.toString());
intent.putExtra(ToDoItem.DATE, date);
}
public String toString() {
return mTitle + ITEM_SEP + mPriority + ITEM_SEP + mStatus + ITEM_SEP
+ FORMAT.format(mDate);
}
public String toLog() {
return "Title:" + mTitle + ITEM_SEP + "Priority:" + mPriority
+ ITEM_SEP + "Status:" + mStatus + ITEM_SEP + "Date:"
+ FORMAT.format(mDate);
}
}
Here's the third activity which is ToDoListAdapter
package course.labs.todomanager;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import course.labs.todomanager.ToDoItem.Status;
public class ToDoListAdapter extends BaseAdapter {
// List of ToDoItems
private final List<ToDoItem> mItems = new ArrayList<ToDoItem>();
private final Context mContext;
private static final String TAG = "Lab-UserInterface";
public ToDoListAdapter(Context context) {
mContext = context;
}
// Add a ToDoItem to the adapter
// Notify observers that the data set has changed
public void add(ToDoItem item) {
mItems.add(item);
notifyDataSetChanged();
}
// Clears the list adapter of all items.
public void clear(){
mItems.clear();
notifyDataSetChanged();
}
// Returns the number of ToDoItems
#Override
public int getCount() {
return mItems.size();
}
// Retrieve the number of ToDoItems
#Override
public Object getItem(int pos) {
return mItems.get(pos);
}
// Get the ID for the ToDoItem
// In this case it's just the position
#Override
public long getItemId(int pos) {
return pos;
}
//Create a View to display the ToDoItem
// at specified position in mItems
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//TODO - Get the current ToDoItem
final ToDoItem toDoItem = getItemPos();
//TODO - Inflate the View for this ToDoItem
// from todo_item.xml.
LayoutInflater = itemLayout;
RelativeLayout itemLayout = m.context.getSystemService(R.layout.todo_item);
//TODO - Fill in specific ToDoItem data
// Remember that the data that goes in this View
// corresponds to the user interface elements defined
// in the layout file
//TODO - Display Title in TextView
final TextView titleView = ItemLayout.findViewById;
setTextView;
//TODO - Set up Status CheckBox
final CheckBox statusView = ItemLayout.findViewById(R.id.statusCheckBox);
statusView.setChecked(checked) statusDone;
statusView.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
log("Entered onCheckedChanged()");
//TODO - Set up and implement an OnCheckedChangeListener, which
// is called when the user toggles the status checkbox
if isChecked ToDoItem.setStatus status.Done(true);
else
}
});
//TODO - Display Priority in a TextView
final TextView priorityView = findViewByID(R.id.PriorityView);
PriorityView.setToString();
//TODO - Display Time and Date.
// Hint - use ToDoItem.FORMAT.format(toDoItem.getDate()) to get date and time String
final TextView dateView = itemLayout.findViewById(R.id.dateView);
dateView.setText(ToDoItem.FORMAT);
// Return the View you just created
return itemLayout;
}
private void log(String msg) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i(TAG, msg);
}
}
And here is the fourth activity which is ToDoManagerActivity
package course.labs.todomanager;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.text.ParseException;
import java.util.Date;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import course.labs.todomanager.ToDoItem.Priority;
import course.labs.todomanager.ToDoItem.Status;
public class ToDoManagerActivity extends ListActivity {
// Add a ToDoItem Request Code
private static final int ADD_TODO_ITEM_REQUEST = 0;
private static final String FILE_NAME = "TodoManagerActivityData.txt";
private static final String TAG = "Lab-UserInterface";
// IDs for menu items
private static final int MENU_DELETE = Menu.FIRST;
private static final int MENU_DUMP = Menu.FIRST + 1;
ToDoListAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create a new TodoListAdapter for this ListActivity's ListView
mAdapter = new ToDoListAdapter(getApplicationContext());
// Put divider between ToDoItems and FooterView
getListView().setFooterDividersEnabled(true);
//TODO - Inflate footerView for footer_view.xml file
TextView footerView = TextView().getLayoutInflater()
.inflate(R.layout.footer_view, null);
//TODO - Add footerView to ListView
getListView fv = (ListView)findViewById(R.layout.footer_view);
footerView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
log("Entered footerView.OnClickListener.onClick()");
//TODO - Attach Listener to FooterView. Implement onClick().
Intent intent = new Intent(getBaseContext(), AddToDoActivity.class);
startActivityForResult(intent, ADD_TODO_ITEM_REQUEST);
}
});
//TODO - Attach the adapter to this ListActivity's ListView
getListView.footer_view.setAdapter(mAdapter, fv);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
log("Entered onActivityResult()");
// TODO - Check result code and request code.
// If user submitted a new ToDoItem
// Create a new ToDoItem from the data Intent
// and then add it to the adapter
if requestCode == ADD_TODO_ITEM_REQUEST {
also if resultCode != RESULT_OK(true);
new mAdapter++;
}
}
// Do not modify below here
#Override
public void onResume() {
super.onResume();
// Load saved ToDoItems, if necessary
if (mAdapter.getCount() == 0)
loadItems();
}
#Override
protected void onPause() {
super.onPause();
// Save ToDoItems
saveItems();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(Menu.NONE, MENU_DELETE, Menu.NONE, "Delete all");
menu.add(Menu.NONE, MENU_DUMP, Menu.NONE, "Dump to log");
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_DELETE:
mAdapter.clear();
return true;
case MENU_DUMP:
dump();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void dump() {
for (int i = 0; i < mAdapter.getCount(); i++) {
String data = ((ToDoItem) mAdapter.getItem(i)).toLog();
log("Item " + i + ": " + data.replace(ToDoItem.ITEM_SEP, ","));
}
}
// Load stored ToDoItems
private void loadItems() {
BufferedReader reader = null;
try {
FileInputStream fis = openFileInput(FILE_NAME);
reader = new BufferedReader(new InputStreamReader(fis));
String title = null;
String priority = null;
String status = null;
Date date = null;
while (null != (title = reader.readLine())) {
priority = reader.readLine();
status = reader.readLine();
date = ToDoItem.FORMAT.parse(reader.readLine());
mAdapter.add(new ToDoItem(title, Priority.valueOf(priority),
Status.valueOf(status), date));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} finally {
if (null != reader) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// Save ToDoItems to file
private void saveItems() {
PrintWriter writer = null;
try {
FileOutputStream fos = openFileOutput(FILE_NAME, MODE_PRIVATE);
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
fos)));
for (int idx = 0; idx < mAdapter.getCount(); idx++) {
writer.println(mAdapter.getItem(idx));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != writer) {
writer.close();
}
}
}
private void log(String msg) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i(TAG, msg);
}
}
Any thought on how to improve the cancelButton code in the AddToDoAcitivity?
final Button cancelButton = (Button) findViewById(R.id.cancelButton);
cancelButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
log("Entered cancelButton.OnClickListener.onClick()");
//TODO - Implement onClick().
Intent intent = new Intent setResult;
finish();
}
});

change your AddToDoActivity code like this
public class AddToDoActivity extends Activity {
// 7 days in milliseconds - 7 * 24 * 60 * 60 * 1000
private static final int SEVEN_DAYS = 604800000;
private static final String TAG = "Lab-UserInterface";
private static String timeString;
private static String dateString;
private static TextView dateView;
private static TextView timeView;
private Date mDate;
private RadioGroup mPriorityRadioGroup;
private RadioGroup mStatusRadioGroup;
private EditText mTitleText;
private RadioButton mDefaultStatusButton;
private RadioButton mDefaultPriorityButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_todo);
mTitleText = (EditText) findViewById(R.id.title);
mDefaultStatusButton = (RadioButton) findViewById(R.id.statusNotDone);
mDefaultPriorityButton = (RadioButton) findViewById(R.id.medPriority);
mPriorityRadioGroup = (RadioGroup) findViewById(R.id.priorityGroup);
mStatusRadioGroup = (RadioGroup) findViewById(R.id.statusGroup);
dateView = (TextView) findViewById(R.id.date);
timeView = (TextView) findViewById(R.id.time);
// Set the default date and time
setDefaultDateTime();
// OnClickListener for the Date button, calls showDatePickerDialog() to show
// the Date dialog
final Button datePickerButton = (Button) findViewById(R.id.date_picker_button);
datePickerButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showDatePickerDialog();
}
});
// OnClickListener for the Time button, calls showTimePickerDialog() to show
// the Time Dialog
final Button timePickerButton = (Button) findViewById(R.id.time_picker_button);
timePickerButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showTimePickerDialog();
}
});
// OnClickListener for the Cancel Button,
final Button cancelButton = (Button) findViewById(R.id.cancelButton);
cancelButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
log("Entered cancelButton.OnClickListener.onClick()");
finish();
}
});
//OnClickListener for the Reset Button
final Button resetButton = (Button) findViewById(R.id.resetButton);
resetButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
log("Entered resetButton.OnClickListener.onClick()");
setDefaultDateTime();
mTitleText.setText("");
mDefaultStatusButton.setChecked(true);
mDefaultPriorityButton.setChecked(true);
}
});
// OnClickListener for the Submit Button
// Implement onClick().
final Button submitButton = (Button) findViewById(R.id.submitButton);
submitButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
log("Entered submitButton.OnClickListener.onClick()");
// Gather ToDoItem data
Priority priority = getPriority();
Status status = getStatus();
String titleString = mTitleText.getText().toString();
// Date
String fullDate = dateString + " " + timeString;
// Package ToDoItem data into an Intent
Intent data = new Intent();
ToDoItem.packageIntent(data, titleString, priority, status, fullDate);
setResult(Activity.RESULT_OK, data);
finish();
}
});
}
// Do not modify below here
// Use this method to set the default date and time
private void setDefaultDateTime() {
// Default is current time + 7 days
mDate = new Date();
mDate = new Date(mDate.getTime() + SEVEN_DAYS);
Calendar c = Calendar.getInstance();
c.setTime(mDate);
setDateString(c.get(Calendar.DAY_OF_MONTH), c.get(Calendar.MONTH),
c.get(Calendar.YEAR));
dateView.setText(dateString);
setTimeString(c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE),
c.get(Calendar.MILLISECOND));
timeView.setText(timeString);
}
private static void setDateString(int dayOfMonth, int monthOfYear, int year) {
// Increment monthOfYear for Calendar/Date -> Time Format setting
monthOfYear++;
String mon = "" + monthOfYear;
String day = "" + dayOfMonth;
if (monthOfYear < 10)
mon = "0" + monthOfYear;
if (dayOfMonth < 10)
day = "0" + dayOfMonth;
dateString = year + "-" + mon + "-" + day;
}
private static void setTimeString(int hourOfDay, int minute, int mili) {
String hour = "" + hourOfDay;
String min = "" + minute;
if (hourOfDay < 10)
hour = "0" + hourOfDay;
if (minute < 10)
min = "0" + minute;
timeString = hour + ":" + min + ":00";
}
private Priority getPriority() {
switch (mPriorityRadioGroup.getCheckedRadioButtonId()) {
case R.id.lowPriority: {
return Priority.LOW;
}
case R.id.highPriority: {
return Priority.HIGH;
}
default: {
return Priority.MED;
}
}
}
private Status getStatus() {
switch (mStatusRadioGroup.getCheckedRadioButtonId()) {
case R.id.statusDone: {
return Status.DONE;
}
default: {
return Status.NOTDONE;
}
}
}
// DialogFragment used to pick a ToDoItem deadline date
public static class DatePickerFragment extends DialogFragment implements
DatePickerDialog.OnDateSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int day = c.get(Calendar.DAY_OF_MONTH);
int month = c.get(Calendar.MONTH);
int year = c.get(Calendar.YEAR);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
#Override
public void onDateSet(DatePicker view, int dayOfMonth, int monthOfYear,
int year) {
setDateString(dayOfMonth, monthOfYear, year);
dateView.setText(dateString);
}
}
// DialogFragment used to pick a ToDoItem deadline time
public static class TimePickerFragment extends DialogFragment implements
TimePickerDialog.OnTimeSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return
return new TimePickerDialog(getActivity(), this, hour, minute,
true);
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
setTimeString(hourOfDay, minute, 0);
timeView.setText(timeString);
}
}
private void showDatePickerDialog() {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");
}
private void showTimePickerDialog() {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "timePicker");
}
private void log(String msg) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i(TAG, msg);
}
}

Related

Everything works until I use updateDisplay method, causing the app to crash

Everything appears correctly on the screen until I fill in updateDisplay() method with code to update my textViews using setText/get.
The app does not crash prior to entering the setText/get code to update from the DarkSky API, but once entered the app crashes and tells me to try again.
I believe everything is entered correctly, but for some reason the app won't take the information. ALSO, I am using the recent version of OkHTTP in cradle, so the issue doesn't lie there. (Permissions are also used)
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
public static final String TAG = MainActivity.class.getSimpleName();
private CurrentWeather mCurrentWeather;
#BindView(R.id.timeLabel) TextView mTimeLabel;
#BindView(R.id.tempLabel) TextView mTempLabel;
#BindView(R.id.humidityValue) TextView mHumidityValue;
#BindView(R.id.precipValue) TextView mPrecipValue;
#BindView(R.id.summaryLabel) TextView mSummaryLabel;
#BindView(R.id.iconImageView) ImageView mIconImageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
String apiKey = "MY KEY";
double latitude = 37.8267;
double longitude = -122.4233;
String forecastURL = ("https://api.darksky.net/forecast/" + apiKey +
"/" + latitude + "," + longitude);
if (isNetworkAvailable()) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(forecastURL)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
}
#Override
public void onResponse(Call call, Response response) throws IOException {
try {
String jsonData = response.body().string();
Log.v(TAG, jsonData);
if (response.isSuccessful()) {
mCurrentWeather = getCurrentDetails(jsonData);
runOnUiThread(new Runnable() {
#Override
public void run() {
updateDisplay();
}
});
} else {
alertUserAboutError();
}
}
catch (IOException | JSONException e) {
Log.e(TAG, "Exception caught: ", e);
}
}
});
}
else {
Toast.makeText(this, R.string.network_unavailable_message,
Toast.LENGTH_LONG).show(); // CHALLENGE: Turn into dialog
}
Log.d(TAG, "Main UI code is running!");
}
private void updateDisplay() {
mSummaryLabel.setText(mCurrentWeather.getSummary());
mTempLabel.setText(mCurrentWeather.getTemperature() + "");
}
private CurrentWeather getCurrentDetails(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
Log.i(TAG, "From JSON: " + timezone);
JSONObject currently = forecast.getJSONObject("currently");
CurrentWeather currentWeather = new CurrentWeather();
currentWeather.setHumidity(currently.getDouble("humidity"));
currentWeather.setTime(currently.getLong("time"));
currentWeather.setIcon(currently.getString("icon"));
currentWeather.setPrecipChance(currently.getDouble("precipProbability"));
currentWeather.setSummary(currently.getString("summary"));
currentWeather.setTemperature(currently.getInt("temperature"));
currentWeather.setTimeZone(timezone);
Log.d(TAG, currentWeather.getFormattedTime());
return currentWeather;
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
private void alertUserAboutError() {
AlertDialogFragment dialog = new AlertDialogFragment();
dialog.show(getFragmentManager(), "error_dialog");
}
}
package tricksterantics.com.catsndogs;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class CurrentWeather {
private String mIcon;
private long mTime;
private double mTemperature;
private double mHumidity;
private double mPrecipChance;
private String mSummary;
public String getTimeZone() {
return mTimeZone;
}
public void setTimeZone(String timeZone) {
mTimeZone = timeZone;
}
private String mTimeZone;
public String getIcon() {
return mIcon;
}
public void setIcon(String icon) {
mIcon = icon;
}
public int getIconId() {
// clear-day, clear-night, rain, snow, sleet, wind, fog, cloudy, partly-cloudy-day, or partly-cloudy-night.
int iconId = R.drawable.clear_day;
if (mIcon.equals("clear-day")) {
iconId = R.drawable.clear_day;
}
else if (mIcon.equals("clear-night")) {
iconId = R.drawable.clear_night;
}
else if (mIcon.equals("rain")) {
iconId = R.drawable.rain;
}
else if (mIcon.equals("snow")) {
iconId = R.drawable.snow;
}
else if (mIcon.equals("sleet")) {
iconId = R.drawable.sleet;
}
else if (mIcon.equals("wind")) {
iconId = R.drawable.wind;
}
else if (mIcon.equals("fog")) {
iconId = R.drawable.fog;
}
else if (mIcon.equals("cloudy")) {
iconId = R.drawable.cloudy;
}
else if (mIcon.equals("partly-cloudy-day")) {
iconId = R.drawable.partly_cloudy;
}
else if (mIcon.equals("partly-cloudy-night")) {
iconId = R.drawable.cloudy_night;
}
return iconId;
}
public long getTime() {
return mTime;
}
public void setTime(long time) {
mTime = time;
}
public String getFormattedTime () {
SimpleDateFormat formatter = new SimpleDateFormat("h:mm a");
formatter.setTimeZone(TimeZone.getTimeZone(getTimeZone()));
Date dateTime = new Date(getTime() * 1000);
String timeString = formatter.format(dateTime);
return timeString;
}
public double getTemperature() {
return (int) Math.round(mTemperature);
}
public void setTemperature(double temperature) {
mTemperature = temperature;
}
public double getHumidity() {
return mHumidity;
}
public void setHumidity(double humidity) {
mHumidity = humidity;
}
public int getPrecipChance() {
double precipPercentage = mPrecipChance * 100;
return (int) Math.round(precipPercentage);
}
public void setPrecipChance(double precipChance) {
mPrecipChance = precipChance;
}
public String getSummary() {
return mSummary;
}
public void setSummary(String summary) {
mSummary = summary;
}
}
Edit:
Added an image of the stack trace
Stack trace
Got rid of the Butterknife format I was using (BindVIew) and opted for this, everything now works and is retrieving updated information from the API:
public class MainActivity extends AppCompatActivity {
public static final String TAG = MainActivity.class.getSimpleName();
private CurrentWeather mCurrentWeather;
private TextView mTimeLabel;
private TextView mTempLabel;
private TextView mHumidityValue;
private TextView mPrecipValue;
private TextView mSummaryLabel;
private ImageView mIconImageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTimeLabel = (TextView) findViewById(R.id.timeLabel);
mTempLabel = (TextView) findViewById(R.id.tempLabel);
mHumidityValue = (TextView) findViewById(R.id.humidityValue);
mPrecipValue = (TextView) findViewById(R.id.precipValue);
mSummaryLabel = (TextView) findViewById(R.id.summaryLabel);

Android TimePickerDialog. app crashes when setting time more than current time

My app getting crash when I try to set the time more than the current time.
Please solve my problem.
The current time is working fine but the app is crashing when I select time more than current time.
Thanks
JavaFile:
package com.example.akshay.eventmanager;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.hardware.input.InputManager;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.widget.Toast;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlacePicker;
import com.google.android.gms.maps.model.LatLng;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;
import android.app.DatePickerDialog.OnDateSetListener;
/**
* Created by Akshay on 7/12/2015.
*/
public class Create extends Activity implements View.OnClickListener {
Button select, create;
EditText title, desc, time;
TextView venueInfo;
PlacePicker.IntentBuilder intentBuilder;
private static final int PLACE_PICKER_REQUEST = 1;
public LatLng gotLatLng;
String placeName;
String plName;
String Addr;
Double gotLat, gotLong;
String LAT, LONG;
DataBaseHelper myDB;
public static final String LOG_TAG = "Create";
String GotTime = " ";
String GotDate = " ";
DatePickerDialog datePicker;
TimePickerDialog myTimePicker;
SimpleDateFormat dateFormatter;
SimpleDateFormat TimeFormatter;
static boolean flag = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create);
dateFormatter = new SimpleDateFormat("EEEE dd" ,Locale.US);
showDate();
showTime();
casting();
}
public void casting() {
select = (Button) findViewById(R.id.bSelect);
create = (Button) findViewById(R.id.bCreate);
title = (EditText) findViewById(R.id.etTitle);
desc = (EditText) findViewById(R.id.etDescription);
time = (EditText) findViewById(R.id.etTime);
venueInfo = (TextView) findViewById(R.id.tVVenue);
time.setInputType(InputType.TYPE_NULL);
select.setOnClickListener(this);
create.setOnClickListener(this);
time.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.bSelect:
try {
intentBuilder = new PlacePicker.IntentBuilder();
Intent intent = intentBuilder.build(Create.this);
startActivityForResult(intent, PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
Toast.makeText(Create.this, "Google Play Services is not available.",
Toast.LENGTH_LONG)
.show();
}
break;
case R.id.bCreate:
String TITLE = title.getText().toString();
String DESC = desc.getText().toString();
String eventTime = time.getText().toString();
String PLACE = venueInfo.getText().toString();
myDB = new DataBaseHelper(this);
Log.e(LOG_TAG, TITLE);
Log.e(LOG_TAG, DESC);
Log.e(LOG_TAG, PLACE);
Log.e(LOG_TAG, LAT);
Log.e(LOG_TAG, LONG);
Log.e(LOG_TAG, Addr);
Log.e(LOG_TAG, eventTime);
int flag = myDB.InsertValues(TITLE, DESC, PLACE, LAT, LONG, Addr, eventTime);
if (flag == 1) {
Toast.makeText(Create.this, "Sucess", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(Create.this, "Error Adding Records", Toast.LENGTH_LONG).show();
}
break;
case R.id.etTime:
myTimePicker.show();
datePicker.show();
break;
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
Place place = PlacePicker.getPlace(data, this);
gotLatLng = place.getLatLng();
plName = (String) place.getName();
Addr = (String) place.getAddress();
gotLat = gotLatLng.latitude;
gotLong = gotLatLng.longitude;
LAT = String.valueOf(gotLat);
LONG = String.valueOf(gotLong);
placeName = String.format("Place: %s", place.getName());
Toast.makeText(this, placeName, Toast.LENGTH_LONG).show();
venueInfo.setText(plName);
}
}
}
public void showDate() {
Calendar cal = Calendar.getInstance();
datePicker = new DatePickerDialog(this, new OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth ) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
GotDate = dateFormatter.format(newDate.getTime()).toString();
}
}, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_WEEK));
flag =true;
}
public void showTime() {
if(flag == true) {
Calendar calender = Calendar.getInstance();
myTimePicker = new TimePickerDialog(this, new OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Calendar newTime = Calendar.getInstance();
newTime.set(hourOfDay, minute);
GotTime = GotDate + " At " + String.valueOf(hourOfDay) + " :" + String.valueOf(minute + 1);
time.setText(GotTime);
}
}, calender.get((Calendar.HOUR_OF_DAY)), calender.get(Calendar.MINUTE), true);
}
}
}
LogCat:
07-13 16:43:10.468 478-478/com.example.akshay.eventmanager E/Zygote﹕ MountEmulatedStorage()
07-13 16:43:10.468 478-478/com.example.akshay.eventmanager E/Zygote﹕ v2
07-13 16:43:10.468 478-478/com.example.akshay.eventmanager E/SELinux﹕ [DEBUG] get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
07-13 16:43:29.338 478-478/com.example.akshay.eventmanager E/ViewRootImpl﹕ sendUserActionEvent() mView == null
07-13 16:43:31.088 478-478/com.example.akshay.eventmanager E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.akshay.eventmanager, PID: 478
java.lang.ArrayIndexOutOfBoundsException: length=17; index=17
at java.util.Calendar.set(Calendar.java:1122)
at com.example.akshay.eventmanager.Create$2.onTimeSet(Create.java:196)
at android.app.TimePickerDialog.onClick(TimePickerDialog.java:204)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:162)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5972)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Set the time in calendar in showTime() method as follows:
public void showTime() {
if(flag == true) {
Calendar calender = Calendar.getInstance();
myTimePicker = new TimePickerDialog(this, new OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Calendar newTime = Calendar.getInstance();
//newTime.set(hourOfDay, minute); // remove this line
//Add these two line
newTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
newTime.set(Calendar.MINUTE, minute);
GotTime = GotDate + " At " + String.valueOf(hourOfDay) + " :" + String.valueOf(minute + 1);
time.setText(GotTime);
}
}, calender.get((Calendar.HOUR_OF_DAY)), calender.get(Calendar.MINUTE), true);
}
}
EDIT:
To get HourOdDay in am/pm you can do something like this:
String format = "hh:mm a"; // your own format
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
String formated_time = sdf.format(newTime.getTime());
//formated_time would show you time like "hh:mm am/pm".

Android: How to implement an ArrayList with holidays dates

I'm developing application that in one of its activity has the mechanism that calculates workdays between two dates:
package com.example.salary;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Toast;
public class CountingWorkDays extends Activity {
static Calendar start_calendar = Calendar.getInstance();
static Calendar end_calendar = Calendar.getInstance();
EditText et_start;
EditText et_end;
Button count;
Button save_days;
static int workDays = 0;
static int totalDays = 0;
int dni_robocze = 0;
Calendar start_calendar_save = Calendar.getInstance();
Calendar end_calendar_save = Calendar.getInstance();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.przeliczanie_dni_roboczych);
gather_start_date();
gather_end_date();
after_clicking_count();
after_clicking_save();
}
private void update_et(EditText edittext, Calendar myCalendar) { //inserting to EditText object
String myFormat = "dd/MM/yy";
SimpleDateFormat date = new SimpleDateFormat(myFormat, Locale.UK);
edittext.setText(date.format(myCalendar.getTime()));
}
public void gather_start_date() { //getting start date
et_start = (EditText) findViewById(R.id.et_od);
final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
start_calendar.set(Calendar.YEAR, year);
start_calendar.set(Calendar.MONTH, monthOfYear);
start_calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
update_et(et_start, start_calendar);
}
};
et_start.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new DatePickerDialog(PrzeliczanieDniRoboczych.this, date,
start_calendar.get(Calendar.YEAR), start_calendar
.get(Calendar.MONTH), start_calendar
.get(Calendar.DAY_OF_MONTH)).show();
}
});
}
public void gather_end_date() { //getting end date
et_end = (EditText) findViewById(R.id.et_do);
final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
end_calendar.set(Calendar.YEAR, year);
end_calendar.set(Calendar.MONTH, monthOfYear);
end_calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
update_et(et_end, end_calendar);
}
};
et_end.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new DatePickerDialog(PrzeliczanieDniRoboczych.this, date,
end_calendar.get(Calendar.YEAR), end_calendar
.get(Calendar.MONTH), end_calendar
.get(Calendar.DAY_OF_MONTH)).show();
}
});
}
public void after_clicking_count() { //after clicking "Calculate"
work_days = 0;
count = (Button) findViewById(R.id.b_count_workdays);
count.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
work_days = getWorkingDaysBetweenTwoDates();
}
});
}
public int getWorkingDaysBetweenTwoDates() { //getting working days between two dates
workDays = 0;
totalDays = 0;
// Return 0 if start and end are the same
if (et_start.getText().toString().trim().length() == 0
|| et_end.getText().toString().trim().length() == 0
|| et_start.getText().toString().matches("dd/mm/yy")
|| et_end.getText().toString().matches("dd/mm/yy")) {
Toast.makeText(getApplicationContext(), "Choose dates!",
Toast.LENGTH_SHORT).show();
return 0;
} else {
if (start_calendar.getTimeInMillis() > end_calendar
.getTimeInMillis()) {
Toast.makeText(PrzeliczanieDniRoboczych.this,
"Start date has to be before end date",
Toast.LENGTH_SHORT).show();
} else {
for (; start_calendar.getTimeInMillis() <= end_calendar
.getTimeInMillis(); start_calendar.add(
Calendar.DAY_OF_MONTH, 1)) {
totalDays++;
if (start_calendar.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY
&& start_calendar.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
workDays++;
}
}
start_calendar.add(Calendar.DAY_OF_MONTH, -1 * totalDays);
Toast.makeText(PrzeliczanieDniRoboczych.this,
"Workday is this period are: " + workDays,
Toast.LENGTH_SHORT).show();
}
return workDays;
}
}
I would like to add the mechanism that will allow user to insert dates of holidays (this aplication will calculate the salary and holidays means no salary, so it's important).
As I saw here, user SimplyPanda suggested adding an ArrayList<Integer> to do so. However, I wondering how the inserting by user should look like.
Should user know the integer representation of particular dates in Java? - I guess no.
Does anyone have any idea how to implement such functionality?

EROR NullPointerException [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
at this time i need help from u guys, i have this following code, but when i run in eclipse, it's totally eror,(THE ERROR IS SIGN IN THE CODE BELOW)
package com.example.search;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
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 com.example.database.search.DBDataSource;
import com.example.database.search.Sma;
public class EditData extends Activity implements OnClickListener
{
int hour, minute, mYear,mMonth, mDay;
static final int DATE_DIALOG_ID = 1;
private EditText txtDate;
private String[] arrMonth{"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
private DBDataSource dataSource;
private long id;
private String Nama;
private String Alamat;
private Long Latitude;
private Long Longtitude;
private String Tanggal;
private String Email;
private String Website;
private String Facebook;
private String Twtitter;
private EditText edNama_sma, edAlamat_sma, edLatitude, edLongtitude, edTanggal, edEmail, edWebsite, edFacebook, edTwitter;
private TextView txId;
private Button btnSave;
private Button btnCancel;
private Sma sma;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_data);
//inisialisasi variabel
edNama_sma = (EditText) findViewById(R.id.editText_nama);
edAlamat_sma = (EditText) findViewById(R.id.editText_alamat);
edLatitude = (EditText) findViewById(R.id.editText_latitude);
edLongtitude = (EditText) findViewById(R.id.editText_longtitude);
edTanggal = (EditText) findViewById(R.id.editText_Tanggal);
edEmail = (EditText) findViewById(R.id.editText_Email);
edWebsite = (EditText) findViewById(R.id.editText_Website);
edFacebook = (EditText) findViewById(R.id.editText_Facebook);
edTwitter = (EditText) findViewById(R.id.editText_Twitter);
txId = (TextView) findViewById(R.id.text_id_barang);
// get the current date
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
//WHEN I ADD THIS CODE BELOW, then >> ERROR is happend >> java.lang.NullPointerExceptions
//THIS FUNCTION IS USE FOR SHOWING DATETIMEPICKER
txtDate.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
showDialog(DATE_DIALOG_ID);
return true;
}
});
//UNTIL THIS LINE
dataSource = new DBDataSource(this);
dataSource.open();
// ambil data sma dari extras
Bundle bun = this.getIntent().getExtras();
id = bun.getLong("id");
Nama = bun.getString("Nama");
Alamat = bun.getString("Alamat");
Latitude = bun.getLong("Latitude");
Longtitude = bun.getLong("Longtitude");
Tanggal = bun.getString("Tanggal");
Email = bun.getString("Email");
Website = bun.getString("Website");
Facebook = bun.getString("Facebook");
Twtitter = bun.getString("Twitter");
txId.append(String.valueOf(id));
edNama_sma.setText(Nama);
edAlamat_sma.setText(Alamat);
edLatitude.setText(Latitude.toString());
edLongtitude.setText(Longtitude.toString());
edTanggal.setText(Tanggal);
edEmail.setText(Email);
edWebsite.setText(Website);
edFacebook.setText(Facebook);
edTwitter.setText(Twtitter);
//set listener pada tombol
btnSave = (Button) findViewById(R.id.button_save_update);
btnSave.setOnClickListener(this);
btnCancel = (Button) findViewById(R.id.button_cancel_update);
btnCancel.setOnClickListener(this);
}
#Override
protected Dialog onCreateDialog(int id)
{
switch (id)
{
case DATE_DIALOG_ID:
return new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay);
}
return null;
}
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener()
{
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth)
{
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
String sdate = arrMonth[mMonth] + " " + LPad(mDay + "", "0", 2) + ", " + mYear;
txtDate.setText(sdate);
}
};
private static String LPad(String schar, String spad, int len)
{
String sret = schar;
for (int i = sret.length(); i < len; i++)
{
sret = spad + sret;
}
return new String(sret);
}
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
switch(v.getId())
{
// apabila tombol save diklik (update barang)
case R.id.button_save_update :
String ltd = edLatitude.getText().toString();
String lotd = edLongtitude.getText().toString();
Long latitude = Long.parseLong(ltd);
Long longtitude = Long.parseLong(lotd);
sma = new Sma();
sma.setNama(edNama_sma.getText().toString());
sma.setAlamat(edAlamat_sma.getText().toString());
sma.setLatitude(latitude);
sma.setLongitude(longtitude);
sma.setEmail(edEmail.getText().toString());
sma.setTgl_berdiri(edTanggal.getText().toString());
sma.setWebsite(edWebsite.getText().toString());
sma.setFacebook(edFacebook.getText().toString());
sma.setTwitter(edTwitter.getText().toString());
sma.setId(id);
dataSource.updateBarang(sma);
Intent i = new Intent(this, ViewData.class);
startActivity(i);
EditData.this.finish();
dataSource.close();
break;
case R.id.button_cancel_update :
finish();
dataSource.close();
break;
}
}
}
Anyone please help me from this error, i really want to say thank you to all of u who can resolve this code, Thanks :D
You haven't initialized the txtDate EtidText.
txtDate = (EditText) findViewById(R.id.txtDate);// or what ever you add the id for txtDate
Then you will be fine.

A run-time error prevent my to-do application to start

This is what I found in the LogCat:
02-26 05:10:44.943: E/AndroidRuntime(844): FATAL EXCEPTION: main
02-26 05:10:44.943: E/AndroidRuntime(844): java.lang.RuntimeException: Unable to start activity ComponentInfo{course.labs.todomanager/course.labs.todomanager.ToDoManagerActivity}: android.content.res.Resources$NotFoundException: Resource ID #0x7f060013 type #0x12 is not valid
02-26 05:10:44.943: E/AndroidRuntime(844): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
02-26 05:10:44.943: E/AndroidRuntime(844): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
02-26 05:10:44.943: E/AndroidRuntime(844): at android.app.ActivityThread.access$600(ActivityThread.java:141)
02-26 05:10:44.943: E/AndroidRuntime(844): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
02-26 05:10:44.943: E/AndroidRuntime(844): at android.os.Handler.dispatchMessage(Handler.java:99)
02-26 05:10:44.943: E/AndroidRuntime(844): at android.os.Looper.loop(Looper.java:137)
02-26 05:10:44.943: E/AndroidRuntime(844): at android.app.ActivityThread.main(ActivityThread.java:5103)
02-26 05:10:44.943: E/AndroidRuntime(844): at java.lang.reflect.Method.invokeNative(Native Method)
02-26 05:10:44.943: E/AndroidRuntime(844): at java.lang.reflect.Method.invoke(Method.java:525)
02-26 05:10:44.943: E/AndroidRuntime(844): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
02-26 05:10:44.943: E/AndroidRuntime(844): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
02-26 05:10:44.943: E/AndroidRuntime(844): at dalvik.system.NativeStart.main(Native Method)
02-26 05:10:44.943: E/AndroidRuntime(844): Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x7f060013 type #0x12 is not valid
02-26 05:10:44.943: E/AndroidRuntime(844): at android.content.res.Resources.loadXmlResourceParser(Resources.java:2309)
02-26 05:10:44.943: E/AndroidRuntime(844): at android.content.res.Resources.getLayout(Resources.java:934)
02-26 05:10:44.943: E/AndroidRuntime(844): at android.view.LayoutInflater.inflate(LayoutInflater.java:395)
02-26 05:10:44.943: E/AndroidRuntime(844): at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
02-26 05:10:44.943: E/AndroidRuntime(844): at course.labs.todomanager.ToDoManagerActivity.onCreate(ToDoManagerActivity.java:56)
02-26 05:10:44.943: E/AndroidRuntime(844): at android.app.Activity.performCreate(Activity.java:5133)
02-26 05:10:44.943: E/AndroidRuntime(844): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
02-26 05:10:44.943: E/AndroidRuntime(844): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
02-26 05:10:44.943: E/AndroidRuntime(844): ... 11 more
The Applicaion is a to-do app and it has 4 activities as follows:
1- ToDoManagerActivity
package course.labs.todomanager;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.text.ParseException;
import java.util.Date;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ListView;
import android.widget.TextView;
import course.labs.todomanager.ToDoItem.Priority;
import course.labs.todomanager.ToDoItem.Status;
public class ToDoManagerActivity extends ListActivity {
// Add a ToDoItem Request Code
private static final int ADD_TODO_ITEM_REQUEST = 0;
private static final String FILE_NAME = "TodoManagerActivityData.txt";
private static final String TAG = "Lab-UserInterface";
// IDs for menu items
private static final int MENU_DELETE = Menu.FIRST;
private static final int MENU_DUMP = Menu.FIRST + 1;
ToDoListAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create a new TodoListAdapter for this ListActivity's ListView
mAdapter = new ToDoListAdapter(getApplicationContext());
// Put divider between ToDoItems and FooterView
getListView().setFooterDividersEnabled(true);
//TODO - Inflate footerView for footer_view.xml file
TextView footerView = (TextView) findViewById(R.id.footerView);
LayoutInflater li = getLayoutInflater();
li.inflate(R.id.footerView, getListView());
//TODO - Add footerView to ListView
ListView lv = getListView();
lv.addFooterView(footerView);
footerView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
log("Entered footerView.OnClickListener.onClick()");
//TODO - Attach Listener to FooterView. Implement onClick().
Intent intent = new Intent(ToDoManagerActivity.this, AddToDoActivity.class);
startActivityForResult(intent, ADD_TODO_ITEM_REQUEST);
}
});
//TODO - Attach the adapter to this ListActivity's ListView
lv.setAdapter(mAdapter);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
log("Entered onActivityResult()");
// TODO - Check result code and request code.
// If user submitted a new ToDoItem
// Create a new ToDoItem from the data Intent
// and then add it to the adapter
if (requestCode == ADD_TODO_ITEM_REQUEST && resultCode == RESULT_OK)
{
ToDoItem toDoItem = new ToDoItem(data);
mAdapter.add(toDoItem);
}
}
// Do not modify below here
#Override
public void onResume() {
super.onResume();
// Load saved ToDoItems, if necessary
if (mAdapter.getCount() == 0)
loadItems();
}
#Override
protected void onPause() {
super.onPause();
// Save ToDoItems
saveItems();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(Menu.NONE, MENU_DELETE, Menu.NONE, "Delete all");
menu.add(Menu.NONE, MENU_DUMP, Menu.NONE, "Dump to log");
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_DELETE:
mAdapter.clear();
return true;
case MENU_DUMP:
dump();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void dump() {
for (int i = 0; i < mAdapter.getCount(); i++) {
String data = ((ToDoItem) mAdapter.getItem(i)).toLog();
log("Item " + i + ": " + data.replace(ToDoItem.ITEM_SEP, ","));
}
}
// Load stored ToDoItems
private void loadItems() {
BufferedReader reader = null;
try {
FileInputStream fis = openFileInput(FILE_NAME);
reader = new BufferedReader(new InputStreamReader(fis));
String title = null;
String priority = null;
String status = null;
Date date = null;
while (null != (title = reader.readLine())) {
priority = reader.readLine();
status = reader.readLine();
date = ToDoItem.FORMAT.parse(reader.readLine());
mAdapter.add(new ToDoItem(title, Priority.valueOf(priority),
Status.valueOf(status), date));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} finally {
if (null != reader) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// Save ToDoItems to file
private void saveItems() {
PrintWriter writer = null;
try {
FileOutputStream fos = openFileOutput(FILE_NAME, MODE_PRIVATE);
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
fos)));
for (int idx = 0; idx < mAdapter.getCount(); idx++) {
writer.println(mAdapter.getItem(idx));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != writer) {
writer.close();
}
}
}
private void log(String msg) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i(TAG, msg);
}
}
2- ToDoListAdapter:
package course.labs.todomanager;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import course.labs.todomanager.ToDoItem.Status;
public class ToDoListAdapter extends BaseAdapter {
// List of ToDoItems
private final List<ToDoItem> mItems = new ArrayList<ToDoItem>();
private final Context mContext;
private static final String TAG = "Lab-UserInterface";
public ToDoListAdapter(Context context) {
mContext = context;
}
// Add a ToDoItem to the adapter
// Notify observers that the data set has changed
public void add(ToDoItem item) {
mItems.add(item);
notifyDataSetChanged();
}
// Clears the list adapter of all items.
public void clear(){
mItems.clear();
notifyDataSetChanged();
}
// Returns the number of ToDoItems
#Override
public int getCount() {
return mItems.size();
}
// Retrieve the number of ToDoItems
#Override
public Object getItem(int pos) {
return mItems.get(pos);
}
// Get the ID for the ToDoItem
// In this case it's just the position
#Override
public long getItemId(int pos) {
return pos;
}
//Create a View to display the ToDoItem
// at specified position in mItems
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//TODO - Get the current ToDoItem
final ToDoItem toDoItem = (ToDoItem) getItem(position);
//TODO - Inflate the View for this ToDoItem
// from todo_item.xml.
RelativeLayout itemLayout = (RelativeLayout) View.inflate(mContext, R.layout.todo_item, parent);
//TODO - Fill in specific ToDoItem data
// Remember that the data that goes in this View
// corresponds to the user interface elements defined
// in the layout file
//TODO - Display Title in TextView
final TextView titleView = (TextView) convertView.findViewById(R.id.titleView);
titleView.setText(toDoItem.getTitle());
// TODO - Set up Status CheckBox
final CheckBox statusView = (CheckBox) convertView.findViewById(R.id.statusCheckBox);
statusView.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
log("Entered onCheckedChanged()");
// TODO - Set up and implement an OnCheckedChangeListener, which
// is called when the user toggles the status checkbox
if(isChecked)
{
toDoItem.setStatus(Status.DONE);
}
else
{
toDoItem.setStatus(Status.NOTDONE);
}
}
});
//TODO - Display Priority in a TextView
final TextView priorityView = (TextView) convertView.findViewById(R.id.priorityView);
priorityView.setTag(toDoItem.getPriority());
// TODO - Display Time and Date.
// Hint - use ToDoItem.FORMAT.format(toDoItem.getDate()) to get date and time String
final TextView dateView = (TextView) convertView.findViewById(R.id.dateView);
dateView.setText(ToDoItem.FORMAT.format(toDoItem.getDate()));
// Return the View you just created
return itemLayout;
}
private void log(String msg) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i(TAG, msg);
}
}
3- AddToDoActivity
package course.labs.todomanager;
import java.util.Calendar;
import java.util.Date;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.TimePicker;
import course.labs.todomanager.ToDoItem.Priority;
import course.labs.todomanager.ToDoItem.Status;
public class AddToDoActivity extends Activity {
// 7 days in milliseconds - 7 * 24 * 60 * 60 * 1000
private static final int SEVEN_DAYS = 604800000;
private static final String TAG = "Lab-UserInterface";
private static String timeString;
private static String dateString;
private static TextView dateView;
private static TextView timeView;
private Date mDate;
private RadioGroup mPriorityRadioGroup;
private RadioGroup mStatusRadioGroup;
private EditText mTitleText;
private RadioButton mDefaultStatusButton;
private RadioButton mDefaultPriorityButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_todo);
mTitleText = (EditText) findViewById(R.id.title);
mDefaultStatusButton = (RadioButton) findViewById(R.id.statusNotDone);
mDefaultPriorityButton = (RadioButton) findViewById(R.id.medPriority);
mPriorityRadioGroup = (RadioGroup) findViewById(R.id.priorityGroup);
mStatusRadioGroup = (RadioGroup) findViewById(R.id.statusGroup);
dateView = (TextView) findViewById(R.id.date);
timeView = (TextView) findViewById(R.id.time);
// Set the default date and time
setDefaultDateTime();
// OnClickListener for the Date button, calls showDatePickerDialog() to show
// the Date dialog
final Button datePickerButton = (Button) findViewById(R.id.date_picker_button);
datePickerButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showDatePickerDialog();
}
});
// OnClickListener for the Time button, calls showTimePickerDialog() to show
// the Time Dialog
final Button timePickerButton = (Button) findViewById(R.id.time_picker_button);
timePickerButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showTimePickerDialog();
}
});
// OnClickListener for the Cancel Button,
final Button cancelButton = (Button) findViewById(R.id.cancelButton);
cancelButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
log("Entered cancelButton.OnClickListener.onClick()");
//TODO - Implement onClick().
setResult(RESULT_CANCELED);
finish();
}
});
//OnClickListener for the Reset Button
final Button resetButton = (Button) findViewById(R.id.resetButton);
resetButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
log("Entered resetButton.OnClickListener.onClick()");
//TODO - Reset data fields to default values
mTitleText.setText(R.id.title);
mPriorityRadioGroup = (RadioGroup) findViewById(R.id.priorityGroup);
mStatusRadioGroup = (RadioGroup) findViewById(R.id.statusGroup);
setDefaultDateTime();
}
});
// OnClickListener for the Submit Button
// Implement onClick().
final Button submitButton = (Button) findViewById(R.id.submitButton);
submitButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
log("Entered submitButton.OnClickListener.onClick()");
// Gather ToDoItem data
//TODO - Get Priority
Priority priority = getPriority();
//TODO - Get Status
Status status = getStatus();
//TODO - Title
String titleString = mTitleText.getPrivateImeOptions();
// Date
String fullDate = dateString + " " + timeString;
// Package ToDoItem data into an Intent
Intent data = new Intent();
ToDoItem.packageIntent(data, titleString, priority, status, fullDate);
//TODO - return data Intent and finish
setResult(RESULT_OK);
finish();
}
});
}
// Do not modify below here
// Use this method to set the default date and time
private void setDefaultDateTime() {
// Default is current time + 7 days
mDate = new Date();
mDate = new Date(mDate.getTime() + SEVEN_DAYS);
Calendar c = Calendar.getInstance();
c.setTime(mDate);
setDateString(c.get(Calendar.YEAR), c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH));
dateView.setText(dateString);
setTimeString(c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE),
c.get(Calendar.MILLISECOND));
timeView.setText(timeString);
}
private static void setDateString(int year, int monthOfYear, int dayOfMonth) {
// Increment monthOfYear for Calendar/Date -> Time Format setting
monthOfYear++;
String mon = "" + monthOfYear;
String day = "" + dayOfMonth;
if (monthOfYear < 10)
mon = "0" + monthOfYear;
if (dayOfMonth < 10)
day = "0" + dayOfMonth;
dateString = year + "-" + mon + "-" + day;
}
private static void setTimeString(int hourOfDay, int minute, int mili) {
String hour = "" + hourOfDay;
String min = "" + minute;
if (hourOfDay < 10)
hour = "0" + hourOfDay;
if (minute < 10)
min = "0" + minute;
timeString = hour + ":" + min + ":00";
}
private Priority getPriority() {
switch (mPriorityRadioGroup.getCheckedRadioButtonId()) {
case R.id.lowPriority: {
return Priority.LOW;
}
case R.id.highPriority: {
return Priority.HIGH;
}
default: {
return Priority.MED;
}
}
}
private Status getStatus() {
switch (mStatusRadioGroup.getCheckedRadioButtonId()) {
case R.id.statusDone: {
return Status.DONE;
}
default: {
return Status.NOTDONE;
}
}
}
// DialogFragment used to pick a ToDoItem deadline date
public static class DatePickerFragment extends DialogFragment implements
DatePickerDialog.OnDateSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
setDateString(year, monthOfYear, dayOfMonth);
dateView.setText(dateString);
}
}
// DialogFragment used to pick a ToDoItem deadline time
public static class TimePickerFragment extends DialogFragment implements
TimePickerDialog.OnTimeSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return
return new TimePickerDialog(getActivity(), this, hour, minute,
true);
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
setTimeString(hourOfDay, minute, 0);
timeView.setText(timeString);
}
}
private void showDatePickerDialog() {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");
}
private void showTimePickerDialog() {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "timePicker");
}
private void log(String msg) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i(TAG, msg);
}
}
4- ToDoItem
package course.labs.todomanager;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.content.Intent;
// Do not modify
public class ToDoItem {
public static final String ITEM_SEP = System.getProperty("line.separator");
public enum Priority {
LOW, MED, HIGH
};
public enum Status {
NOTDONE, DONE
};
public final static String TITLE = "title";
public final static String PRIORITY = "priority";
public final static String STATUS = "status";
public final static String DATE = "date";
public final static String FILENAME = "filename";
public final static SimpleDateFormat FORMAT = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss", Locale.US);
private String mTitle = new String();
private Priority mPriority = Priority.LOW;
private Status mStatus = Status.NOTDONE;
private Date mDate = new Date();
ToDoItem(String title, Priority priority, Status status, Date date) {
this.mTitle = title;
this.mPriority = priority;
this.mStatus = status;
this.mDate = date;
}
// Create a new ToDoItem from data packaged in an Intent
ToDoItem(Intent intent) {
mTitle = intent.getStringExtra(ToDoItem.TITLE);
mPriority = Priority.valueOf(intent.getStringExtra(ToDoItem.PRIORITY));
mStatus = Status.valueOf(intent.getStringExtra(ToDoItem.STATUS));
try {
mDate = ToDoItem.FORMAT.parse(intent.getStringExtra(ToDoItem.DATE));
} catch (ParseException e) {
mDate = new Date();
}
}
public String getTitle() {
return mTitle;
}
public void setTitle(String title) {
mTitle = title;
}
public Priority getPriority() {
return mPriority;
}
public void setPriority(Priority priority) {
mPriority = priority;
}
public Status getStatus() {
return mStatus;
}
public void setStatus(Status status) {
mStatus = status;
}
public Date getDate() {
return mDate;
}
public void setDate(Date date) {
mDate = date;
}
// Take a set of String data values and
// package them for transport in an Intent
public static void packageIntent(Intent intent, String title,
Priority priority, Status status, String date) {
intent.putExtra(ToDoItem.TITLE, title);
intent.putExtra(ToDoItem.PRIORITY, priority.toString());
intent.putExtra(ToDoItem.STATUS, status.toString());
intent.putExtra(ToDoItem.DATE, date);
}
public String toString() {
return mTitle + ITEM_SEP + mPriority + ITEM_SEP + mStatus + ITEM_SEP
+ FORMAT.format(mDate);
}
public String toLog() {
return "Title:" + mTitle + ITEM_SEP + "Priority:" + mPriority
+ ITEM_SEP + "Status:" + mStatus + ITEM_SEP + "Date:"
+ FORMAT.format(mDate);
}
}
Can anybody help?
li.inflate(R.id.footerView, getListView());
You cannot inflate ids, only layouts.
Replace R.id.footerView with R.layout.your_footer_view_layout.
Also, you probably want to capture the inflated View to some variable to actually use it later.
Try this:
//Inflate footerView for footer_view.xml file
TextView footerView = (TextView) getLayoutInflater().inflate(R.layout.footer_view, null);
You should replace setTag(). Change
priorityView.setTag(toDoItem.getPriority());
to
priorityView.setText(toDoItem.getPriority().ToString());

Categories

Resources