TitleView bug I don't understand - java

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);

Related

Value on Spinner can't post to databae mySql

logcat doesn't give me a specific error, it only shows the error location, which is on line 155 {id_status = spStatus.getSelectedItem().toString();}
I don't know the right keyword to solve the error. I've been browsing, and I think this is the same as the tutorial I followed. where is my mistake? give me more detailed instructions
my java like this:
package src.bkkpost.loker;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Calendar;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import src.bkkpost.MainActivity;
import src.bkkpost.R;
import src.bkkpost.loker.adapter.AdapterStatus;
import src.bkkpost.model.Value;
import src.bkkpost.util.BaseApiService;
import src.bkkpost.util.SharedPrefManager;
import src.bkkpost.util.UtilsApi;
public class UpdateLoker extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
//string spinner kelamin
String[] idStatus = {"10", "20"};
String[] nama_status = {"Buka", "Tutup"};
//string spinner kelamin
String[] id_kelamin = {"5001", "5002", "5003"};
String[] nama_kelamin = {"Pria/Wanita", "Pria", "Wanita"};
//string spinner pendidikan
String[] pendidikan_id = {"3001", "3002", "3003", "30004", "3005", "3006", "3007"};
String[] nama_pendidikan = {"SD", "SMP", "SMA", "SMK ", "Diploma/(D3)", "Sarjana/(S1)", "Master/(S2)"};
//string spinner pendidikan
String[] jurusan_id = {"30001", "300301", "300302", "3000401", "3000402", "3000403", "3000404",
"3000405", "3000406", "3000407", "3000408", "3000409", "3000410", "3000411", "3000412", "3000413", "3000414",
"3000415", "300501", "300502", "300503", "300504", "300505", "300506", "300075"};
String[] nama_jurusan = {"Semua Jurusan", "IPA", "IPS", "Administrasi Perkantoran ", "Akuntansi ", "ANalisis Kimia ",
"Animasi ", "Broadcasting ", "Elektronik ", "Farmasi ", "Multimedia ", "Otomotif ", "Pariwisata ", "Pemasaran ",
"Perbankan ", "Perhotelan", "Tata Boga ", "Tata Busana ", "Perpajakan(D3/S1) ", "Broadcasting(D3/S1)", "Teknik Mesin(D3/S1)",
"Pariwisata(D3/S1)", "Sekretaris (D3/S1)", "Hubungan Masyarakat (D3/S1)", "Akuntansi(D3/S1) "};
AutoCompleteTextView date;
DatePickerDialog datePickerDialog;
BaseApiService mApiservice;
ProgressDialog loading;
Context mContex;
SharedPrefManager sharedPrefManager;
public static final String URL = "http://192.168.43.164/gokerja/";
private ProgressDialog progress;
String bkk_id, posisi, nama_pt, alamat_pt, waktu_buka, id_status;
#BindView(R.id.post_btn_upload)
Button btnUpload;
#BindView(R.id.post_bkk_id)
TextView tvBkkid;
#BindView(R.id.post_posisi)
AutoCompleteTextView etPosisi;
#BindView(R.id.post_namaperusahaan)
AutoCompleteTextView etNamaperusahan;
#BindView(R.id.post_alamat_pt)
AutoCompleteTextView etAlamat;
#BindView(R.id.post_tanggal)
AutoCompleteTextView etTangggal;
#BindView(R.id.post_spin_statusup)
Spinner spStatus;
#OnClick(R.id.post_btn_upload)
void daftar() { }
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loker_update_loker);
ButterKnife.bind(this);
sharedPrefManager = new SharedPrefManager(this);
tvBkkid.setText(sharedPrefManager.getSPNama());
mApiservice = UtilsApi.getAPIService();
mContex = this;
date = (AutoCompleteTextView) findViewById(R.id.post_tanggal);
date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final java.util.Calendar c = java.util.Calendar.getInstance();
int mYear = c.get(java.util.Calendar.YEAR);
int mMont = c.get(Calendar.MONTH);
int mDay = c.get(java.util.Calendar.DAY_OF_MONTH);
//date picker dialog
datePickerDialog = new DatePickerDialog(UpdateLoker.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int month, int dayOfMonth) {
date.setText(year + "-"
+ (month + 1) + "-" + dayOfMonth);
}
}, mYear, mMont, mDay);
datePickerDialog.show();
}
});
//get spinner status
final Spinner spinnerStatus = (Spinner) findViewById(R.id.post_spin_statusup);
spinnerStatus.setOnItemSelectedListener(this);
AdapterStatus adapterStatus = new AdapterStatus(getApplicationContext(), idStatus);
spinnerStatus.setAdapter(adapterStatus);
progress = new ProgressDialog(this);
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (etPosisi.getText().toString().equals("")) {
etPosisi.setError("Posisi harus di isi");
} else if (etNamaperusahan.getText().toString().equals("")) {
etNamaperusahan.setError("Perusahaan harus di isi");
} else if (etAlamat.getText().toString().equals("")) {
etAlamat.setError("alamat harus di isi");
} else {
//Untuk menampilkan progress dialog
progress.setCancelable(false);
progress.setMessage("Loading...");
progress.show();
bkk_id = tvBkkid.getText().toString();
posisi = etPosisi.getText().toString();
nama_pt = etNamaperusahan.getText().toString();
alamat_pt = etAlamat.getText().toString();
waktu_buka = etTangggal.getText().toString();
id_status = spStatus.getSelectedItem().toString();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
BaseApiService api = retrofit.create(BaseApiService.class);
Call<Value> call = api.post_loker(bkk_id, posisi, nama_pt, alamat_pt, waktu_buka, id_status);
call.enqueue(new Callback<Value>() {
#Override
public void onResponse(Call<Value> call, Response<Value> response) {
String value = response.body().getValue();
String message = response.body().getMessage();
progress.dismiss();
if (value.equals("1")) {
AlertDialog.Builder alert = new AlertDialog.Builder(UpdateLoker.this);
alert.setTitle("Confirm");
alert.setMessage("Iklan Lowongan kerja telah berhasil dibuat");
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(mContex, MainActivity.class));
dialog.dismiss();
}
});
alert.show();
} else {
AlertDialog.Builder alert = new AlertDialog.Builder(UpdateLoker.this);
alert.setTitle("Confirm");
alert.setMessage("Terjadi Kesalahan Jaringan, Iklan gagal dibuat");
alert.setPositiveButton("Coba Lagi", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(mContex, UpdateLoker.class));
dialog.dismiss();
}
});
alert.show();
}
}
#Override
public void onFailure(Call<Value> call, Throwable t) {
t.printStackTrace();
progress.dismiss();
AlertDialog.Builder alert = new AlertDialog.Builder(UpdateLoker.this);
alert.setTitle("Error 301");
alert.setMessage("Terjadi kesalahan jaringan, Iklan gagal dibuat");
alert.setPositiveButton("Coba Lagi", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.show();
//Toast.makeText(UpdateLoker.this, "semelekete", Toast.LENGTH_SHORT).show();
}
});
}
}
});
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
this my Logcat
09-04 17:13:15.904 16015-16015/src.bkkpost D/AndroidRuntime: Shutting down VM
09-04 17:13:15.904 16015-16015/src.bkkpost W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x419f3d58)
--------- beginning of /dev/log/system
09-04 17:13:15.904 16015-16015/src.bkkpost E/AndroidRuntime: FATAL EXCEPTION: main
Process: src.bkkpost, PID: 16015
java.lang.NullPointerException
at src.bkkpost.loker.UpdateLoker$2.onClick(UpdateLoker.java:155)
at android.view.View.performClick(View.java:4444)
at android.view.View$PerformClick.run(View.java:18457)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5113)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
at dalvik.system.NativeStart.main(Native Method)

How to get recyclerview image data in mainactivity

What i am trying to do is getting images from gallery and camera and placing it in an recyclerview.
Now main parts comes after image is now placedd in the recyclerview ,
but can anyone just tell me how can i get back these images shown in the recyclerview back to the mainActivity only when i click my upload button.
Thank you in advance.
My Main Activity.
package www.welkinfort.com.pphc;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import butterknife.ButterKnife;
public class XenImageUploading extends AppCompatActivity implements AdapterView.OnItemSelectedListener, View.OnClickListener {
ArrayAdapter<String> des_dataAdapter;
ArrayList<String> discription_list = new ArrayList<>();
//#BindView(R.id.selct_prject_spinner)
Spinner select_pro_spn;
TextView datetextTextView;
Calendar myCalendar;
static Bitmap rotatedBitmap;
static Bitmap finalrotatedBitmap;
DatePickerDialog.OnDateSetListener date;
static final int REQUEST_TAKE_PHOTO = 1;
private int SELECT_FILE = 2;
private static String bitmap_overdraw_str;
private static ImageButton cameraclick;
private static ImageButton galleryclick;
private static ImageButton videoclick;
private static String mCurrentPhotoPath;
private static RecyclerView recyclerView;
ArrayList<Data_Model> arrayList;
ImageView image_view;
MyAdapter m;
Bitmap finalbitmap;
static String clickpath;
int i = 0;
String path ;
private static final String TAG = "XenImageUploading";
static File photoFile_1 = null;
private String userChoosenTask;
private Uri fileUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.xen_image_upload);
ButterKnife.bind(this);
setTitle("XEN IMAGE UPLOAD");
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
cameraclick = (ImageButton) findViewById(R.id.camera_btn);
galleryclick = (ImageButton) findViewById(R.id.gallery_btn);
image_view = (ImageView) findViewById(R.id.image_view);
arrayList = new ArrayList<>();
Log.d("oncreate", "set adapter");
bitmap_overdraw_str = "Lat:" + "aaaaaaaa" + "\nLong:" + "aaaaaaaa" + "\nDate:" + "aaaaaaaa";
recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
///////////////////////////////////////////////////////////////////
//select_pro_spn = (Spinner) findViewById(R.id.selct_prject_spinner);
//datetextTextView = (TextView) findViewById(R.id.selctdate__txtv);
discription_list.add("Traffic light broken/not working");
discription_list.add("Traffic light pole hit by vehicle");
discription_list.add("No electricity connection");
discription_list.add("Traffic light not visible/partially visible");
// select_pro_spn.setOnItemSelectedListener(this);
// Creating adapter for spinner
des_dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, discription_list);
// Drop down layout style - list view with radio button
des_dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
// select_pro_spn.setAdapter(des_dataAdapter);
myCalendar = Calendar.getInstance();
date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabel();
}
};
// datetextTextView.setOnClickListener(new View.OnClickListener() {
//
// #Override
// public void onClick(View v) {
// // TODO Auto-generated method stub
// new DatePickerDialog(XenImageUploading.this, date, myCalendar
// .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
// myCalendar.get(Calendar.DAY_OF_MONTH)).show();
// }
// });
cameraclick.setOnClickListener(this);
galleryclick.setOnClickListener(this);
recyclerView.setOnClickListener(this);
}
private void updateLabel() {
String myFormat = "MM-dd-yyyy"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
datetextTextView.setText(sdf.format(myCalendar.getTime()));
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (parent.getId()) {
// case R.id.selct_prject_spinner:
// String selected_intersection = parent.getSelectedItem().toString();
// Log.e("Selected item ", selected_intersection);
// //parent.notifyAll();
// break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.camera_btn:
selectImage();
break;
case R.id.recycler_view:
getImageall();
break;
case R.id.gallery_btn:
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
i.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(i, SELECT_FILE);
break;
}
}
private void getImageall() {
}
private void selectImage() {
takepicture();
}
public void takepicture() {
Log.d(TAG, "takepicture");
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
try {
photoFile_1 = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile_1 != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile_1));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK && null != data) {
// Save Image To Gallery
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
////////////////setting image to adapter on capturing///////////////////////////
clickpath = mCurrentPhotoPath;
Bitmap bitmap = BitmapUtility.decodeSampledBitmapFromResource(clickpath, 560, 300);
setCameraDisplayOrientation(bitmap);
try {
FileOutputStream fos = new FileOutputStream(photoFile_1);
finalrotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
Data_Model data_model = new Data_Model();
data_model.setImage(finalrotatedBitmap);
image_view.setImageBitmap(finalrotatedBitmap);
arrayList.add(data_model);
m = new MyAdapter(this, arrayList);
recyclerView.setAdapter(m);
m.notifyDataSetChanged();
}
if (requestCode == SELECT_FILE && resultCode == RESULT_OK && null != data) {
InputStream stream = null;
Uri uri = data.getData();
//for (int i =0 ; i<numberOfImages ;i++){
getImagePath(uri);
Data_Model data_model = new Data_Model();
data_model.setImage(finalbitmap);
image_view.setImageBitmap(finalbitmap);
arrayList.add(data_model);
m = new MyAdapter(this, arrayList);
recyclerView.setAdapter(m);
m.notifyDataSetChanged();
// }
}
}
public String getImagePath(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
String document_id = cursor.getString(0);
document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
cursor.close();
cursor = getContentResolver().query(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
cursor.moveToFirst();
path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
finalbitmap = BitmapUtility.decodeSampledBitmapFromResource(path, 560, 300);
//targetImage = (ImageView)findViewById(R.id.imageView1);
image_view.setImageBitmap(finalbitmap);
return path;
}
public static void setCameraDisplayOrientation(Bitmap fileresult) {
Log.e(TAG, "setCameraDisplayOrientation");
BitmapFactory.Options bounds = new BitmapFactory.Options();
bounds.inJustDecodeBounds = true;
BitmapFactory.decodeFile(clickpath, bounds);
BitmapFactory.Options opts = new BitmapFactory.Options();
Bitmap bm = BitmapFactory.decodeFile(clickpath, opts);
ExifInterface exif = null;
try {
exif = new ExifInterface(clickpath);
} catch (IOException e) {
e.printStackTrace();
}
String orientString = exif.getAttribute(ExifInterface.TAG_ORIENTATION);
int orientation = orientString != null ? Integer.parseInt(orientString) : ExifInterface.ORIENTATION_NORMAL;
int rotationAngle = 0;
if (orientation == ExifInterface.ORIENTATION_ROTATE_90) rotationAngle = 90;
if (orientation == ExifInterface.ORIENTATION_ROTATE_180) rotationAngle = 180;
if (orientation == ExifInterface.ORIENTATION_ROTATE_270) rotationAngle = 270;
Matrix matrix = new Matrix();
matrix.setRotate(rotationAngle, (float) bm.getWidth() / 2, (float) bm.getHeight() / 2);
rotatedBitmap = Bitmap.createBitmap(bm, 0, 0, bounds.outWidth, bounds.outHeight, matrix, true);
finalrotatedBitmap = AddTextonBitmap.textAsBitmap(rotatedBitmap, bitmap_overdraw_str);
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
}
Adapter class
package www.welkinfort.com.pphc;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.util.ArrayList;
/**
* Created by Admin on 13-Jul-17.
*/
class MyAdapter extends RecyclerView.Adapter<MyAdapter.Myviewholder> {
private static final String TAG = "Adapter";
static Data_Model m;
XenImageUploading xenImageUploading;
ArrayList<Data_Model> arrayList;
private Context mContext;
public MyAdapter(XenImageUploading xenImageUploading, ArrayList<Data_Model> arrayList) {
this.arrayList = arrayList;
this.xenImageUploading = xenImageUploading;
}
#Override
public Myviewholder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.abc, parent, false);
Myviewholder myviewholder = new Myviewholder(view);
Log.d("myactivty ", "oncreateViewHolder");
return myviewholder;
}
#Override
public void onBindViewHolder(final Myviewholder holder, final int position) {
m = arrayList.get(position);
Log.d(" myactivty", "onBindviewholder" + position);
holder.imageView.setImageBitmap(m.getImage());
}
#Override
public int getItemCount() {
return arrayList == null ? 0 : arrayList.size();
}
public class Myviewholder extends RecyclerView.ViewHolder {
// public View view;
public ImageView imageView;
public Myviewholder(View itemView) {
super(itemView);
imageView = (ImageView) itemView.findViewById(R.id.image);
}
}
}
try this create one method in your adapter like this
public ArrayList<Data_Model> getArray() {
return arrayList;
}
now on your button click just call this method
upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<Data_Model> arrayList= adapter.getArray();
}
});
ask me in case of any query

volley Image loader library Error Excpetion

Hello everyone i was trying to make Custom list of view with volley feed following this tutorial: http://www.androidhive.info/2014/06/android-facebook-like-custom-listview-feed-using-volley/
but i got an error with the image loader i can't get the hang of it , i hope if someone can tell me what is the problem and how should i solve it in the first place :)
thanks in advance
this is the error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.asro9.customfeed/com.example.asro9.customfeed.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at Adapter.FeedListAdapter.<init>(FeedListAdapter.java:33)
at com.example.asro9.customfeed.MainActivity.onCreate(MainActivity.java:50)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
            at android.app.ActivityThread.access$800(ActivityThread.java:135)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5001)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
            at dalvik.system.NativeStart.main(Native Method)
i will show up the classes i have created !
FeedListAdapter.java
package Adapter;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.text.Html;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.example.asro9.customfeed.FeedImageView;
import com.example.asro9.customfeed.R;
import CustomFeed.AppController;
import Data.FeedItem;
/**
* Created by asro9 on 3/7/2016.
*/
public class FeedListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<FeedItem> feedItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public FeedListAdapter(Activity activity, List<FeedItem> feedItems) {
this.activity = activity;
this.feedItems = feedItems;
}
#Override
public int getCount() {
return feedItems.size();
}
#Override
public Object getItem(int location) {
return feedItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.feed_item, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView timestamp = (TextView) convertView
.findViewById(R.id.timestamp);
TextView statusMsg = (TextView) convertView
.findViewById(R.id.txtStatusMsg);
TextView url = (TextView) convertView.findViewById(R.id.txtUrl);
NetworkImageView profilePic = (NetworkImageView) convertView
.findViewById(R.id.profilePic);
FeedImageView feedImageView = (FeedImageView) convertView
.findViewById(R.id.feedImage1);
FeedItem item = feedItems.get(position);
name.setText(item.getName());
// Converting timestamp into x ago format
CharSequence timeAgo = DateUtils.getRelativeTimeSpanString(
Long.parseLong(item.getTimeStamp()),
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
timestamp.setText(timeAgo);
// Chcek for empty status message
if (!TextUtils.isEmpty(item.getStatus())) {
statusMsg.setText(item.getStatus());
statusMsg.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
statusMsg.setVisibility(View.GONE);
}
// Checking for null feed url
if (item.getUrl() != null) {
url.setText(Html.fromHtml("<a href=\"" + item.getUrl() + "\">"
+ item.getUrl() + "</a> "));
// Making url clickable
url.setMovementMethod(LinkMovementMethod.getInstance());
url.setVisibility(View.VISIBLE);
} else {
// url is null, remove from the view
url.setVisibility(View.GONE);
}
// user profile pic
profilePic.setImageUrl(item.getProfilePic(), imageLoader);
// Feed image
if (item.getImge() != null) {
feedImageView.setImageUrl(item.getImge(), imageLoader);
feedImageView.setVisibility(View.VISIBLE);
feedImageView
.setResponseObserver(new FeedImageView.ResponseObserver() {
#Override
public void onError() {
}
#Override
public void onSuccess() {
}
});
} else {
feedImageView.setVisibility(View.GONE);
}
return convertView;
}
}
FeedImageVie.java
package com.example.asro9.customfeed;
import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageContainer;
import com.android.volley.toolbox.ImageLoader.ImageListener;
/**
* Created by asro9 on 3/7/2016.
*/
public class FeedImageView extends ImageView {
public interface ResponseObserver {
public void onError();
public void onSuccess();
}
private ResponseObserver mObserver;
public void setResponseObserver(ResponseObserver observer) {
mObserver = observer;
}
/**
* The URL of the network image to load
*/
private String mUrl;
/**
* Resource ID of the image to be used as a placeholder until the network
* image is loaded.
*/
private int mDefaultImageId;
/**
* Resource ID of the image to be used if the network response fails.
*/
private int mErrorImageId;
/**
* Local copy of the ImageLoader.
*/
private ImageLoader mImageLoader;
/**
* Current ImageContainer. (either in-flight or finished)
*/
private ImageContainer mImageContainer;
public FeedImageView(Context context) {
this(context, null);
}
public FeedImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public FeedImageView(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}
/**
* Sets URL of the image that should be loaded into this view. Note that
* calling this will immediately either set the cached image (if available)
* or the default image specified by
* {#link VolleyImageView#setDefaultImageResId(int)} on the view.
*
* NOTE: If applicable, {#link VolleyImageView#setDefaultImageResId(int)}
* and {#link VolleyImageView#setErrorImageResId(int)} should be called
* prior to calling this function.
*
* #param url
* The URL that should be loaded into this ImageView.
* #param imageLoader
* ImageLoader that will be used to make the request.
*/
public void setImageUrl(String url, ImageLoader imageLoader) {
mUrl = url;
mImageLoader = imageLoader;
// The URL has potentially changed. See if we need to load it.
loadImageIfNecessary(false);
}
/**
* Sets the default image resource ID to be used for this view until the
* attempt to load it completes.
*/
public void setDefaultImageResId(int defaultImage) {
mDefaultImageId = defaultImage;
}
/**
* Sets the error image resource ID to be used for this view in the event
* that the image requested fails to load.
*/
public void setErrorImageResId(int errorImage) {
mErrorImageId = errorImage;
}
/**
* Loads the image for the view if it isn't already loaded.
*
* #param isInLayoutPass
* True if this was invoked from a layout pass, false otherwise.
*/
private void loadImageIfNecessary(final boolean isInLayoutPass) {
final int width = getWidth();
int height = getHeight();
boolean isFullyWrapContent = getLayoutParams() != null
&& getLayoutParams().height == LayoutParams.WRAP_CONTENT
&& getLayoutParams().width == LayoutParams.WRAP_CONTENT;
// if the view's bounds aren't known yet, and this is not a
// wrap-content/wrap-content
// view, hold off on loading the image.
if (width == 0 && height == 0 && !isFullyWrapContent) {
return;
}
// if the URL to be loaded in this view is empty, cancel any old
// requests and clear the
// currently loaded image.
if (TextUtils.isEmpty(mUrl)) {
if (mImageContainer != null) {
mImageContainer.cancelRequest();
mImageContainer = null;
}
setDefaultImageOrNull();
return;
}
// if there was an old request in this view, check if it needs to be
// canceled.
if (mImageContainer != null && mImageContainer.getRequestUrl() != null) {
if (mImageContainer.getRequestUrl().equals(mUrl)) {
// if the request is from the same URL, return.
return;
} else {
// if there is a pre-existing request, cancel it if it's
// fetching a different URL.
mImageContainer.cancelRequest();
setDefaultImageOrNull();
}
}
// The pre-existing content of this view didn't match the current URL.
// Load the new image
// from the network.
ImageContainer newContainer = mImageLoader.get(mUrl,
new ImageListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (mErrorImageId != 0) {
setImageResource(mErrorImageId);
}
if (mObserver != null) {
mObserver.onError();
}
}
#Override
public void onResponse(final ImageContainer response,
boolean isImmediate) {
// If this was an immediate response that was delivered
// inside of a layout
// pass do not set the image immediately as it will
// trigger a requestLayout
// inside of a layout. Instead, defer setting the image
// by posting back to
// the main thread.
if (isImmediate && isInLayoutPass) {
post(new Runnable() {
#Override
public void run() {
onResponse(response, false);
}
});
return;
}
int bWidth = 0, bHeight = 0;
if (response.getBitmap() != null) {
setImageBitmap(response.getBitmap());
bWidth = response.getBitmap().getWidth();
bHeight = response.getBitmap().getHeight();
adjustImageAspect(bWidth, bHeight);
} else if (mDefaultImageId != 0) {
setImageResource(mDefaultImageId);
}
if (mObserver != null) {
mObserver.onSuccess();
}
}
});
// update the ImageContainer to be the new bitmap container.
mImageContainer = newContainer;
}
private void setDefaultImageOrNull() {
if (mDefaultImageId != 0) {
setImageResource(mDefaultImageId);
} else {
setImageBitmap(null);
}
}
#Override
protected void onLayout(boolean changed, int left, int top, int right,
int bottom) {
super.onLayout(changed, left, top, right, bottom);
loadImageIfNecessary(true);
}
#Override
protected void onDetachedFromWindow() {
if (mImageContainer != null) {
// If the view was bound to an image request, cancel it and clear
// out the image from the view.
mImageContainer.cancelRequest();
setImageBitmap(null);
// also clear out the container so we can reload the image if
// necessary.
mImageContainer = null;
}
super.onDetachedFromWindow();
}
#Override
protected void drawableStateChanged() {
super.drawableStateChanged();
invalidate();
}
/*
* Adjusting imageview height
* */
private void adjustImageAspect(int bWidth, int bHeight) {
LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams();
if (bWidth == 0 || bHeight == 0)
return;
int swidth = getWidth();
int new_height = 0;
new_height = swidth * bHeight / bWidth;
params.width = swidth;
params.height = new_height;
setLayoutParams(params);
}
}
the MainActivity.java
package com.example.asro9.customfeed;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ListView;
import org.json.JSONException;
import java.util.ArrayList;
import java.util.List;
import Adapter.FeedListAdapter;
import CustomFeed.AppController;
import Data.FeedItem;
import com.android.volley.Cache;
import com.android.volley.Cache.Entry;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import java.io.UnsupportedEncodingException;
import org.json.JSONArray;
import org.json.JSONObject;
public class MainActivity extends Activity {
private static final String TAG = MainActivity.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
private String URL_FEED = "http://api.androidhive.info/feed/feed.json";
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
feedItems = new ArrayList<FeedItem>();
listAdapter = new FeedListAdapter(this, feedItems);
listView.setAdapter(listAdapter);
// These two lines not needed,
// just to get the look of facebook (changing background color & hiding the icon)
getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3b5998")));
getActionBar().setIcon(
new ColorDrawable(getResources().getColor(android.R.color.transparent)));
// We first check for cached request
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(URL_FEED);
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
URL_FEED, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
}
/**
* Parsing json reponse and passing the data to feed view list adapter
* */
private void parseJsonFeed(JSONObject response) {
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
// notify data changes to list adapater
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
AppController.java
package CustomFeed;
import android.app.Application;
import android.text.TextUtils;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import Volly.LruBitmapCache;
/**
* Created by asro9 on 3/9/2016.
*/
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
LruBitmapCache mLruBitmapCache;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
getLruBitmapCache();
mImageLoader = new ImageLoader(this.mRequestQueue, mLruBitmapCache);
}
return this.mImageLoader;
}
public LruBitmapCache getLruBitmapCache() {
if (mLruBitmapCache == null)
mLruBitmapCache = new LruBitmapCache();
return this.mLruBitmapCache;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
feeditem.java
package Data;
/**
* Created by asro9 on 3/7/2016.
*/
public class FeedItem {
private int id;
private String name, status, image, profilePic, timeStamp, url;
public FeedItem() {
}
public FeedItem(int id, String name, String image, String status,
String profilePic, String timeStamp, String url) {
super();
this.id = id;
this.name = name;
this.image = image;
this.status = status;
this.profilePic = profilePic;
this.timeStamp = timeStamp;
this.url = url;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImge() {
return image;
}
public void setImge(String image) {
this.image = image;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getProfilePic() {
return profilePic;
}
public void setProfilePic(String profilePic) {
this.profilePic = profilePic;
}
public String getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
volley cache
LruBitmapCache :
package Volly;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import com.android.volley.toolbox.ImageLoader.ImageCache;
/**
* Created by asro9 on 3/7/2016.
*/
public class LruBitmapCache extends LruCache<String, Bitmap> implements
ImageCache {
public static int getDefaultLruCacheSize() {
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;
return cacheSize;
}
public LruBitmapCache() {
this(getDefaultLruCacheSize());
}
public LruBitmapCache(int sizeInKiloBytes) {
super(sizeInKiloBytes);
}
#Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes() * value.getHeight() / 1024;
}
#Override
public Bitmap getBitmap(String url) {
return get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
put(url, bitmap);
}
}
The error is self explanatory, the crash is here:
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
getInstance is returning null.

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

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.

Android RSS Feed

i am creating an app for my final year project at uni.. i am trying to get an rss feed working.. My issue at the moment is that i created a project (RSSActivity) and got the RSS feeds to work. I then copy and pasted all the files (5 classes and 2 layouts) into the appropriate places. There were a few errors: R cannot be found, but this was easily fixed by changing the package to that of the project (football_app). What i am tring to do is be able to click on a button called 'News' and the news appears.. the problem that i am have is that the when i now click on the 'News' button, it say 'Unfortunately football app has stopped'.. i have tried every single class in the intent, and changed the intent activity name appropriately.. can anyone help me.. code below...
/////////////// HttpFeedSource.java
package com.julian.football_app;
import java.util.ArrayList;
import java.util.List;
class HttpFeedSource implements FeedSource {
protected static final String URL = "http://www.skysports.com/rss/0,20514,11661,00.xml";
public List<RSSItem> getFeed() {
List<RSSItem> itemList = new ArrayList<RSSItem>();
NewsParser parser = new NewsParser(URL);
parser.parse();
NewsParser.RssFeed feed = parser.getFeed();
for (NewsParser.Item i : feed.getItems()) {
itemList.add(new RSSItem(i.getUrl(), i.getTitle(), i.getDescription(), i.getimageUrl()));
}
return itemList;
}
}
////////////////////// FeedSource.java
package com.julian.football_app;
import java.util.List;
interface FeedSource {
List<RSSItem> getFeed();
}
<code>
/////////////////////////////////////////////////////////////////////////////////////////// //MockFeedSource.java
package com.julian.football_app;
import java.util.ArrayList;
import java.util.List;
class MockFeedSource implements FeedSource {
public List<RSSItem> getFeed() {
RSSItem item;
final List<RSSItem> items = new ArrayList<RSSItem>();
item = new RSSItem("Android Workshop er gøy", "http://www.ap.no", " this is the desc", "");
items.add(item);
item = new RSSItem("Android Workshop er gøy 2", "http://www.ap.no", "this is the desc", "");
items.add(item);
item = new RSSItem("Android Workshop er gøy3", "http://www.ap.no", "this is the desc", "");
items.add(item);
return items;
}
}
</code>
/////////////////////////////////////////////////////////////////////////////////////////// NewsParser.java
package com.julian.football_app;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.InputStream;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
class NewsParser extends DefaultHandler {
public static SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH);
private String urlString;
private RssFeed rssFeed;
private StringBuilder text;
private Item item;
private boolean imgStatus;
public NewsParser(String url) {
this.urlString = url;
this.text = new StringBuilder();
}
public void parse() {
InputStream urlInputStream = null;
SAXParserFactory spf;
SAXParser sp;
try {
URL url = new URL(this.urlString);
urlInputStream = url.openConnection().getInputStream();
InputSource is = new InputSource(urlInputStream);
is.setEncoding("ISO-8859-1");
spf = SAXParserFactory.newInstance();
if (spf != null) {
sp = spf.newSAXParser();
sp.parse(is, this);
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
try {
if (urlInputStream != null) urlInputStream.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public RssFeed getFeed() {
return (this.rssFeed);
}
public void startElement(String uri, String localName, String qName,
Attributes attributes) {
if (qName.equalsIgnoreCase("channel"))
this.rssFeed = new RssFeed();
else if (qName.equalsIgnoreCase("item") && (this.rssFeed != null)) {
this.item = new Item();
this.rssFeed.addItem(this.item);
} else if (qName.equalsIgnoreCase("image") && (this.rssFeed != null))
this.imgStatus = true;
}
public void endElement(String uri, String localName, String qName) {
if (this.rssFeed == null)
return;
if (qName.equalsIgnoreCase("item"))
this.item = null;
else if (qName.equalsIgnoreCase("image"))
this.imgStatus = false;
else if (qName.equalsIgnoreCase("title")) {
if (this.item != null) this.item.title = this.text.toString().trim();
else if (this.imgStatus) this.rssFeed.imageTitle = this.text.toString().trim();
else this.rssFeed.title = this.text.toString().trim();
} else if (qName.equalsIgnoreCase("link")) {
if (this.item != null) this.item.link = this.text.toString().trim();
else if (this.imgStatus) this.rssFeed.imageLink = this.text.toString().trim();
else this.rssFeed.link = this.text.toString().trim();
} else if (qName.equalsIgnoreCase("description")) {
if (this.item != null) this.item.description = this.text.toString().trim();
else this.rssFeed.description = this.text.toString().trim();
} else if (qName.equalsIgnoreCase("url") && this.imgStatus)
this.rssFeed.imageUrl = this.text.toString().trim();
else if (qName.equalsIgnoreCase("language"))
this.rssFeed.language = this.text.toString().trim();
else if (qName.equalsIgnoreCase("generator"))
this.rssFeed.generator = this.text.toString().trim();
else if (qName.equalsIgnoreCase("copyright"))
this.rssFeed.copyright = this.text.toString().trim();
else if (qName.equalsIgnoreCase("pubDate") && (this.item != null)) {
try {
this.item.pubDate = sdf.parse(this.text.toString().trim());
} catch (ParseException e) {
throw new RuntimeException();
}
} else if (qName.equalsIgnoreCase("category") && (this.item != null))
this.rssFeed.addItem(this.text.toString().trim(), this.item);
this.text.setLength(0);
}
public void characters(char[] ch, int start, int length) {
this.text.append(ch, start, length);
}
public static class RssFeed {
public String title;
public String description;
public String link;
public String language;
public String generator;
public String copyright;
public String imageUrl;
public String imageTitle;
public String imageLink;
private ArrayList<Item> items;
private HashMap<String, ArrayList<Item>> category;
public void addItem(Item item) {
if (this.items == null)
this.items = new ArrayList<Item>();
this.items.add(item);
}
public void addItem(String category, Item item) {
if (this.category == null)
this.category = new HashMap<String, ArrayList<Item>>();
if (!this.category.containsKey(category))
this.category.put(category, new ArrayList<Item>());
this.category.get(category).add(item);
}
public ArrayList<Item> getItems() {
return items;
}
}
public static class Item implements Comparable<Item> {
public String title;
public String description;
public String link;
public Date pubDate;
private String url;
private String imageUrl;
public String toString() {
return (this.title + ": ");
}
public int compareTo(Item o) {
return (int) (o.pubDate.getTime() - pubDate.getTime());
}
public Date getPubDate() {
return pubDate;
}
public String getDescription() {
return description;
}
public String getTitle() {
return title;
}
public String getUrl() {
return url;
}
public String getimageUrl() {
return imageUrl;
}
}
}
package com.julian.football_app;
import com.julian.football_app.R;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
public class RSSActivity extends Activity {
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
ListView rssItemList = (ListView) findViewById(R.id.rssListview);
FeedSource feedSource = new HttpFeedSource();
RSSItemAdapter adapter = new RSSItemAdapter(this, R.layout.rssitem, feedSource.getFeed());
rssItemList.setAdapter(adapter);
}
}
/////////RssItem
package com.julian.football_app;
import java.util.Date;
class RSSItem {
private String url;
private String title;
private String description;
private String imageUrl;
private Date pubDate;
public RSSItem() {
}
public RSSItem(String url, String title, String description, String imageUrl) {
this.url = url;
this.title = title;
this.description = description;
this.imageUrl = imageUrl;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDesc(String description) {
this.description = description;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getimageUrl() {
return imageUrl;
}
public void setpubDate(Date pubDate){
this.pubDate = pubDate;
}
public Date getpubDate(){
return pubDate;
}
}
////////////////// RssItemAdaptor
package com.julian.football_app;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
import com.julian.football_app.R;
class RSSItemAdapter extends ArrayAdapter<RSSItem> {
private final Context context;
public RSSItemAdapter(Context context, int textViewResourceId,
List<RSSItem> items) {
super(context, textViewResourceId, items);
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.rssitem, null);
}
final RSSItem item = getItem(position);
TextView title = (TextView) v.findViewById(R.id.title);
TextView desc = (TextView) v.findViewById(R.id.description);
TextView url = (TextView) v.findViewById(R.id.url);
// this is what is viewed
title.setText(item.getTitle());
desc.setText(item.getDescription());
url.setText(item.getimageUrl());
return v;
}
}
///This is the button i want to display the Rss Feed
package com.julian.football_app;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Menu extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
//setting the buttons
Button btnews1 = (Button) findViewById(R.id.news_1);
btnews1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent news1intent = new Intent(Menu.this, news_1.class);
Menu.this.startActivity(news1intent);
}
});
Thank you for looking at my code... It would be much appreciated if someone could help me :) (i know its says news_1.class in the intent.. its only cuz i tried everything and went back to original state..)
These are the errors that appear in the LogCat:
03-23 13:54:16.118: E/AndroidRuntime(553): FATAL EXCEPTION: main
03-23 13:54:16.118: E/AndroidRuntime(553): at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1508)
03-23 13:54:16.118: E/AndroidRuntime(553): at android.app.Instrumentation.execStartActivity(Instrumentation.java:1384)
03-23 13:54:16.118: E/AndroidRuntime(553): at android.app.Activity.startActivityForResult(Activity.java:3190)
03-23 13:54:16.118: E/AndroidRuntime(553): at android.app.Activity.startActivity(Activity.java:3297)
03-23 13:54:16.118: E/AndroidRuntime(553): at com.julian.football_app.Menu$1.onClick(Menu.java:24)
03-23 13:54:16.118: E/AndroidRuntime(553): at android.view.View.performClick(View.java:3460)
03-23 13:54:16.118: E/AndroidRuntime(553): at android.view.View$PerformClick.run(View.java:13955)
03-23 13:54:16.118: E/AndroidRuntime(553): at android.os.Handler.handleCallback(Handler.java:605)
03-23 13:54:16.118: E/AndroidRuntime(553): at android.os.Handler.dispatchMessage(Handler.java:92)
03-23 13:54:16.118: E/AndroidRuntime(553): at android.os.Looper.loop(Looper.java:137)
03-23 13:54:16.118: E/AndroidRuntime(553): at android.app.ActivityThread.main(ActivityThread.java:4340)
03-23 13:54:16.118: E/AndroidRuntime(553): at java.lang.reflect.Method.invokeNative(Native Method)
03-23 13:54:16.118: E/AndroidRuntime(553): at java.lang.reflect.Method.invoke(Method.java:511)
03-23 13:54:16.118: E/AndroidRuntime(553): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
03-23 13:54:16.118: E/AndroidRuntime(553): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
03-23 13:54:16.118: E/AndroidRuntime(553): at dalvik.system.NativeStart.main(Native Method)
It sounds like the app is experiencing an exception. To find the cause you need to use LogCat to look at the exception details, which will show you where in your code there is a problem.
See how your application goes off the rails right around:
E/AndroidRuntime(553): at android.app.Activity.startActivity(Activity.java:3297) 03-23 13:54:16.118:
E/AndroidRuntime(553): at com.julian.football_app.Menu$1.onClick(Menu.java:24) 03-23 13:54:16.118:
My feeling is this isn't about the RSS at all. I think you need to fix the Intent navigation between the Activities in your application. You might try blocking out all the behavior from your Activities (comment out the interesting bits of onCreate() or whatever) and make sure you can navigate smoothly between Activities. Then re-enable the Activities and make sure they don't blow up when you enter them.
See also MH's comment about checking that all Activities are in your Manifest.
And take out that line that says:
import com.julian.football_app.R;
If you can't get your code to compile without including a .R, then you're doing something wrong. Try saving all the source files, deleting the contents of your gen directory, and selecting Project > Clean.

Categories