Unable to start Activity ComponentInfo{} java.lang.nullPointerException - java

I'm still in the process of learning java, so I'm sorry if this question is too obvious. I'm trying to launch my app and it throws this error. The problem seems to be in the OnCreate() method, but I can't figure out what's causing it.
import java.util.Calendar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;
public class MainActivity extends Activity {
public final static String NAME = "nick.miros.famous.problems.MESSAGE";
public final static String EMAIL = "nick.miros.famous.problems.MESSAGE1";
public final static String STUFFSEX = "nick.miros.famous.problems.MESSAGE2";
public final static String BIRTHDAY = "nick.miros.famous.problems.MESSAGE3";
private boolean agreed;
private String sex;
public static String bornDate;
public EditText emailEdit;
public EditText nameEdit;
public EditText passwordEdit;
// public EditText passwordRepeatEdit;
public RadioGroup radioSex;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nameEdit = (EditText) findViewById(R.id.name);
emailEdit = (EditText) findViewById(R.id.email);
passwordEdit = (EditText) findViewById(R.id.password);
// passwordRepeatEdit = (EditText) findViewById(R.id.passwordRepeat);
emailEdit.addTextChangedListener(new GenericTextWatcher(emailEdit));
nameEdit.addTextChangedListener(new GenericTextWatcher(nameEdit));
passwordEdit
.addTextChangedListener(new GenericTextWatcher(passwordEdit));
// passwordRepeatEdit.addTextChangedListener(new
// GenericTextWatcher(passwordRepeatEdit));
Button Go = (Button) findViewById(R.id.sendButton);
Go.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
sendAndCheck();
}
});
}
#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);
return true;
}
private String getSex(int id) {
switch (id) {
case R.id.radioMale:
sex = "Male";
break;
case R.id.radioFemale:
sex = "Female";
break;
}
return sex;
}
public void showThanks() {
Toast.makeText(this.getApplicationContext(), R.string.thank_you,
Toast.LENGTH_LONG).show();
}
public void onCheckBoxClicked(View view) {
// Is the view now checked?
agreed = ((CheckBox) findViewById(R.id.agreementBox)).isChecked();
}
public final static boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target)
.matches();
}
}
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);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
bornDate = Integer.toString(year) + "/" + Integer.toString(month)
+ "/" + Integer.toString(day);
}
}
public void showDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");
}
/** Called when the user clicks the Send button */
public void sendAndCheck() {
CharSequence emailToCheck = ((EditText) findViewById(R.id.email))
.getText().toString();
if (agreed) {
// Do something in response to button
if (isValidEmail(emailToCheck)) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
String sent_name = ((EditText) findViewById(R.id.name))
.getText().toString();
String sent_email = ((EditText) findViewById(R.id.email))
.getText().toString();
int id = ((RadioGroup) findViewById(R.id.radioSex))
.getCheckedRadioButtonId();
String sent_sex = getSex(id);
String sent_birthday = bornDate;
intent.putExtra(NAME, sent_name);
intent.putExtra(EMAIL, sent_email);
intent.putExtra(STUFFSEX, sent_sex);
intent.putExtra(BIRTHDAY, sent_birthday);
startActivity(intent);
showThanks();
} else {
((EditText) findViewById(R.id.email)).setError("wrong email!");
}
} else {
AlertDialog.Builder Alert = new AlertDialog.Builder(this);
Alert.setMessage("Please agree with the terms and conditions first");
Alert.setTitle("Notice");
Alert.setPositiveButton("OK", null);
Alert.setCancelable(true);
Alert.create().show();
}
}
}
Here is the GenericTextWatcher:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
public class GenericTextWatcher implements TextWatcher{
private View view;
private PasswordValidator passwordValidator = new PasswordValidator();
String password = ((EditText) view).getText().toString();
GenericTextWatcher(View view) {
this.view = view;
}
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
public void afterTextChanged(Editable editable) {
String text = editable.toString();
switch(view.getId()){
case R.id.name:
if (!(text.equals("")))
{
}
else
{
((EditText) view).setError("wrong name!");
}
break;
case R.id.email:
CharSequence emailToCheck = ((EditText) view).getText().toString();
if (isValidEmail(emailToCheck))
{
}
else
{
((EditText) view).setError("wrong email!");
}
break;
case R.id.password:
if (passwordValidator.isValidPassword(text))
{
}
else
{
((EditText) view).setError("must have 1 uppercase letter, 1 number and be 6 characters long");
}
break;
/* case R.id.passwordRepeat:
String password = (((EditText) view) findViewById(R.id.password).getText().toString();
if (text.equals(password))
{
}
else
{
((EditText) view).setError("passwords don't match");
}
break;*/
}
}
public final static boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target)
.matches();
}
}
public class PasswordValidator{
private Pattern pattern;
private Matcher matcher;
private static final String PASSWORD_PATTERN =
"((?=.*\\d)(?=.*[A-Z]).{6,20})";
public PasswordValidator(){
pattern = Pattern.compile(PASSWORD_PATTERN);
}
/**
* Validate password with regular expression
* #param password password for validation
* #return true valid password, false invalid password
*/
public boolean isValidPassword(String password){
matcher = pattern.matcher(password);
return matcher.matches();
}
}
}
Here is the LogCat:
02-04 03:59:14.267: D/dalvikvm(2400): GC_FOR_ALLOC freed 37K, 7% free 2640K/2820K, paused 1ms, total 34ms
02-04 03:59:14.267: I/dalvikvm-heap(2400): Grow heap (frag case) to 3.319MB for 635808-byte allocation
02-04 03:59:14.277: D/dalvikvm(2400): GC_FOR_ALLOC freed 2K, 6% free 3258K/3444K, paused 10ms, total 10ms
02-04 03:59:14.377: D/AndroidRuntime(2400): Shutting down VM
02-04 03:59:14.377: W/dalvikvm(2400): threadid=1: thread exiting with uncaught exception (group=0xb2eb7648)
02-04 03:59:14.377: E/AndroidRuntime(2400): FATAL EXCEPTION: main
02-04 03:59:14.377: E/AndroidRuntime(2400): java.lang.RuntimeException: Unable to start activity ComponentInfo{nick.miros.famous.problems/nick.miros.famous.problems.MainActivity}: java.lang.NullPointerException
02-04 03:59:14.377: E/AndroidRuntime(2400): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
02-04 03:59:14.377: E/AndroidRuntime(2400): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
02-04 03:59:14.377: E/AndroidRuntime(2400): at android.app.ActivityThread.access$600(ActivityThread.java:141)
02-04 03:59:14.377: E/AndroidRuntime(2400): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
02-04 03:59:14.377: E/AndroidRuntime(2400): at android.os.Handler.dispatchMessage(Handler.java:99)
02-04 03:59:14.377: E/AndroidRuntime(2400): at android.os.Looper.loop(Looper.java:137)
02-04 03:59:14.377: E/AndroidRuntime(2400): at android.app.ActivityThread.main(ActivityThread.java:5103)
02-04 03:59:14.377: E/AndroidRuntime(2400): at java.lang.reflect.Method.invokeNative(Native Method)
02-04 03:59:14.377: E/AndroidRuntime(2400): at java.lang.reflect.Method.invoke(Method.java:525)
02-04 03:59:14.377: E/AndroidRuntime(2400): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
02-04 03:59:14.377: E/AndroidRuntime(2400): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
02-04 03:59:14.377: E/AndroidRuntime(2400): at dalvik.system.NativeStart.main(Native Method)
02-04 03:59:14.377: E/AndroidRuntime(2400): Caused by: java.lang.NullPointerException
02-04 03:59:14.377: E/AndroidRuntime(2400): at nick.miros.famous.problems.GenericTextWatcher.<init>(GenericTextWatcher.java:15)
02-04 03:59:14.377: E/AndroidRuntime(2400): at nick.miros.famous.problems.MainActivity.onCreate(MainActivity.java:46)
02-04 03:59:14.377: E/AndroidRuntime(2400): at android.app.Activity.performCreate(Activity.java:5133)
02-04 03:59:14.377: E/AndroidRuntime(2400): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
02-04 03:59:14.377: E/AndroidRuntime(2400): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
02-04 03:59:14.377: E/AndroidRuntime(2400): ... 11 more

There's a NullPointerException in GenericTextWatcher initialization (<init>), on line 15.
In there you have a member variable:
String password = ((EditText) view).getText().toString();
view is null at this point, you only assign it in constructor later. Move this code to constructor or later.

Related

TitleView bug I don't understand

I am working on a coursera course and I am really getting to the point where I think I am not really up for this field of work (development) and should stick to graphic designing. at least i want to finish this course but i keep getting bugs I don't understand! according to logcat there is a problem with the following line
titleView.setText(toDoItem.getTitle());
But for the life of me cant see the problem! Below is the full program if you need anything just tell me.
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 {
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 inflitrate= getLayoutInflater();
//inflitrate.inflate(R.id.footerView, getListView());
TextView footerView = (TextView) getLayoutInflater().inflate(R.layout.footer_view, null);
// NOTE: You can remove this block once you've implemented the assignment
//if (null == footerView) {
// return;
//}
// TODO - Add footerView to ListView
ListView viewer= getListView();
viewer.addFooterView(footerView);
footerView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.i(TAG,"Entered footerView.OnClickListener.onClick()");
//TODO - Implement OnClick().
Intent addone= new Intent (ToDoManagerActivity.this, AddToDoActivity.class);
startActivityForResult(addone, ADD_TODO_ITEM_REQUEST);
}
});
// TODO - Attach the adapter to this ListActivity's ListView
viewer.setAdapter(mAdapter);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i(TAG,"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.i(TAG, "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();
}
}
}
}
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.i(TAG, "Entered cancelButton.OnClickListener.onClick()");
// TODO - Indicate result and finish
Intent returnIntent = new Intent();
setResult(RESULT_CANCELED,returnIntent);
finish();
}
});
// TODO - Set up OnClickListener for the Reset Button
final Button resetButton = (Button) findViewById(R.id.resetButton);
resetButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.i(TAG, "Entered resetButton.OnClickListener.onClick()");
// TODO - Reset data to default values
mTitleText.setText("");
setDefaultDateTime();
mDefaultStatusButton.setChecked(true);
mDefaultPriorityButton.setChecked(true);
}
});
// Set up OnClickListener for the Submit Button
final Button submitButton = (Button) findViewById(R.id.submitButton);
submitButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.i(TAG, "Entered submitButton.OnClickListener.onClick()");
// gather ToDoItem data
// TODO - Get the current Priority
Priority priority = getPriority();
// TODO - Get the current Status
Status status = getStatus();
// TODO - Get the current ToDoItem Title
String titleString = getToDoTitle();
// Construct the Date string
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 this point.
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;
}
}
}
private String getToDoTitle() {
return mTitleText.getText().toString();
}
// 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");
}
}
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;
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);
}
}
ToDoListAdapter
package course.labs.todomanager;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.os.AsyncTask.Status;
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;
public class ToDoListAdapter extends BaseAdapter {
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 for the ToDoItem at specified position
// Remember to check whether convertView holds an already allocated View
// before created a new View.
// Consider using the ViewHolder pattern to make scrolling more efficient
// See: http://developer.android.com/training/improving-layouts/smooth-scrolling.html
#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 = null;
// 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
if (convertView==null){
LayoutInflater inflator= (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView=inflator.inflate(R.layout.add_todo, null);
}
// 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.setChecked(toDoItem.getStatus()==course.labs.todomanager.ToDoItem.Status.DONE);
statusView.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Log.i(TAG, "Entered onCheckedChanged()");
// TODO - set up an OnCheckedChangeListener, which
// is called when the user toggles the status checkbox
if (toDoItem.getStatus().equals(course.labs.todomanager.ToDoItem.Status.DONE))
{
toDoItem.setStatus(course.labs.todomanager.ToDoItem.Status.NOTDONE); //Change it
}
else
{
toDoItem.setStatus(course.labs.todomanager.ToDoItem.Status.DONE); //Change it
}
}
});
// TODO - Display Priority in a TextView
final TextView priorityView = (TextView) convertView.findViewById(R.id.priorityView);
priorityView.setText(toDoItem.getPriority().toString());
// 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 convertView;
}
}
logcat
02-06 13:11:20.711: E/AndroidRuntime(1288): FATAL EXCEPTION: main
02-06 13:11:20.711: E/AndroidRuntime(1288): java.lang.NullPointerException
02-06 13:11:20.711: E/AndroidRuntime(1288): at >course.labs.todomanager.ToDoListAdapter.getView(ToDoListAdapter.java:105)
02-06 13:11:20.711: E/AndroidRuntime(1288): at android.widget.HeaderViewListAdapter.getView(HeaderViewListAdapter.java:220)
02-06 13:11:20.711: E/AndroidRuntime(1288): at android.widget.AbsListView.obtainView(AbsListView.java:2177)
02-06 13:11:20.711: E/AndroidRuntime(1288): at android.widget.ListView.makeAndAddView(ListView.java:1840)
02-06 13:11:20.711: E/AndroidRuntime(1288): at android.widget.ListView.fillSpecific(ListView.java:1321)
02-06 13:11:20.711: E/AndroidRuntime(1288): at android.widget.ListView.layoutChildren(ListView.java:1633)
02-06 13:11:20.711: E/AndroidRuntime(1288): at android.widget.AbsListView.onLayout(AbsListView.java:2012)
02-06 13:11:20.711: E/AndroidRuntime(1288): at android.view.View.layout(View.java:14289)
02-06 13:11:20.711: E/AndroidRuntime(1288): at android.view.ViewGroup.layout(ViewGroup.java:4562)
02-06 13:11:20.711: E/AndroidRuntime(1288): at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
02-06 13:11:20.711: E/AndroidRuntime(1288): at android.view.View.layout(View.java:14289)
02-06 13:11:20.711: E/AndroidRuntime(1288): at android.view.ViewGroup.layout(ViewGroup.java:4562)
02-06 13:11:20.711: E/AndroidRuntime(1288): at com.android.internal.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:349)
02-06 13:11:20.711: E/AndroidRuntime(1288): at android.view.View.layout(View.java:14289)
02-06 13:11:20.711: E/AndroidRuntime(1288): at android.view.ViewGroup.layout(ViewGroup.java:4562)
02-06 13:11:20.711: E/AndroidRuntime(1288): at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
02-06 13:11:20.711: E/AndroidRuntime(1288): at android.view.View.layout(View.java:14289)
02-06 13:11:20.711: E/AndroidRuntime(1288): at android.view.ViewGroup.layout(ViewGroup.java:4562)
02-06 13:11:20.711: E/AndroidRuntime(1288): at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:1976)
02-06 13:11:20.711: E/AndroidRuntime(1288): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1730)
02-06 13:11:20.711: E/AndroidRuntime(1288): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1004)
02-06 13:11:20.711: E/AndroidRuntime(1288): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5481)
02-06 13:11:20.711: E/AndroidRuntime(1288): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
02-06 13:11:20.711: E/AndroidRuntime(1288): at android.view.Choreographer.doCallbacks(Choreographer.java:562)
02-06 13:11:20.711: E/AndroidRuntime(1288): at android.view.Choreographer.doFrame(Choreographer.java:532)
02-06 13:11:20.711: E/AndroidRuntime(1288): at >android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
02-06 13:11:20.711: E/AndroidRuntime(1288): at >android.os.Handler.handleCallback(Handler.java:730)
02-06 13:11:20.711: E/AndroidRuntime(1288): at >android.os.Handler.dispatchMessage(Handler.java:92)
02-06 13:11:20.711: E/AndroidRuntime(1288): at >android.os.Looper.loop(Looper.java:137)
02-06 13:11:20.711: E/AndroidRuntime(1288): at >android.app.ActivityThread.main(ActivityThread.java:5103)
02-06 13:11:20.711: E/AndroidRuntime(1288): at >java.lang.reflect.Method.invokeNative(Native Method)
02-06 13:11:20.711: E/AndroidRuntime(1288): at java.lang.reflect.Method.invoke(Method.java:525)
02-06 13:11:20.711: E/AndroidRuntime(1288): at >com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
02-06 13:11:20.711: E/AndroidRuntime(1288): at >com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
02-06 13:11:20.711: E/AndroidRuntime(1288): at >dalvik.system.NativeStart.main(Native Method)
02-06 13:11:26.121: I/Process(1288): Sending signal. PID: 1288 SIG: 9
thanks for any help you can offer in advance!
Please make sure your titleView (with id: priorityView) is located in the layout you inflate the R.layout.add_todo
If that's not the case you should place it there. If that doesn't help please post your layout xml file.
I don't know if you figured out the solution yet, but you can try to switch the following
convertView=inflator.inflate(R.layout.add_todo, null);
to
convertView=inflator.inflate(R.layout.add_todo, parent);

Stuck, need help Program crashes whenever it tries to access the SharedPreferences

Program runs until it tries to access the SharedPreferences in my updateUserSettings() method. I have spent the last 2 hours searching the internet with no explanations. Please help!
I have the line that messes everything up Commented at the bottom of my onCreate();
Here is FuelEconomyCalculatorActivity.java
package com.example.fuelcalculator;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
public class FuelEconomyCalculatorActivity extends ActionBarActivity implements
OnClickListener {
private EditText fuelEditText;
private EditText distanceEditText;
private TextView mpgTextView;
private TextView litresTextView;
private Button calculateButton;
private Button clearButton;
private RadioButton gallonsRadio;
private RadioButton litresRadio;
private RadioButton milesRadio;
private RadioButton kmRadio;
private String mpg = " ";
private String kp100 = " ";
private boolean metricChecked;
private boolean imperialChecked;
private boolean usGallonChecked;
private boolean ukGallonChecked;
private static final int RESULT_SETTINGS = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fuel_economy_calculator);
fuelEditText = (EditText) findViewById(R.id.fuelEditText);
distanceEditText = (EditText) findViewById(R.id.distanceEditText);
mpgTextView = (TextView) findViewById(R.id.mpgTextView);
litresTextView = (TextView) findViewById(R.id.litresTextView);
calculateButton = (Button) findViewById(R.id.calculateButton);
clearButton = (Button) findViewById(R.id.clearButton);
gallonsRadio = (RadioButton) findViewById(R.id.gallonsRadio);
litresRadio = (RadioButton) findViewById(R.id.litresRadio);
milesRadio = (RadioButton) findViewById(R.id.milesRadio);
kmRadio = (RadioButton) findViewById(R.id.kmRadio);
calculateButton.setOnClickListener(this);
clearButton.setOnClickListener(this);
if (savedInstanceState != null) {
mpg = savedInstanceState.getString("mpg");
kp100 = savedInstanceState.getString("kp100");
initializeViews();
}
// updateUserSettings();
}
protected void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString("mpg", (String) mpgTextView.getText());
savedInstanceState.putString("kp100", (String) litresTextView.getText());
litresRadio.setChecked(true);
kmRadio.setChecked(true);
}
private void initializeViews() {
mpgTextView.setText(mpg);
litresTextView.setText(kp100);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.fuel_economy_calculator, 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.
switch (item.getItemId()) {
case R.id.action_settings: {
Intent intent = new Intent(FuelEconomyCalculatorActivity.this,
FuelEconomySettingsActivity.class);
startActivityForResult(intent, RESULT_SETTINGS);
return true;
}
case R.id.action_about: {
Intent intent = new Intent(getApplicationContext(), FuelEconomyAboutPageActivity.class);
startActivity(intent);
return true;
}
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_SETTINGS:
updateUserSettings();
break;
}
}
private void updateUserSettings() {
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this);
if(sharedPrefs.getString("measuringUnits", null).equalsIgnoreCase("metric"))
{
metricChecked = true;
imperialChecked = false;
}
else if(sharedPrefs.getString("measuringUnits", null).equalsIgnoreCase("imperial"))
{
imperialChecked = true;
metricChecked = false;
}
if(sharedPrefs.getString("gallons", null).equalsIgnoreCase("uk"))
{
ukGallonChecked = true;
usGallonChecked = false;
}
else if(sharedPrefs.getString("gallons", null).equalsIgnoreCase("us"))
{
usGallonChecked = true;
ukGallonChecked = false;
}
if(metricChecked)
{
litresRadio.setChecked(true);
kmRadio.setChecked(true);
}
else if(imperialChecked)
{
milesRadio.setChecked(true);
gallonsRadio.setChecked(true);
}
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.calculateButton) {
float mpg = 0;
float kmLitres = 0;
// it doesn't matter which you use here, as long
// as you use a fuel and a distance method
if (ukGallonChecked && !usGallonChecked) {
if (getKM() > 0 && getLitres() > 0) {
mpg = getMiles() / getGallons();
kmLitres = getLitres() / (getKM() / 100);
mpgTextView.setText(String.format("%.2f", mpg));
litresTextView.setText(String.format("%.2f", kmLitres));
}
} else if (usGallonChecked && !ukGallonChecked) {
if (getKM() > 0 && getLitres() > 0) {
mpg = getMiles() / getGallonsUS();
kmLitres = getLitresUS() / (getKM() / 100);
mpgTextView.setText(String.format("%.2f", mpg));
litresTextView.setText(String.format("%.2f", kmLitres));
}
}
} else if (v.getId() == R.id.clearButton) {
resetValues();
}
}
public float CheckValues(EditText input) {
float value = 0;
try {
value = Float.parseFloat(input.getText().toString());
if (value < 1) {
Toast toast = Toast.makeText(this,
"Please enter a number that is larger than 0",
Toast.LENGTH_SHORT);
toast.show();
}
} catch (Exception ex) {
Toast toast = Toast.makeText(this, "Please enter a number",
Toast.LENGTH_SHORT);
toast.show();
}
return value;
}
public void resetValues() {
mpg = " ";
kp100 = " ";
fuelEditText.setText("");
distanceEditText.setText("");
mpgTextView.setText("");
litresTextView.setText("");
}
public float getKM() {
float distance = CheckValues(distanceEditText);
if (milesRadio.isChecked()) {
distance = (float) (distance * 1.60934);
}
return distance;
}
public float getMiles() {
float distance = CheckValues(distanceEditText);
if (kmRadio.isChecked()) {
distance = (float) (distance * 0.62137);
}
return distance;
}
public float getLitres() {
float fuel = CheckValues(fuelEditText);
if (gallonsRadio.isChecked()) {
fuel = (float) (fuel * 4.54609);
}
return fuel;
}
public float getLitresUS() {
float fuel = CheckValues(fuelEditText);
if (gallonsRadio.isChecked()) {
fuel = (float) (fuel * 3.785411784);
}
return fuel;
}
public float getGallons() {
float fuel = CheckValues(fuelEditText);
if (litresRadio.isChecked()) {
fuel = (float) (fuel * 0.219969);
}
return fuel;
}
public float getGallonsUS() {
float fuel = CheckValues(fuelEditText);
if (litresRadio.isChecked()) {
fuel = (float) (fuel * 0.264172);
}
return fuel;
}
}
And here is my FuelEconomySettingsActivity.java
package com.example.fuelcalculator;
import android.app.Activity;
import android.os.Bundle;
public class FuelEconomySettingsActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content,
new FuelEconomySettingsFragment()).commit();
}
}
Here is my LogCat
07-18 14:35:37.014: E/AndroidRuntime(3084): FATAL EXCEPTION: main
07-18 14:35:37.014: E/AndroidRuntime(3084): Process: com.example.fuelcalculator, PID: 3084
07-18 14:35:37.014: E/AndroidRuntime(3084): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.fuelcalculator/com.example.fuelcalculator.FuelEconomyCalculatorActivity}: java.lang.NullPointerException
07-18 14:35:37.014: E/AndroidRuntime(3084): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
07-18 14:35:37.014: E/AndroidRuntime(3084): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
07-18 14:35:37.014: E/AndroidRuntime(3084): at android.app.ActivityThread.access$900(ActivityThread.java:161)
07-18 14:35:37.014: E/AndroidRuntime(3084): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
07-18 14:35:37.014: E/AndroidRuntime(3084): at android.os.Handler.dispatchMessage(Handler.java:102)
07-18 14:35:37.014: E/AndroidRuntime(3084): at android.os.Looper.loop(Looper.java:157)
07-18 14:35:37.014: E/AndroidRuntime(3084): at android.app.ActivityThread.main(ActivityThread.java:5356)
07-18 14:35:37.014: E/AndroidRuntime(3084): at java.lang.reflect.Method.invokeNative(Native Method)
07-18 14:35:37.014: E/AndroidRuntime(3084): at java.lang.reflect.Method.invoke(Method.java:515)
07-18 14:35:37.014: E/AndroidRuntime(3084): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
07-18 14:35:37.014: E/AndroidRuntime(3084): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
07-18 14:35:37.014: E/AndroidRuntime(3084): at dalvik.system.NativeStart.main(Native Method)
07-18 14:35:37.014: E/AndroidRuntime(3084): Caused by: java.lang.NullPointerException
07-18 14:35:37.014: E/AndroidRuntime(3084): at com.example.fuelcalculator.FuelEconomyCalculatorActivity.updateUserSettings(FuelEconomyCalculatorActivity.java:128)
07-18 14:35:37.014: E/AndroidRuntime(3084): at com.example.fuelcalculator.FuelEconomyCalculatorActivity.onCreate(FuelEconomyCalculatorActivity.java:63)
07-18 14:35:37.014: E/AndroidRuntime(3084): at android.app.Activity.performCreate(Activity.java:5426)
07-18 14:35:37.014: E/AndroidRuntime(3084): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
07-18 14:35:37.014: E/AndroidRuntime(3084): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
07-18 14:35:37.014: E/AndroidRuntime(3084): ... 11 more
I am new to Android so I am not very good at debugging so could someone please assist me with my predicament?
The activity is already included in my Manifest so I know that is not the issue.
Any help is much obliged.
You are getting a NullPointerException because you are getting null as the default value for SharedPreference.getString()
Since it is getString() get an empty string as the default value...
So try this..
if(sharedPrefs.getString("measuringUnits", "").equalsIgnoreCase("metric"))
instead of
if(sharedPrefs.getString("measuringUnits", null).equalsIgnoreCase("metric"))

Search bar to ListView return blank values and getFilter error

I need to add a search bar in my app, but all the tutorials I tried is not working. Because I want this bar to return the values ​​of my ListView imported from Excel (I applied in a way that the Activity shows the names of people). My ListView is imported from Excel, not created in-app code.
That is, when I search for "A" all the names of the ListView with "A" appears when I search "Arn", appear the names containing "Arn" (E.g. Arnold Clinton).
This is the code of TabelaActivity.java:
package com.akzonobel.malote.tabela;
import com.akzonobel.malote.R;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.ListView;
public class TabelaActivity extends Activity {
CSVAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabela);
ListView mList = (ListView)findViewById(R.id.mList);
mAdapter = new CSVAdapter(this, -1);
mList.setAdapter(mAdapter);
}
}
This is the code of CSVAdapter.java:
package com.akzonobel.malote.tabela;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class CSVAdapter extends ArrayAdapter<State>{
Context ctx;
public CSVAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
this.ctx = context;
loadArrayFromFile();
}
#Override
public View getView(final int pos, View convertView, final ViewGroup parent){
TextView mView = (TextView)convertView;
if(null == mView){
mView = new TextView(parent.getContext());
mView.setTextSize(19);
mView.setTextColor(Color.WHITE);
}
mView.setText(getItem(pos).getName());
return mView;
}
private void loadArrayFromFile(){
try {
InputStream is = ctx.getAssets().open("states.csv");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null) {
State cur = new State();
cur.setName(line);
this.add(cur);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
This is the code of State.java:
package com.akzonobel.malote.tabela;
public class State {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
I tried to apply this search bar:
EditText inputSearch;
inputSearch = (EditText) findViewById(R.id.inputSearch);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
TabelaActivity.this.mAdapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
The search bar works, can you enter. But when I type the value... it just does not return anything, goes blank. Any help? How to make it work? Or is there another easy way to make a search bar? Can the ActionBar.. the important thing is it works.
Then I tried to apply the getFilter in CSVAdapter, but then when I try to use the bar with this getFilter, it crashes and closes alone.
This is the code I applied getFilter:
private List<State> allModelItemsArray;
private List<State> filteredModelItemsArray;
private Filter filter;
#Override
public Filter getFilter() {
if (filter == null){
filter = new ModelFilter();
}
return filter;
}
private class ModelFilter extends Filter
{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
constraint = constraint.toString().toLowerCase();
FilterResults result = new FilterResults();
if(constraint != null && constraint.toString().length() > 0)
{
ArrayList<State> filteredItems = new ArrayList<State>();
for(int i = 0, l = allModelItemsArray.size(); i < l; i++)
{
State m = allModelItemsArray.get(i);
if(m.getName().toLowerCase().contains(constraint))
filteredItems.add(m);
}
result.count = filteredItems.size();
result.values = filteredItems;
}
else
{
synchronized(this)
{
result.values = allModelItemsArray;
result.count = allModelItemsArray.size();
}
}
return result;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredModelItemsArray = (ArrayList<State>)results.values;
notifyDataSetChanged();
clear();
for(int i = 0, l = filteredModelItemsArray.size(); i < l; i++)
add(filteredModelItemsArray.get(i));
notifyDataSetInvalidated();
}
}
And when this is active getFilter, besides closing, it gives the following error in LogCat:
07-13 08:32:52.925: W/Filter(30254): An exception occured during performFiltering()!
07-13 08:32:52.925: W/Filter(30254): java.lang.NullPointerException
07-13 08:32:52.925: W/Filter(30254): at com.akzonobel.malote.tabela.CSVAdapter$ModelFilter.performFiltering(CSVAdapter.java:129)
07-13 08:32:52.925: W/Filter(30254): at android.widget.Filter$RequestHandler.handleMessage(Filter.java:234)
07-13 08:32:52.925: W/Filter(30254): at android.os.Handler.dispatchMessage(Handler.java:99)
07-13 08:32:52.925: W/Filter(30254): at android.os.Looper.loop(Looper.java:137)
07-13 08:32:52.925: W/Filter(30254): at android.os.HandlerThread.run(HandlerThread.java:60)
07-13 08:33:14.856: D/AndroidRuntime(30254): Shutting down VM
07-13 08:33:14.856: W/dalvikvm(30254): threadid=1: thread exiting with uncaught exception (group=0x41101930)
07-13 08:33:14.876: E/AndroidRuntime(30254): FATAL EXCEPTION: main
07-13 08:33:14.876: E/AndroidRuntime(30254): java.lang.NullPointerException
07-13 08:33:14.876: E/AndroidRuntime(30254): at com.akzonobel.malote.tabela.CSVAdapter$ModelFilter.publishResults(CSVAdapter.java:156)
07-13 08:33:14.876: E/AndroidRuntime(30254): at android.widget.Filter$ResultsHandler.handleMessage(Filter.java:282)
07-13 08:33:14.876: E/AndroidRuntime(30254): at android.os.Handler.dispatchMessage(Handler.java:99)
07-13 08:33:14.876: E/AndroidRuntime(30254): at android.os.Looper.loop(Looper.java:137)
07-13 08:33:14.876: E/AndroidRuntime(30254): at android.app.ActivityThread.main(ActivityThread.java:5283)
07-13 08:33:14.876: E/AndroidRuntime(30254): at java.lang.reflect.Method.invokeNative(Native Method)
07-13 08:33:14.876: E/AndroidRuntime(30254): at java.lang.reflect.Method.invoke(Method.java:511)
07-13 08:33:14.876: E/AndroidRuntime(30254): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
07-13 08:33:14.876: E/AndroidRuntime(30254): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
07-13 08:33:14.876: E/AndroidRuntime(30254): at dalvik.system.NativeStart.main(Native Method)
Add a constructor to the State class:
public State(String name) {
this.name = name;
}
Don't use the global allModelItemsArray and filteredItemsArray, get rid of them.
Then change your performFiltering function like this:
#Override
protected FilterResults performFiltering(CharSequence constraint) {
constraint = constraint.toString().toLowerCase();
FilterResults result = new FilterResults();
if(constraint != null && constraint.toString().length() > 0)
{
ArrayList<State> filteredItems = new ArrayList<State>();
for(int i = 0, l = getCount(); i < l; i++)
{
State m = getItem(i);
if(m.getName().toLowerCase().contains(constraint))
filteredItems.add(m);
}
result.count = filteredItems.size();
result.values = filteredItems;
}
else
{
ArrayList<State> allItems = new ArrayList<State>();
for(int i = 0, l = getCount(); i < l; i++)
{
State m = getItem(i);
allItems.add(m);
}
synchronized(this)
{
result.values = allItems;
result.count = allItems.size();
}
}
return result;
}
This will work much better and is proper way to fix this.

The constructor LocationClient(MainActivity, MainActivity, MainActivity) is undefined

So I'm following along with a Lynda.com Tutorial on using Google Maps V2 to build mobile Apps and I was going along with a part that has you creating a map app that is finding the location programatically rather than relying on the setMyLocationEnabled(true) method. So I've followed along with the code and each time I go to run the app it crashes and give me the following error in the logcat:
05-15 12:18:35.139: E/AndroidRuntime(22270): FATAL EXCEPTION: main
05-15 12:18:35.139: E/AndroidRuntime(22270): Process: com.example.gmapsapp, PID: 22270
05-15 12:18:35.139: E/AndroidRuntime(22270): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.gmapsapp/com.example.gmapsapp.MainActivity}: java.lang.ClassCastException: com.example.gmapsapp.MainActivity cannot be cast to com.google.android.gms.common.GooglePlayServicesClient$ConnectionCallbacks
05-15 12:18:35.139: E/AndroidRuntime(22270): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
05-15 12:18:35.139: E/AndroidRuntime(22270): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
05-15 12:18:35.139: E/AndroidRuntime(22270): at android.app.ActivityThread.access$900(ActivityThread.java:161)
05-15 12:18:35.139: E/AndroidRuntime(22270): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
05-15 12:18:35.139: E/AndroidRuntime(22270): at android.os.Handler.dispatchMessage(Handler.java:102)
05-15 12:18:35.139: E/AndroidRuntime(22270): at android.os.Looper.loop(Looper.java:157)
05-15 12:18:35.139: E/AndroidRuntime(22270): at android.app.ActivityThread.main(ActivityThread.java:5356)
05-15 12:18:35.139: E/AndroidRuntime(22270): at java.lang.reflect.Method.invokeNative(Native Method)
05-15 12:18:35.139: E/AndroidRuntime(22270): at java.lang.reflect.Method.invoke(Method.java:515)
05-15 12:18:35.139: E/AndroidRuntime(22270): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
05-15 12:18:35.139: E/AndroidRuntime(22270): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
05-15 12:18:35.139: E/AndroidRuntime(22270): at dalvik.system.NativeStart.main(Native Method)
05-15 12:18:35.139: E/AndroidRuntime(22270): Caused by: java.lang.ClassCastException: com.example.gmapsapp.MainActivity cannot be cast to com.google.android.gms.common.GooglePlayServicesClient$ConnectionCallbacks
05-15 12:18:35.139: E/AndroidRuntime(22270): at com.example.gmapsapp.MainActivity.onCreate(MainActivity.java:60)
05-15 12:18:35.139: E/AndroidRuntime(22270): at android.app.Activity.performCreate(Activity.java:5426)
05-15 12:18:35.139: E/AndroidRuntime(22270): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
05-15 12:18:35.139: E/AndroidRuntime(22270): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
05-15 12:18:35.139: E/AndroidRuntime(22270): ... 11 more
Here's the code in my MainActivity.java, let me know if you need any other files to see if you can help with the issue thanks:
package com.example.gmapsapp;
import java.io.IOException;
import java.util.List;
import android.app.Dialog;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
public class MainActivity extends FragmentActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
private static final int GPS_ERRORDIALOG_REQUEST = 9001;
#SuppressWarnings("unused")
private static final int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9002;
GoogleMap mMap;
#SuppressWarnings("unused")
private static final double SEATTLE_LAT = 47.60621,
SEATTLE_LNG =-122.33207,
SYDNEY_LAT = -33.867487,
SYDNEY_LNG = 151.20699,
NEWYORK_LAT = 40.714353,
NEWYORK_LNG = -74.005973;
private static final float DEFAULTZOOM = 15;
#SuppressWarnings("unused")
private static final String LOGTAG = "Maps";
LocationClient mLocationClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (servicesOK()) {
setContentView(R.layout.activity_map);
if (initMap()) {
// mMap.setMyLocationEnabled(true);
mLocationClient = new LocationClient(this, (ConnectionCallbacks) this, this);
mLocationClient.connect();
}
else {
Toast.makeText(this, "Map not available!", Toast.LENGTH_SHORT).show();
}
}
else {
setContentView(R.layout.activity_main);
}
}
#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);
return true;
}
public boolean servicesOK() {
int isAvailable = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (isAvailable == ConnectionResult.SUCCESS) {
return true;
}
else if (GooglePlayServicesUtil.isUserRecoverableError(isAvailable)) {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(isAvailable, this, GPS_ERRORDIALOG_REQUEST);
dialog.show();
}
else {
Toast.makeText(this, "Can't connect to Google Play services", Toast.LENGTH_SHORT).show();
}
return false;
}
private boolean initMap() {
if (mMap == null) {
SupportMapFragment mapFrag =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mMap = mapFrag.getMap();
}
return (mMap != null);
}
#SuppressWarnings("unused")
private void gotoLocation(double lat, double lng) {
LatLng ll = new LatLng(lat, lng);
CameraUpdate update = CameraUpdateFactory.newLatLng(ll);
mMap.moveCamera(update);
}
private void gotoLocation(double lat, double lng,
float zoom) {
LatLng ll = new LatLng(lat, lng);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, zoom);
mMap.moveCamera(update);
}
public void geoLocate(View v) throws IOException {
hideSoftKeyboard(v);
EditText et = (EditText) findViewById(R.id.editText1);
String location = et.getText().toString();
Geocoder gc = new Geocoder(this);
List<Address> list = gc.getFromLocationName(location, 1);
Address add = list.get(0);
String locality = add.getLocality();
Toast.makeText(this, locality, Toast.LENGTH_LONG).show();
double lat = add.getLatitude();
double lng = add.getLongitude();
gotoLocation(lat, lng, DEFAULTZOOM);
}
private void hideSoftKeyboard(View v) {
InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.mapTypeNone:
mMap.setMapType(GoogleMap.MAP_TYPE_NONE);
break;
case R.id.mapTypeNormal:
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
break;
case R.id.mapTypeSatellite:
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
break;
case R.id.mapTypeTerrain:
mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
break;
case R.id.mapTypeHybrid:
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
break;
case R.id.gotoCurrentLocation:
gotoCurrentLocation();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onStop() {
super.onStop();
MapStateManager mgr = new MapStateManager(this);
mgr.saveMapState(mMap);
}
#Override
protected void onResume() {
super.onResume();
MapStateManager mgr = new MapStateManager(this);
CameraPosition position = mgr.getSavedCameraPosition();
if (position != null) {
CameraUpdate update = CameraUpdateFactory.newCameraPosition(position);
mMap.moveCamera(update);
// This is part of the answer to the code challenge
mMap.setMapType(mgr.getSavedMapType());
}
}
protected void gotoCurrentLocation() {
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle arg0) {
Toast.makeText(this, "Connected to location service", Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
}
}
The second and third parameters of constructor have a type of:
GooglePlayServicesClient.ConnectionCallbacks
GooglePlayServicesClient.OnConnectionFailedListener
So you should implement these interfaces in your Activity, if you are pointing to this. But you've picked up similar interfaces from another class - GoogleApiClient
Not familiar with android apis but looks like a bad import of ConnectionCallbacks (import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;). When you cast to ConnectionCallbacks its using that bad import instead of GoogleApiClient.ConnectionCallbacks.
Edited:
ok so its the other way around!

java.lang.RuntimeException: Unable to create application and at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4254)

I am new to android and java. I tried to check my code against an example but somehow the application keeps forced close while the example works perfectly well. I need help please! Thanks in advance! I just changed the name to string instead of int. I don't know if i did correct for HistoryActivity the ArrayAdapter
Logcat:
07-31 17:26:56.485: E/ArrayAdapter(20248): You must supply a resource ID for a TextView
07-31 17:26:56.490: D/AndroidRuntime(20248): Shutting down VM
07-31 17:26:56.490: W/dalvikvm(20248): threadid=1: thread exiting with uncaught exception (group=0x40fdb2a0)
07-31 17:26:56.505: E/AndroidRuntime(20248): FATAL EXCEPTION: main
07-31 17:26:56.505: E/AndroidRuntime(20248): java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView
07-31 17:26:56.505: E/AndroidRuntime(20248): at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:386)
07-31 17:26:56.505: E/AndroidRuntime(20248): at android.widget.ArrayAdapter.getView(ArrayAdapter.java:362)
07-31 17:26:56.505: E/AndroidRuntime(20248): at android.widget.AbsListView.obtainView(AbsListView.java:2465)
07-31 17:26:56.505: E/AndroidRuntime(20248): at android.widget.ListView.makeAndAddView(ListView.java:1775)
07-31 17:26:56.505: E/AndroidRuntime(20248): at android.widget.ListView.fillDown(ListView.java:678)
07-31 17:26:56.505: E/AndroidRuntime(20248): at android.widget.ListView.fillFromTop(ListView.java:739)
07-31 17:26:56.505: E/AndroidRuntime(20248): at android.widget.ListView.layoutChildren(ListView.java:1628)
07-31 17:26:56.505: E/AndroidRuntime(20248): at android.widget.AbsListView.onLayout(AbsListView.java:2300)
07-31 17:26:56.505: E/AndroidRuntime(20248): at android.view.View.layout(View.java:14072)
07-31 17:26:56.505: E/AndroidRuntime(20248): at android.view.ViewGroup.layout(ViewGroup.java:4607)
07-31 17:26:56.505: E/AndroidRuntime(20248): at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1655)
07-31 17:26:56.505: E/AndroidRuntime(20248): at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1513)
07-31 17:26:56.505: E/AndroidRuntime(20248): at android.widget.LinearLayout.onLayout(LinearLayout.java:1426)
07-31 17:26:56.505: E/AndroidRuntime(20248): at android.view.View.layout(View.java:14072)
07-31 17:26:56.505: E/AndroidRuntime(20248): at android.view.ViewGroup.layout(ViewGroup.java:4607)
07-31 17:26:56.505: E/AndroidRuntime(20248): at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
07-31 17:26:56.505: E/AndroidRuntime(20248): at android.view.View.layout(View.java:14072)
07-31 17:26:56.505: E/AndroidRuntime(20248): at android.view.ViewGroup.layout(ViewGroup.java:4607)
07-31 17:26:56.505: E/AndroidRuntime(20248): at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1655)
07-31 17:26:56.505: E/AndroidRuntime(20248): at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1513)
07-31 17:26:56.505: E/AndroidRuntime(20248): at android.widget.LinearLayout.onLayout(LinearLayout.java:1426)
07-31 17:26:56.505: E/AndroidRuntime(20248): at android.view.View.layout(View.java:14072)
07-31 17:26:56.505: E/AndroidRuntime(20248): at android.view.ViewGroup.layout(ViewGroup.java:4607)
07-31 17:26:56.505: E/AndroidRuntime(20248): at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
07-31 17:26:56.505: E/AndroidRuntime(20248): at android.view.View.layout(View.java:14072)
07-31 17:26:56.505: E/AndroidRuntime(20248): at android.view.ViewGroup.layout(ViewGroup.java:4607)
07-31 17:26:56.505: E/AndroidRuntime(20248): at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:1997)
07-31 17:26:56.505: E/AndroidRuntime(20248): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1818)
07-31 17:26:56.505: E/AndroidRuntime(20248): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1115)
07-31 17:26:56.505: E/AndroidRuntime(20248): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4526)
07-31 17:26:56.505: E/AndroidRuntime(20248): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
07-31 17:26:56.505: E/AndroidRuntime(20248): at android.view.Choreographer.doCallbacks(Choreographer.java:555)
07-31 17:26:56.505: E/AndroidRuntime(20248): at android.view.Choreographer.doFrame(Choreographer.java:525)
07-31 17:26:56.505: E/AndroidRuntime(20248): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711)
07-31 17:26:56.505: E/AndroidRuntime(20248): at android.os.Handler.handleCallback(Handler.java:615)
07-31 17:26:56.505: E/AndroidRuntime(20248): at android.os.Handler.dispatchMessage(Handler.java:92)
07-31 17:26:56.505: E/AndroidRuntime(20248): at android.os.Looper.loop(Looper.java:137)
07-31 17:26:56.505: E/AndroidRuntime(20248): at android.app.ActivityThread.main(ActivityThread.java:4921)
07-31 17:26:56.505: E/AndroidRuntime(20248): at java.lang.reflect.Method.invokeNative(Native Method)
07-31 17:26:56.505: E/AndroidRuntime(20248): at java.lang.reflect.Method.invoke(Method.java:511)
07-31 17:26:56.505: E/AndroidRuntime(20248): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
07-31 17:26:56.505: E/AndroidRuntime(20248): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
07-31 17:26:56.505: E/AndroidRuntime(20248): at dalvik.system.NativeStart.main(Native Method)
07-31 17:26:56.505: E/AndroidRuntime(20248): Caused by: java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.widget.TextView
07-31 17:26:56.505: E/AndroidRuntime(20248): at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:379)
07-31 17:26:56.505: E/AndroidRuntime(20248): ... 42 more
Contacts.java
package com.Elson.ProjectVersion;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteException;
import android.util.Log;
public class Contacts implements Comparable<Contacts> {
private long id;
private String name;
private int Phone;
private int Email;
private Date date;
private double runningAverage;
public Contacts(String name, int Phone, Date date) {
this.name = name;
this.Phone = Phone;
this.date = date;
}
public Contacts(long id, String name,int Phone) {
this.id=id;
this.Phone=Phone;
this.name= (name);
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public int getPhone() {
return Phone;
}
public void setPhone(int Phone) {
this.Phone = Phone;
}
public String getname() {
return name;
}
public void setname(String name) {
this.name = name;
}
public Date getDate() {
return date;
}
public long getDateEpoch(){
return date.getTime()/1000;
}
public void setDateEpoch(long seconds){
date= new Date (seconds*1000);
}
public void setDate(Date date) {
this.date = date;
}
public void setRunningAverage(double runningAverage) {
this.runningAverage = runningAverage;
}
public boolean equals(Object that){
Contacts bs = (Contacts) that;
return this.date.equals(bs.date);
}
#Override
public String toString() {
String result;
// "ID" + id +" "
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
result = df.format(date) + "" + name + "" + Phone ;
return result;
}
#Override
public int compareTo(Contacts another) {
// TODO Auto-generated method stub
return 0;
}
}
ContactsActivityApplication:
package com.Elson.ProjectVersion;
import java.util.ArrayList;
import android.app.Application;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import static com.Elson.ProjectVersion.MyContactSQL.*;
public class EnterContactsActivity extends Activity {
private Button saveButton;
private EditText NameEditText;
private EditText PhoneEditText;
private Button ExitButton;
private EditText EmailEditText;
private TextView date;
private int month;//private within class
private int day;
private int year;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addcontacts);
setUpViews();
Calendar calendar =Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
Date today = calendar.getTime();
DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM);
String cs = df.format(today);
date.setText(cs);
}
public void saveClickHandler(View v){
String ContactsScore;
ContactsScore= NameEditText.getText().toString();
String name = String.format(ContactsScore, null);
ContactsScore= PhoneEditText.getText().toString();
int Phone = Integer.parseInt(ContactsScore);
Log.d("EnterContacts" , "I hear the Save Button");
if( isValid(Phone) ) {
Contacts contacts;
Date dateofGames= new GregorianCalendar(year,month,day).getTime();
contacts = new Contacts (name , Phone , dateofGames);
ContactsActivityApplication app = (ContactsActivityApplication) getApplication();
//might be wrong
Log.d("DeBUGGING", "app is this type: " + app.getClass().getName());
//need add the function addBowlingScores
app.addallContacts(contacts);
Toast.makeText(getApplicationContext(), "Your Contact has been Saved!", Toast.LENGTH_SHORT).show();
}
else{
//pop up a dialog that data is invalid
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Invalid Phone Number")
.setMessage("Phone numbers cannot have more than 8 numbers")
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
private boolean isValid(int Phone ) {
if(Phone > 0 && Phone <100000000)
return true;
return false;
// TODO Auto-generated method stub
}
public void handleShowHistoryClick (View v) {
Intent intent = new Intent(this, HistoryActivity.class);
startActivity(intent);
}
private void setUpViews()
{
ExitButton = (Button) findViewById(R.id.BtnExit);
saveButton =(Button) findViewById(R.id.BtnSave);
NameEditText= (EditText) findViewById(R.id.NameEditText);
PhoneEditText= (EditText) findViewById(R.id.PhoneEditText);
EmailEditText= (EditText) findViewById(R.id.EmailEditText);
date = (TextView) findViewById(R.id.DateTextView);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.addcontacts, menu);
return true;
}
}
EnterContactsActivity:
package com.Elson.ProjectVersion;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class EnterContactsActivity extends Activity {
private Button saveButton;
private EditText NameEditText;
private EditText PhoneEditText;
private Button ExitButton;
private EditText EmailEditText;
private TextView date;
private int month;//private within class
private int day;
private int year;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addcontacts);
setUpViews();
Calendar calendar =Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
Date today = calendar.getTime();
DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM);
String cs = df.format(today);
date.setText(cs);
}
public void saveClickHandler(View v){
String ContactsScore;
ContactsScore= NameEditText.getText().toString();
int name = Integer.parseInt(ContactsScore);
ContactsScore= PhoneEditText.getText().toString();
int Phone = Integer.parseInt(ContactsScore);
ContactsScore = EmailEditText.getText().toString();
int Email = Integer.parseInt(ContactsScore);
Log.d("EnterContacts" , "I hear the Save Button");
if( isValid(name) && isValid(Phone) && isValid(Email) ) {
Contacts contacts;
Date dateofGames= new GregorianCalendar(year,month,day).getTime();
contacts = new Contacts (name , Phone , Email, dateofGames);
ContactsActivityApplication app = (ContactsActivityApplication) getApplication();
//might be wrong
Log.d("DeBUGGING", "app is this type: " + app.getClass().getName());
//need add the function addBowlingScores
app.addallContacts(contacts);
Toast.makeText(getApplicationContext(), "Your Contact has been Saved!", Toast.LENGTH_SHORT).show();
}
else{
//pop up a dialog that data is invalid
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Invalid Phone Number")
.setMessage("Phone numbers cannot have more than 8 numbers")
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
private boolean isValid(int phone) {
if(phone <= 0 && phone >=100000000)
return true;
return false;
// TODO Auto-generated method stub
}
private void setUpViews()
{
ExitButton = (Button) findViewById(R.id.BtnExit);
saveButton =(Button) findViewById(R.id.BtnSave);
NameEditText= (EditText) findViewById(R.id.NameEditText);
PhoneEditText= (EditText) findViewById(R.id.PhoneEditText);
EmailEditText= (EditText) findViewById(R.id.EmailEditText);
date = (TextView) findViewById(R.id.DateTextView);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.addcontacts, menu);
return true;
}
}
MyContactsSQL:
package com.Elson.ProjectVersion;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteException;
import android.util.Log;
public class MyContactSQL extends SQLiteOpenHelper {
public static final String DB_NAME ="MyContactSQL.SQLite";
public static final int DB_VERSION = 1;
public static String CONTACT_LIST_TABLE = "ContactListTable";
public static String RECORD_ID ="ID";
public static String NAME = "NAME";
public static String PHONE_NUMBER="PhoneNumber";
public MyContactSQL(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase contactListDB) {
String sqlStatement = "create table " + CONTACT_LIST_TABLE
+ " ("
+ RECORD_ID + " integer primary key autoincrement not null,"
+ NAME + " long,"
+ PHONE_NUMBER +" integer"
+");";
Log.d("Contact Database", sqlStatement);
contactListDB.execSQL(sqlStatement);
}
#Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
}
}
HistoryActivity:
import java.util.ArrayList;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class HistoryActivity extends ListActivity {
Bundle savedInstanceState;
private ArrayList <Contacts> allContacts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.savedInstanceState = savedInstanceState;
setContentView(R.layout.history_layout);
//get data from the App
ContactsActivityApplication app = (ContactsActivityApplication) getApplication();
allContacts = app.getAllContacts();
//View --- Adapter ------ Data
setListAdapter(
new ArrayAdapter<Contacts> (this, R.layout.history_row,
allContacts
));
ListView listView = this.getListView();
listView.setOnItemClickListener(
new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
verifyDeleteRow(position);
Log.d("DEBUG", "I hear item selected:" + position);
// TODO Auto-generated method stub
}
}
);
}
private void verifyDeleteRow(final int position){
//pop up a dialog to confirm delete row
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Delete this Series?")
.setMessage("Do you want to delete this data?" + allContacts.get(position))
.setCancelable(false)
.setNegativeButton("NO! Leave it there!",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
})
.setPositiveButton("Delete",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Contacts toDelete = allContacts.get(position);
ContactsActivityApplication app = (ContactsActivityApplication) getApplication();
app.deleteBowlingScores(toDelete);
// TODO Auto-generated method stub
onCreate(savedInstanceState);
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
The date object you are passing to df.format is NULL, which is causing NullPointerException
public String toString() {
String result;
// "ID" + id +" "
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
result = df.format(date) + "" + name + "" + Phone ;
^^^^^^^^^^^^^^^
date object is null above
return result;
}
you need to do null check on the date instance
if(date != null) {
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
result = df.format(date) + "" + name + "" + Phone ;
}
else {
result = name + "" + Phone ;
}
I think the date varibale is not initialized when you are trying to parse using it here:
result = df.format(date) + "" + name + "" + Phone ;
So make sure you have initialized it before passing it to parse.
And please only post the code relevant to your problem. Not the entire code, unless required. It creates a lot of confusion

Categories