I tried to create a simple activity with a button and a textview that showing the date. The button should show the HijriDatePicker dialog when clicked. I tried to make it using ummalqura-calendar and by the dialog, i tried use the HijriDatePicker to create the dialog.
However, after many attempts, it doesn't work. Sometimes the activity will stop when I click the button, and sometimes it just crash. I tried already for many fail attempts.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 13658
com.github.msarhan.ummalqura.calendar.DateTimeException: Invalid Hijrah day of month: 31
at com.github.msarhan.ummalqura.calendar.HijrahChronology.getEpochDay(HijrahChronology.java:255)
at com.github.msarhan.ummalqura.calendar.HijrahChronology.toGregorian(HijrahChronology.java:697)
at com.github.msarhan.ummalqura.calendar.UmmalquraCalendar.set(UmmalquraCalendar.java:259)
at net.alhazmy13.hijridatepicker.date.hijri.HijriDatePickerDialog.getEndDate(HijriDatePickerDialog.java:1028)
at net.alhazmy13.hijridatepicker.date.hijri.MonthAdapter.getCount(MonthAdapter.java:146)
at android.widget.ListView.setAdapter(ListView.java:493)
at net.alhazmy13.hijridatepicker.date.hijri.DayPickerView.refreshAdapter(DayPickerView.java:142)
at net.alhazmy13.hijridatepicker.date.hijri.DayPickerView.setController(DayPickerView.java:114)
at net.alhazmy13.hijridatepicker.date.hijri.DayPickerView.<init>(DayPickerView.java:105)
at net.alhazmy13.hijridatepicker.date.hijri.SimpleDayPickerView.<init>(SimpleDayPickerView.java:32)
at net.alhazmy13.hijridatepicker.date.hijri.HijriDatePickerDialog.onCreateView(HijriDatePickerDialog.java:340)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2600)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:881)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:439)
at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2079)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1869)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727)
at androidx.fragment.app.FragmentManagerImpl$2.run(FragmentManagerImpl.java:150)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
and my main activity java
public class MainActivity extends AppCompatActivity implements HijriDatePickerDialog.OnDateSetListener{
TextView tvDate;
TextView etDate;
HijriDatePickerDialog.OnDateSetListener setListener;
public MainActivity() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvDate = findViewById(R.id.tv_date);
etDate = findViewById(R.id.et_date);
tvDate.setOnClickListener(v -> {
UmmalquraCalendar now = new UmmalquraCalendar();
HijriDatePickerDialog dpd = HijriDatePickerDialog.newInstance(
MainActivity.this,
now.get(Calendar.YEAR),
now.get(Calendar.MONTH),
now.get(Calendar.DAY_OF_MONTH)
);
dpd.setMinDate(new UmmalquraCalendar(1440,0,1));
dpd.show(getSupportFragmentManager(), "Datepickerdialog");
});
}
#Override
public void onResume() {
super.onResume();
assert getFragmentManager() != null;
HijriDatePickerDialog dpd = (HijriDatePickerDialog) getSupportFragmentManager().findFragmentByTag("Datepickerdialog");
if (dpd != null) dpd.setOnDateSetListener(this);
}
#Override
public void onDateSet(HijriDatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
String date = "You picked the following date: " + dayOfMonth + "/" + (++monthOfYear) + "/" + year;
System.out.println(date);
etDate.setText(date);
}
}
This problem seems to be a known bug in the msarhan-library. There was also a meanwhile closed issue on its related website. It indicates that a fix has been applied in the newest version.
So I suggest you to update your marhan library to version v2.0.2 which might solve your problem.
Update:
When looking at the date-picker-library you use we can see that it still uses the version v2.0.1. Either you wait until the author of the date-picker-library fixes the dependency or you build your own version of the date-picker-library.
If you use koltin this method will fix your issue
fun selectDateOfBirthHijri(context: Context, editText: EditText, childFragmentManager: FragmentManager) {
val now = Calendar.getInstance()
val dateOfBirthClickListener =
HijriDatePickerDialog.OnDateSetListener { view, year, month, dayOfMonth ->
now.set(Calendar.YEAR, year)
now.set(Calendar.MONTH, month)
now.set(Calendar.DAY_OF_MONTH, dayOfMonth)
editText.setText(
Formatter.format(
now.time.toString(),
Formatter.EEE_MMM_DD_HH_MM_SS_ZZZ_YYYY,
Formatter.DD_MM_YYYY
)
)
}
val ummAlquraCalendar = UmmalquraCalendar()
val b = HijriDatePickerDialog.newInstance(
dateOfBirthClickListener,
ummAlquraCalendar.get(UmmalquraCalendar.YEAR),
ummAlquraCalendar.get(UmmalquraCalendar.MONTH),
ummAlquraCalendar.get(UmmalquraCalendar.DAY_OF_MONTH)
)
b.maxDate = UmmalquraCalendar(ummAlquraCalendar.get(Calendar.YEAR),
ummAlquraCalendar.get(Calendar.MONTH),
ummAlquraCalendar.get(Calendar.DAY_OF_MONTH))
b.setTitle(context.getString(R.string.hint_date_of_birth))
b.show(childFragmentManager, "HijriDatePickerDialog")
}
Related
My application is crashing and I believe it is due to the SharedPreferencesManager prefManager = SharedPreferencesManager.getInstance(this); being stored globally in Contentclass. However, if I take it out of there then I cannot use prefManager within the switch statement further down.
I want to use the number of clicks from prefManager to determine my switch statement. How can I get around this?
public class Content extends AppCompatActivity {
Button selectAnotherButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content);
final SharedPreferencesManager prefManager = SharedPreferencesManager.getInstance(this);
selectAnotherButton = findViewById(R.id.button_select_another);
selectAnotherButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
prefManager.increaseClickCount();
for (int i = 0; i <= 100; i+=2) {
ShowRewardDialog();
}
}
});
private void ShowRewardDialog() {
String message = "";
//show dialog
// set text based on an if statement you need to create
switch (SharedPreferencesManager.getInstance(this).increaseClickCount()){
case 2 :
message = "You are rewarded with a video";
break;
case 4 :
message = "You are rewarded with a the yellow smiley face in the homepage";
break;
case 6 :
message = "You are rewarded with a video";
break;
case 8 :
message = "You are rewarded with a the green smiley face in the homepage";
break;
case 10 :
message = "You are rewarded with a video";
break;
case 12 :
message = "You are rewarded with a the red smiley face in the homepage";
break;
case 14 :
message = "You are rewarded with a video";
break;
default :
message="";
}
// custom dialog
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.custom_dialog);
SpannableString title = new SpannableString("YOU GAINED A REWARD");
title.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.purple))
, 0, title.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
// set the custom dialog components - text, image and button
TextView text = dialog.findViewById(R.id.dialog_text);
dialog.setTitle(title);
text.setText(message);
Button dialogButton = dialog.findViewById(R.id.dialog_button_OK);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
}
Stack Trace:
06-14 21:57:39.420 15488-15488/com.mima.chilltime E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.mima.chilltime, PID: 15488
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.mima.chilltime/com.mima.chilltime.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2989)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3260)
at android.app.ActivityThread.access$1000(ActivityThread.java:218)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1734)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6934)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:111)
at com.mima.chilltime.SharedPreferencesManager.<init>(SharedPreferencesManager.java:19)
at com.mima.chilltime.SharedPreferencesManager.getInstance(SharedPreferencesManager.java:25)
at com.mima.chilltime.MainActivity.<init>(MainActivity.java:25)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1690)
at android.app.Instrumentation.newActivity(Instrumentation.java:1094)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2979)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3260)
at android.app.ActivityThread.access$1000(ActivityThread.java:218)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1734)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6934)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Try using
SharedPreferencesManager.getInstance(getApplicationContext());
instead of using this
In the SharedPreferencesManager.getInstance(this); .... this refers to the particular activity (i.e. not global) (i.e. its lifecycle directly related to the current context).
On the other hand, if you clearly need a reference to the global state of your application, then you can use ApplicationContext.
From Android Documentation (my emphasis) :
public Context getApplicationContext()
Return the context of the single, global Application object of the
current process. This generally should only be used if you need a
Context whose lifecycle is separate from the current context, that is
tied to the lifetime of the process rather than the current component.
So change to:
SharedPreferencesManager prefManager = SharedPreferencesManager.getInstance(getApplicationContext());
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
when you click a button in my activity it starts/displays a DatePickerDialog. When the user selects a date and clicks "ok" i want to run an AsyncTask in the original class (the activity where the button was clicked). Everything works but i want to display to the user a TOAST when the AsyncTask is finished but it keep on getting an error when doing so.
Heres my code:
Button method in the BuyerHomePage.java
public void MeetingCreator(){
CalenderImageButton = (ImageButton)findViewById(R.id.CalenderImageButton);
CalenderImageButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment picker = new DatePickerFragment();
picker.show(getFragmentManager(), "datePicker");
}
}
);
}
DatePickerFragment.java code
public class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
public static String formattedDate;
#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 month, int day) {
Calendar c = Calendar.getInstance();
c.set(year, month, day);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
formattedDate = sdf.format(c.getTime());
BuyerHomePage Meeting = new BuyerHomePage();
Meeting.new MeetingSender().execute();
}
}
BuyerHomePage.java (post method in the AsyncTask)
#Override
protected void onPostExecute (String result){
if (result.equals("email sent")) {
//This is where i get the error
Toast.makeText(BuyerHomePage.this, "Email sent!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(BuyerHomePage.this, "Can't send email", Toast.LENGTH_LONG).show();
}
}
Error Logs:
04-23 02:25:31.631 22071-22071/com.wilsapp.wilsapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.wilsapp.wilsapp, PID: 22071
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:87)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:81)
at android.widget.Toast.<init>(Toast.java:102)
at android.widget.Toast.makeText(Toast.java:259)
at com.wilsapp.wilsapp.BuyerHomePage$MeetingSender.onPostExecute(BuyerHomePage.java:930)
at com.wilsapp.wilsapp.BuyerHomePage$MeetingSender.onPostExecute(BuyerHomePage.java:836)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
if there's any confusion or i need to explain anything please comment! Thank you!
Try this.
Toast.makeText(getApplicationContext(), "Email sent!", Toast.LENGTH_LONG).show();
I am making an app to display data from a database into a list view. When an item on the list view is clicked, it takes the user to a new activity where they can view more details about that item. I want to make the details page dynamic to display the details and have managed to show the title of the list view item in a toast.
Now, I am trying to display this by using setText() to show the title in a string but am getting the error:
AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.kathe.parenttripapp, PID: 22849
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.kathe.parenttripapp/com.example.kathe.parenttripapp.Details}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.Serializable android.content.Intent.getSerializableExtra(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.Serializable android.content.Intent.getSerializableExtra(java.lang.String)' on a null object reference
at com.example.kathe.parenttripapp.Details.<init>(Details.java:23)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
this is the class the error occurs at:
TextView titletext;
final List<Activitytable> activityTable = Activitytable.listAll(Activitytable.class);
String data = getIntent().getSerializableExtra("listPosition").toString();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
TextView titletext = (TextView) findViewById(R.id.titletext);
String data = getIntent().getSerializableExtra("listPosition").toString();
Toast.makeText(getBaseContext(),String.valueOf(data),Toast.LENGTH_LONG).show();
setData();
}
private void setData() {
Intent i = getIntent();
Bundle b = i.getExtras();
if (data != null) {
String j = (String) b.get("listPosition");
titletext.setText(j);
}
else{
titletext.setText("Hello");
}
}
This is the activity it has come from:
final ListView listView = (ListView) findViewById(R.id.viewAll_listview);
long count = Activitytable.count(Activitytable.class);
if(count>0) {
final List<Activitytable> activitytable = Activitytable.listAll(Activitytable.class);
final ViewAllListView madapter = new ViewAllListView(getApplicationContext(), activitytable);
listView.setAdapter(madapter);
listView.setClickable(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?>parent, View v, int position, long id) {
String title = activitytable.get(position).Title.toString();
Activitytable AT = Activitytable.findById(Activitytable.class,activitytable.get(position).getId());
Intent i = new Intent(getApplicationContext(),Details.class);
i.putExtra("listPosition",title);
startActivity(i);
}
public Object getItem(int position) {return position;}
});
}
else
{
Toast.makeText(getApplicationContext(), "No Data Available in Table", Toast.LENGTH_LONG);
}
}
What I would like to do is to put the intent data into the TextView 'titletext' and then do an if statement saying if the passed intent data is equal to an activity title then display the following data but can't work out what is going wrong. I have tried using getStringExtra() instead of getSerializableExtra but no such luck. Works on toast but not on TextView.
If you don't have some good understanding of why you are doing so, try not to initialize your variables until you are in onCreate, also to prevent a NullPointerException, it is a good habit to use if (variable != null).
And you are storing an int, so use getIntExtra
TextView titletext;
List<Activitytable> activityTable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
activityTable = Activitytable.listAll(Activitytable.class);
titletext = (TextView) findViewById(R.id.titletext);
Intent i = getIntent();
if (i != null) {
String data = i.getStingExtra("listPosition");
titletext.setText(String.valueOf(data));
}
}
In onCreate() and don't do it as a member variable.
Bundle intentBundle = getIntent().getExtras();
if (intentBundle != null) {
lastPosition = getInt( "lastPostion" );
}
The null pointer you are receiving is in the Details class on line 23
at com.example.kathe.parenttripapp.Details.<init>(Details.java:23)
I am making a messenger that has date and time pickers pop up when I click the button. When I press the Set button to display them, the app crashes. My code is:
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
yearSet = year;
monthSet = monthOfYear + 1;
daySet = dayOfMonth;
btnDate.setText(yearSet + monthSet + daySet);
}
};
private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hour, int minute) {
hourSet = hour;
minuteSet = minute;
btnTime.setText(hourSet + minuteSet);
}
};
LogCat:
E/AndroidRuntime: FATAL EXCEPTION: main
android.content.res.Resources$NotFoundException: String resource ID #0x7f4
at android.content.res.Resources.getText(Resources.java:1068)
at android.widget.TextView.setText(TextView.java:4546)
at devncode.kemo.testApp.SendMessageActivity$3.onDateSet(SendMessageActivity.java:95)
at android.app.DatePickerDialog.tryNotifyDateSet(DatePickerDialog.java:199)
at android.app.DatePickerDialog.onClick(DatePickerDialog.java:154)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:185)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)
Your problem is that you are setting text of different items as integers.. For example btn.setText(int); where it should be a string btn.setText(String);
So to fix it, wherever you have something like
btnTime.setText(hourSet + minuteSet);
change it to
btnTime.setText(hourSet + minuteSet + "");
Adding the + "" will cast it as a String and not give an error.
I'm currently trying to display the current time to my custom ListView but I keep getting a NullPointerException and was wondering what I was doing wrong since I was already adding to the array and grabbing its value.
The custom Adapter and setter/getters are here: 1 2
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list_view);
boss_title = getResources().getStringArray(R.array.boss_array);
bossTime = (TextView) findViewById(R.id.boss_time);
adapter = new BossAdapter(getApplicationContext(), R.layout.boss_layout);
listView.setAdapter(adapter);
int i = 0;
Thread t = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("HH-mm-ss");
String formattedTime = df.format(c.getTime());
String [] boss_time_array = new String[6];
for(int i =0; i < 6; i++){
boss_time_array[i] = formattedTime;
}
boss_time = boss_time_array;
}
});
}
} catch (InterruptedException e) {
}
}
};
t.start();
for (String boss : boss_title) {
Boss bossObject = new Boss(boss_icon[i], boss, boss_time[i]);
adapter.add(bossObject);
i++;
}
}
Logcat
8541-8541/baegmon.com.bosstimer E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: baegmon.com.bosstimer, PID: 8541
java.lang.RuntimeException: Unable to start activity ComponentInfo{baegmon.com.bosstimer/baegmon.com.bosstimer.MainActivity}: java.lang.NullPointerException: Attempt to read from null array
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to read from null array
at baegmon.com.bosstimer.MainActivity.onCreate(MainActivity.java:67)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
How do I modify it so that it doesn't return a null-pointer error and returns the correct time to my list view?
Handler handler=new Handler();
handler.post(new Runnable(){
#Override
public void run() {
// upadte textView here
handler.postDelayed(this,500); // set time here to refresh textView
}
});
Just pass your textview in the hanlder method. That works fine.
try to implement this code from the below site.
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
String strDate = sdf.format(c.getTime());
Hope any queries or concerns, do let me know.
You get the NullPointerException because the Thread isn't finished when you create the Adapter.
After the Thread was started you are immediately reading the results from boss_title.
This not possible because you have to wait for it to be finished.
You should use an AsyncTask for this and create your Adapter inside the onPostExecute (http://developer.android.com/reference/android/os/AsyncTask.html).
Also the SimpleDateFormat class is not thread-safe:
public static Date dateToString(Date date, final String format, final Locale locale)
ThreadLocal<SimpleDateFormat> formater = new ThreadLocal<SimpleDateFormat>() {
#Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat(format, locale);
}
};
return formater.get().format(string);
}