package org.jaberrio.personai2;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.os.Bundle;
import android.widget.DatePicker;
import android.widget.TextView;
import java.util.Calendar;
public 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) {
DataBaseManager dataBaseManager = new DataBaseManager();
String date = String.valueOf(month) + "/" + String.valueOf(day) + "/" + String.valueOf(year);
dataBaseManager.tempSaveCurrentEvent(DataBaseManager.FieldTypes.DUE_DATE,date, getActivity().getApplicationContext());
TextView dueDate = (TextView)view.getRootView().findViewById(R.id.dueDate);
dueDate.setText(dataBaseManager.tempGetCurrentEvent(DataBaseManager.FieldTypes.DUE_DATE,getActivity().getApplicationContext()));
}
}
LOGCAT:
06-23 19:04:05.451 13931-13931/org.jaberrio.personai2 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: org.jaberrio.personai2, PID: 13931
java.lang.NullPointerException
at org.jaberrio.personai2.DatePickerFragment.onDateSet(DatePickerFragment.java:36)
at android.app.DatePickerDialog.tryNotifyDateSet(DatePickerDialog.java:148)
at android.app.DatePickerDialog.onClick(DatePickerDialog.java:116)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
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 am calling dueDate.setText() however it is returning null. I called view.getRootView() because I am inside the view of DatePicker therefore it should return the view containing my dueDate TextView. I could also pass the View from the method calling DatePickerFragment but I do not know how.I am guessing that DatePicker view when called getRootView() does not return the view that contains R.id.dueDate. Thanks in advance.
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I am trying to make an app on Android, using Kotlin and Java.
My inspiration comes from this tutorial:
https://www.youtube.com/watch?v=Qg3L_B9--zY
I changed it a little bit, and now I have a beautiful error:
"Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference"
Here is the error log:
11-21 10:46:03.006 27125-27125/? E/libprocessgroup: failed to make and chown /acct/uid_10058: Read-
only file system
11-21 10:46:03.006 27125-27125/? W/Zygote: createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?
11-21 10:46:03.006 27125-27125/? I/art: Not late-enabling -Xcheck:jni (already on)
11-21 10:46:03.079 27125-27125/com.example.budgetapp I/System.out: Util Constructor
11-21 10:46:03.143 27125-27125/com.example.budgetapp E/MainActivity: before onCreate()
11-21 10:46:03.150 27125-27125/com.example.budgetapp W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter androidx.vectordrawable.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
11-21 10:46:03.183 27125-27125/com.example.budgetapp E/MainActivity: after onCreate()
11-21 10:46:03.206 27125-27125/com.example.budgetapp I/art: Rejecting re-init on previously-failed class java.lang.Class<androidx.core.view.ViewCompat$2>
11-21 10:46:03.206 27125-27125/com.example.budgetapp I/art: Rejecting re-init on previously-failed class java.lang.Class<androidx.core.view.ViewCompat$2>
11-21 10:46:03.275 27125-27125/com.example.budgetapp E/MainActivity: after setContentView()
11-21 10:46:03.275 27125-27125/com.example.budgetapp D/AndroidRuntime: Shutting down VM
--------- beginning of crash
11-21 10:46:03.276 27125-27125/com.example.budgetapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.budgetapp, PID: 27125
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.budgetapp/com.example.budgetapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
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 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:149)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:99)
at android.content.Context.obtainStyledAttributes(Context.java:437)
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:692)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:659)
at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:479)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:214)
at Util.setupUIViews(Util.java:43)
at com.example.budgetapp.MainActivity.onCreate(MainActivity.kt:27)
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: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)
And here are my classes:
MainActivity.kt:
package com.example.budgetapp
import Util
import android.app.DatePickerDialog
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*
class MainActivity : AppCompatActivity() {
private val tag = "MainActivity"
var util = Util()
override fun onCreate(savedInstanceState: Bundle?) {
Log.e(tag, "before onCreate()")
super.onCreate(savedInstanceState)
Log.e(tag, "after onCreate()")
setContentView(R.layout.activity_main)
Log.e(tag, "after setContentView()")
util.setupUIViews()
Log.e(tag, "after setupUIView()")
util.initToolbar()
Log.e(tag, "after initToolbar()")
util.setupListView()
Log.e(tag, "after setupListView()")
//Calendars:
val c = Calendar.getInstance()
val year = c.get(Calendar.YEAR)
val month = c.get(Calendar.MONTH)
val day = c.get(Calendar.DAY_OF_MONTH)
val c2 = Calendar.getInstance()
val year2 = c2.get(Calendar.YEAR)
val month2 = c2.get(Calendar.MONTH)
val day2 = c2.get(Calendar.DAY_OF_MONTH)
Log.e(tag, "year1: $year")
Log.e(tag, "month1: $month")
Log.e(tag, "month2: $month2")
Log.e(tag, "day1: $day")
//button click to show DatePickerDialog
pickDateBtn.setOnClickListener {
val dpd = DatePickerDialog(
this,
DatePickerDialog.OnDateSetListener {_, mYear, mMonth, mDay ->
var monthSel=mMonth+1
dateTv2.text = "$mDay/$monthSel/$mYear"
},
year,
month,
day
)
dpd.show()
val dpd2 = DatePickerDialog(
this,
DatePickerDialog.OnDateSetListener {_, mYear2, mMonth2, mDay2 ->
var monthSel2=mMonth2+1
dateTv.text = "$mDay2/$monthSel2/$mYear2"
},
year2,
month2,
day2
)
dpd2.show()
}
}
}
SimpleAdapter.java:
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.budgetapp.R;
public class SimpleAdapter extends BaseAdapter {
public Context mContext;
private LayoutInflater layoutInflater;
private TextView title, description;
private String[] titleArray, descriptionArray;
private ImageView imageView;
public SimpleAdapter(Context context, String[] title, String [] description){
mContext= context;
titleArray=title;
descriptionArray= description;
layoutInflater= LayoutInflater.from(context);
}
#Override
public int getCount(){
return titleArray.length;
}
#Override
public Object getItem(int position) {
return titleArray[position];
}
#Override
public long getItemId(int position){
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
layoutInflater.inflate(R.layout.main_activity_single_item, null);
}
title= convertView.findViewById(R.id.tvMain);
description = convertView.findViewById(R.id.tvDescription);
imageView = convertView.findViewById(R.id.ivMain);
title.setText(titleArray[position]);
description.setText(descriptionArray[position]);
if(titleArray[position].equalsIgnoreCase("Timetable")){
imageView.setImageResource(R.drawable.timetable);
}else if(titleArray[position].equalsIgnoreCase("Subjects")){
imageView.setImageResource(R.drawable.book);
}else if(titleArray[position].equalsIgnoreCase("Faculty")) {
imageView.setImageResource(R.drawable.play);
}else{
imageView.setImageResource(R.drawable.settings);
}
return convertView;
}
}
and Util.java:
import android.widget.ListView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import com.example.budgetapp.R;
import java.util.logging.Logger;
public class Util extends AppCompatActivity {
public Util(){
System.out.println("Util Constructor");
}
public Toolbar getToolbar() {
return toolbar;
}
public void setToolbar(Toolbar toolbar) {
this.toolbar = toolbar;
}
public ListView getListView() {
return listView;
}
public void setListView(ListView listView) {
this.listView = listView;
}
#Override
public String toString() {
return "Util{" +
"toolbar=" + toolbar +
", listView=" + listView +
'}';
}
private Toolbar toolbar;
private ListView listView;
Logger logger;
public void setupUIViews(){
toolbar = findViewById(R.id.ToolbarMain);
logger.info("inside Util class, setupUiViews, before findViewById(lvMain)");
listView = findViewById(R.id.lvMain);
}
public void initToolbar(){
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(" App");
}
public void setupListView(){
String[] title = getResources().getStringArray(R.array.Main);
String[] description=getResources().getStringArray(R.array.Description);
SimpleAdapter simpleAdapter = new SimpleAdapter(this, title, description);
listView.setAdapter(simpleAdapter);
}
}
The code crushes before entering into setupUIViews() method from Util class.
Can you please, please take a look and tell me how can I resolve the issue ?
I debugged, but did not understand where the problem comes from.
Also, looked to other similar questions, but each exemple is specific, so I cannot extrapolate to my situation.
Thank you very much for your time and help!
you call util. setupUIViews(), in the inner method,it called findViewById(R.id.ToolbarMain). this method is belonged to Activity, we look at the source code
return getWindow().findViewById(id);
//in the window, (PhoneWindow)
#Nullable
public <T extends View> T findViewById(#IdRes int id) {
return getDecorView().findViewById(id);
}
// the DecorView is the basic view, it set when you call setContentView
public void setContentView(#LayoutRes int layoutResID) {
getWindow().setContentView(layoutResID);
initWindowDecorActionBar();
}
//PhoneWindow setContentView
#Override
public void setContentView(View view) {
setContentView(view, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
}
#Override
public void setContentView(View view, ViewGroup.LayoutParams params) {
// decor, when theme attributes and the like are crystalized. Do not
// check the feature
// before this happens.
if (mContentParent == null) {
installDecor(); // this method init DecorView
} else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
mContentParent.removeAllViews();
}
...
}
but you do not call util setContenView to set its view. so it reports the error.
and your code writes way is wrong. we set view in activity or fragment own class;
we cannot use another activity to set other activities.
In android, every activity has its own window. try to move the Utils method into MainActiviy.
The util class is extending from AppCompatActivity but is not properly initialized. You can't use AppCompatActivity in that way. Instead you need to do something like:
class MainActivity : AppCompatActivity() {
private val tag = "MainActivity"
lateinit var util: Util
override fun onCreate(savedInstanceState: Bundle?) {
util = Util(this)
}
}
And the Util (in kotlin) class:
class Util(private delegate:MainActivity) {
public void setupUIViews(){
toolbar = delegate.findViewById(R.id.ToolbarMain);
listView = delegate.findViewById(R.id.lvMain);
}
}
Also, I think that using this pattern and move all view-related stuff to a "Util" class is not the best. You will have better results using other patterns like MVP or MVVM.
recently i started a new project in android studios and came across an error I can't really find or see the problem with, my application crashes when it hits the line getSupportFragmentManager(). I am using it alongside of TimePickerFragment
I tried googling different things and trying different ways to implement this
ButtonListeners class
import android.app.TimePickerDialog;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.TimePicker;
public class ButtonListeners extends FragmentActivity implements
View.OnClickListener, TimePickerDialog.OnTimeSetListener {
#Override
public void onClick(View buttons) {
switch (buttons.getId()){
case R.id.button1:
break;
case R.id.button2:
DialogFragment timePicker = new TimePickerFragment();
**FragmentManager manager = getSupportFragmentManager();** //<< error here
timePicker.show(manager,"timepicker");
}
}
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
//do something
}
}
TimePickerFragment class
public class TimePickerFragment extends DialogFragment {
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
return new TimePickerDialog(getActivity(), (TimePickerDialog.OnTimeSetListener) getActivity(), hour, minute, DateFormat.is24HourFormat(getActivity()));
}
}
LogCat
2019-06-18 16:29:24.449 25857-25857/com.example.calendar E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.calendar, PID: 25857
java.lang.IllegalStateException: Activity has been destroyed
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:2114)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:683)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:637)
at android.support.v4.app.DialogFragment.show(DialogFragment.java:144)
at com.example.calendar.ButtonListeners.onClick(ButtonListeners.java:28)
at android.view.View.performClick(View.java:6597)
at android.view.View.performClickInternal(View.java:6574)
at android.view.View.access$3100(View.java:778)
at android.view.View$PerformClick.run(View.java:25885)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Try to use getFragmentManager() in place of getSupportFragmentManager().
There is second option, using getActivity().getSupportFragmentManager();
I previously had this code working, but now it doesn't for some strange reason.
Code for Date And Time Picker
btnDatePicker=(Button)view.findViewById(R.id.btn_date);
btnTimePicker=(Button)view.findViewById(R.id.btn_time);
txtDate=(EditText)view.findViewById(R.id.in_date);
txtTime=(EditText)view.findViewById(R.id.in_time);
btnDatePicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(getContext(),
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
txtDate.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year);
}
}, mYear, mMonth, mDay);
datePickerDialog.show();
}
});
btnTimePicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Get Current Time
final Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
// Launch Time Picker Dialog
TimePickerDialog timePickerDialog = new TimePickerDialog(getContext(),
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
txtTime.setText(hourOfDay + ":" + minute);
}
}, mHour, mMinute, false);
timePickerDialog.show();
}
});
xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="6dp">
<EditText
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="#+id/in_date"
android:layout_marginTop="82dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SELECT DATE"
android:id="#+id/btn_date"
android:layout_alignBottom="#+id/in_date"
android:layout_toRightOf="#+id/in_date"
android:layout_toEndOf="#+id/in_date" />
<EditText
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="#+id/in_time"
android:layout_below="#+id/in_date"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SELECT TIME"
android:id="#+id/btn_time"
android:layout_below="#+id/btn_date"
android:layout_alignLeft="#+id/btn_date"
android:layout_alignStart="#+id/btn_date" />
<TextView
android:id="#+id/medOptions"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/btn_time"
android:layout_marginTop="10dp"
android:padding="6dp"
android:text="Medication:"
android:textColor="#color/Black"
android:textSize="16sp" />
</RelativeLayout>
Error Log
android.view.InflateException: Binary XML file line #20: Binary XML file line #20: Error inflating class android.widget.DatePicker
at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at android.app.DatePickerDialog.<init>(DatePickerDialog.java:112)
at android.app.DatePickerDialog.<init>(DatePickerDialog.java:82)
at com.example.shakeel.appidea2.calendar.CalendarFragment$1.onClick(CalendarFragment.java:118)
at android.view.View.performClick(View.java:5210)
at android.view.View$PerformClick.run(View.java:21328)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5551)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
Caused by: android.view.InflateException: Binary XML file line #20: Error inflating class android.widget.DatePicker
at android.view.LayoutInflater.createView(LayoutInflater.java:645)
at com.android.internal.policy.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:58)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:694)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:762)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at android.app.DatePickerDialog.<init>(DatePickerDialog.java:112)
at android.app.DatePickerDialog.<init>(DatePickerDialog.java:82)
at com.example.shakeel.appidea2.calendar.CalendarFragment$1.onClick(CalendarFragment.java:118)
at android.view.View.performClick(View.java:5210)
at android.view.View$PerformClick.run(View.java:21328)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5551)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance(Native Method)
at android.view.LayoutInflater.createView(LayoutInflater.java:619)
at com.android.internal.policy.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:58)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:694)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:762)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at android.app.DatePickerDialog.<init>(DatePickerDialog.java:112)
at android.app.DatePickerDialog.<init>(DatePickerDialog.java:82)
at com.example.shakeel.appidea2.calendar.CalendarFragment$1.onClick(CalendarFragment.java:118)
at android.view.View.performClick(View.java:5210)
at android.view.View$PerformClick.run(View.java:21328)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5551)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
Caused by: android.view.InflateException: Binary XML file line #23: Binary XML file line #36: Error inflating class TextView
at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.widget.DatePickerCalendarDelegate.<init>(DatePickerCalendarDelegate.java:118)
at android.widget.DatePicker.createCalendarUIDelegate(DatePicker.java:160)
at android.widget.DatePicker.<init>(DatePicker.java:140)
at android.widget.DatePicker.<init>(DatePicker.java:126)
at android.widget.DatePicker.<init>(DatePicker.java:122)
at java.lang.reflect.Constructor.newInstance(Native Method)
at android.view.LayoutInflater.createView(LayoutInflater.java:619)
at com.android.internal.policy.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:58)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:694)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:762)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at android.app.DatePickerDialog.<init>(DatePickerDialog.java:112)
at android.app.DatePickerDialog.<init>(DatePickerDialog.java:82)
at com.example.shakeel.appidea2.calendar.CalendarFragment$1.onClick(CalendarFragment.java:118)
at android.view.View.performClick(View.java:5210)
at android.view.View$PerformClick.run(View.java:21328)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5551)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
Caused by: android.view.InflateException: Binary XML file line #36: Error inflating class TextView
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:782)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:971)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:831)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.widget.DatePickerCalendarDelegate.<init>(DatePickerCalendarDelegate.java:118)
at android.widget.DatePicker.createCalendarUIDelegate(DatePicker.java:160)
at android.widget.DatePicker.<init>(DatePicker.java:140)
at android.widget.DatePicker.<init>(DatePicker.java:126)
at android.widget.DatePicker.<init>(DatePicker.java:122)
at java.lang.reflect.Constructor.newInstance(Native Method)
at android.view.LayoutInflater.createView(LayoutInflater.java:619)
at com.android.internal.policy.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:58)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:694)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:762)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at android.app.DatePickerDialog.<init>(DatePickerDialog.java:112)
at android.app.DatePickerDialog.<init>(DatePickerDialog.java:82)
at com.example.shakeel.appidea2.calendar.CalendarFragment$1.onClick(CalendarFragment.java:118)
at android.view.View.performClick(View.java:5210)
at android.view.View$PerformClick.run(View.java:21328)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5551)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=17; index=268
at android.content.res.StringBlock.get(StringBlock.java:65)
at android.content.res.XmlBlock$Parser.getPooledString(XmlBlock.java:458)
at android.content.res.TypedArray.loadStringValueAt(TypedArray.java:1151)
at android.content.res.TypedArray.getText(TypedArray.java:158)
at android.widget.TextView.<init>(TextView.java:1005)
at android.widget.TextView.<init>(TextView.java:703)
at android.support.v7.widget.AppCompatTextView.<init>(AppCompatTextView.java:60)
at android.support.v7.widget.AppCompatTextView.<init>(AppCompatTextView.java:56)
at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:103)
at android.support.v7.app.AppCompatDelegateImplV7.createView(AppCompatDelegateImplV7.java:963)
at android.support.v7.app.AppCompatDeleg
I'm not too sure on how to fix it, it was working perfectly before but I dont know what happened. I just updated android studio, then everything stopped working in my code, i've tried clean/rebuild and resync but still nothing.
I Solved my problem.
The problem was located within my styles.xml file. I was playing about with changing the colour of the app, but by adding a colour accent to a theme caused everything to break. Not too sure why. If someone can explain why adding a colour accent would cause such a problem, that would be great.
Try altering this with getActivity instead of getContext this is most likely whats causing the inflation issue.
DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(),
new DatePickerDialog.OnDateSetListener() {
DATE PICKER
package course.examples.UI.datepicker;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
public class DatePickerActivity extends Activity {
private TextView mDateDisplay;
private Button mPickDate;
private int mYear;
private int mMonth;
private int mDay;
static final int DATE_DIALOG_ID = 0;
// the callback received when the user "sets" the date in the dialog
private DatePickerDialog.OnDateSetListener mDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
updateDisplay();
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// capture our View elements
mDateDisplay = (TextView) findViewById(R.id.dateDisplay);
mPickDate = (Button) findViewById(R.id.pickDate);
// add a click listener to the button
mPickDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
// get the current date
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
// display the current date (this method is below)
updateDisplay();
}
// updates the date in the TextView
private void updateDisplay() {
mDateDisplay.setText(
new StringBuilder()
// Month is 0 based so add 1
.append(mMonth + 1).append("-")
.append(mDay).append("-")
.append(mYear).append(" "));
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this,
mDateSetListener,
mYear, mMonth, mDay);
}
return null;
}
}
TIME PICKER
package course.examples.UI.timepicker;
import java.util.Calendar;
import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
public class TimePickerActivity extends Activity {
private TextView mTimeDisplay;
private Button mPickTime;
private int mHour;
private int mMinute;
static final int TIME_DIALOG_ID = 0;
// the callback received when the user "sets" the time in the dialog
private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
mHour = hourOfDay;
mMinute = minute;
updateDisplay();
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// capture our View elements
mTimeDisplay = (TextView) findViewById(R.id.timeDisplay);
mPickTime = (Button) findViewById(R.id.pickTime);
// add a click listener to the button
mPickTime.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(TIME_DIALOG_ID);
}
});
// get the current time
final Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
// display the current date
updateDisplay();
}
// updates the time we display in the TextView
private void updateDisplay() {
mTimeDisplay.setText(new StringBuilder().append(pad(mHour)).append(":")
.append(pad(mMinute)));
}
private static String pad(int c) {
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case TIME_DIALOG_ID:
return new TimePickerDialog(this, mTimeSetListener, mHour, mMinute,
false);
}
return null;
}
}
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 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.