Issue
First time it works fine. this app download image from the internet and save into external storage.
I want to make a method when i call the method then it will repopulate the image from external storage and set new adapter to show the all images on PagerView.
In simple words i want to refresh the pagerview screens view. on app
start there is 3 images in sdcard. and when i press button then there
is 4 images in sdcard. it should update/refresh the view.
This the custom adapter class
public class CustomSwipeAdapter extends PagerAdapter {
static ImageView i1;
String pdfName;
static Bitmap[] bmp ;
private Context ctx;
private LayoutInflater layoutInflater;
public CustomSwipeAdapter(Context ctx) {
this.ctx =ctx;
}
#Override
public int getCount() {
bmp=Picgraber();
return bmp.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return (view==(LinearLayout)object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
//Picgraber();
layoutInflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View item_view = layoutInflater.inflate(R.layout.swipe_layout,container,false);
i1 = (ImageView)item_view.findViewById(R.id.swipeimageview);
TextView t1 = (TextView)item_view.findViewById(R.id.swipetextview);
// i1.setImageResource(images[position]);
i1.setImageBitmap(bmp[position]);
i1.setTag(imagesstr[position]);
t1.setText("image "+ position);
pdfName = String.valueOf(i1.getResources());
Log.d("pdfname", pdfName);
Log.d("position", String.valueOf(position));
container.addView(item_view);
return item_view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout)object);
}
public Bitmap[] Picgraber(){
ArrayList<Bitmap> list = new ArrayList<Bitmap>();
File file= new File("/sdcard/com.shah.tabs/");
File[] folders=file.listFiles();
for(File ff:folders){
File it=new File(file.getPath()+File.separator+ff.getName()+File.separator+"image"+File.separator+ff.getName()+".png");
// Log.w("folder with path",it.getPath());
list.add(BitmapFactory.decodeFile(it.getPath()));
}
Bitmap[] Array = list.toArray(new Bitmap[list.size()]);
return Array;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
public void update(){
bmp = Picgraber();
this.notifyDataSetChanged();
}
}
This is the onCreate method of the activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_books);
packageFolder = new File(Environment.getExternalStorageDirectory() + File.separator + getApplicationContext().getPackageName());
if (!packageFolder.exists()) {
packageFolder.mkdir();
}
viewPager = (ViewPager) findViewById(R.id.viewpager);
adapter = new CustomSwipeAdapter(this);
viewPager.setAdapter(adapter);
Log.d("curritem", String.valueOf(viewPager.getCurrentItem()));
viewPager.setPageTransformer(true, new ZoomOutSlideTransformer());
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
public void onPageSelected(int position) {
pos = position;
Log.d("onpagechange", String.valueOf(pos));
Log.d("imagename", String.valueOf(CustomSwipeAdapter.i1.getTag()));
}
});
viewPager.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
x1 = event.getX();
y1 = event.getY();
break;
}
case MotionEvent.ACTION_UP: {
x2 = event.getX();
y2 = event.getY();
if (x1 < x2) {
}
if (x1 > x2) {
}
if (y1 < y2) {
}
if (y1 > y2 + 100) {
downtoupswipe();
}
break;
}
}
return false;
}
});
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
startActivityForResult(intent, 1);
}
});
}
This the logcat of the application when crash
10-10 11:00:50.388 16816-16816/com.shah.tabs E/InputEventReceiver: Exception dispatching input event.
10-10 11:00:50.389 16816-16816/com.shah.tabs E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback
10-10 11:00:50.390 16816-16816/com.shah.tabs E/MessageQueue-JNI: java.lang.IllegalStateException: The application's PagerAdapter changed the adapter's contents without calling PagerAdapter#notifyDataSetChanged! Expected adapter item count: 2, found: 3 Pager id: com.shah.tabs:id/viewpager Pager class: class android.support.v4.view.ViewPager Problematic adapter: class com.shah.tabs.CustomSwipeAdapter
at android.support.v4.view.ViewPager.populate(ViewPager.java:1071)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1025)
at android.support.v4.view.ViewPager.onTouchEvent(ViewPager.java:2114)
at android.view.View.dispatchTouchEvent(View.java:8471)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2399)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2092)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2405)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2049)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2405)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2049)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2405)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2049)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2405)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2049)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2405)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2049)
at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2369)
at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1719)
at android.app.Activity.dispatchTouchEvent(Activity.java:2742)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2330)
at android.view.View.dispatchPointerEvent(View.java:8666)
at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4123)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3989)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3544)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3597)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3563)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3680)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3571)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3737)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3544)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3597)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3563)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3571)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3544)
at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:5807)
at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:5781)
at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:5752)
at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:5897)
at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:185)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:143)
at android.os.Looper.loop(Looper.java:122)
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)
10-10 11:00:50.390 16816-16816/com.shah.tabs D/AndroidRuntime: Shutting down VM
10-10 11:00:50.393 16816-16816/com.shah.tabs E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.shah.tabs, PID: 16816
java.lang.IllegalStateException: The application's PagerAdapter changed the adapter's contents without calling PagerAdapter#notifyDataSetChanged! Expected adapter item count: 2, found: 3 Pager id: com.shah.tabs:id/viewpager Pager class: class android.support.v4.view.ViewPager Problematic adapter: class com.shah.tabs.CustomSwipeAdapter
at android.support.v4.view.ViewPager.populate(ViewPager.java:1071)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1025)
at android.support.v4.view.ViewPager.onTouchEvent(ViewPager.java:2114)
at android.view.View.dispatchTouchEvent(View.java:8471)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2399)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2092)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2405)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2049)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2405)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2049)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2405)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2049)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2405)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2049)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2405)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2049)
at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2369)
at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1719)
at android.app.Activity.dispatchTouchEvent(Activity.java:2742)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2330)
at android.view.View.dispatchPointerEvent(View.java:8666)
at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4123)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3989)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3544)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3597)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3563)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3680)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3571)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3737)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3544)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3597)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3563)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3571)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3544)
at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:5807)
at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:5781)
at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:5752)
at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:5897)
at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:185)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:143)
at android.os.Looper.loop(Looper.java:122)
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)
**
Call from activity fab button
**
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
adapter.update();
}
});
Using the array of bitmaps have a performance issues. You can use any ImageLoader libs to do display image.
The Universal ImageLoader has methods to display local images
make some changes in this class
CustomSwipeAdapter
#Override
public int getCount() {
return imagesstr.length();
}
//add this method
public void setImages(String image[]){
imagesstr = image;
this.notifyDataSetChanged();
}
to display image use the imageLoader as suggested earlier
Just take a look at the Exception message you got here. It says:
java.lang.IllegalStateException: The application's PagerAdapter
changed the adapter's contents without calling
PagerAdapter#notifyDataSetChanged! Expected adapter item count: 2,
found: 3
It is pretty clear from the Exception message that while refreshing your PagerView, you are adding new images but you are not telling the adapter that the data which it is going to populate has been changed. As a result, the adapter expecting to just populate 2 images find 3 images and your application crashes.
So whenever you add a new image you need to explicitly call adapter.notifyDataSetChanged() to tell the adpater that a new image has been added which would eventually solve this issue.
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 9 months ago.
I am currently trying to create a calendar app in android studio. The app contains a calendar with different "Views" e.g. monthly view, weekly view, and daily view.
The app uses fragments as pages and each view is an activity.
This is the code for the fragment and buttons to initialise each view
public class CalendarFragment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_calendar, container, false);
Button btn1 = (Button) v.findViewById(R.id.openCalendar);
btn1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v)
{
Intent intent = new Intent(getActivity(),CalendarActivity.class);
startActivity(intent);
}
});
Button btn2 = (Button) v.findViewById(R.id.openWeek);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent = new Intent(getActivity(), WeekViewActivity.class);
startActivity(intent);
}
});
return v;
}
The first button which displays the monthly view of the calendar called "CalendarActivity" in code works fine but when the second button is clicked which displays the weekly view of the calendar, causes the app to crash and gives the following error in the logcat
2022-05-13 14:44:59.642 15183-15183/com.example.finalyearproject E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.finalyearproject, PID: 15183
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.finalyearproject/com.example.finalyearproject.WeekViewActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.time.LocalDate.format(java.time.format.DateTimeFormatter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3685)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3842)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2252)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7842)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.time.LocalDate.format(java.time.format.DateTimeFormatter)' on a null object reference
at com.example.finalyearproject.CalendarUtils.monthYearFromDate(CalendarUtils.java:16)
at com.example.finalyearproject.WeekViewActivity.setWeekView(WeekViewActivity.java:40)
at com.example.finalyearproject.WeekViewActivity.onCreate(WeekViewActivity.java:29)
at android.app.Activity.performCreate(Activity.java:8054)
at android.app.Activity.performCreate(Activity.java:8034)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1341)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3666)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3842)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2252)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7842)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
I am not sure what the problem is as I have been following a tutorial and the other features work. I have also included the code for each activity below.
Monthly View
public class CalendarActivity extends AppCompatActivity implements CalendarAdapter.OnItemListener {
private TextView monthYearText;
private RecyclerView calendarRecyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendar);
initWidgets();
CalendarUtils.selectedDate = LocalDate.now();
setMonthView();
}
private void initWidgets()
{
calendarRecyclerView = findViewById(R.id.calendarRecyclerView);
monthYearText = findViewById(R.id.monthYearTV);
}
private void setMonthView()
{
monthYearText.setText(monthYearFromDate(CalendarUtils.selectedDate));
ArrayList<LocalDate> daysInMonth = daysInMonthArray(CalendarUtils.selectedDate);
CalendarAdapter calendarAdapter = new CalendarAdapter(daysInMonth, this);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 7);
calendarRecyclerView.setLayoutManager(layoutManager);
calendarRecyclerView.setAdapter(calendarAdapter);
}
public void nextMonth(View view)
{
CalendarUtils.selectedDate = CalendarUtils.selectedDate.plusMonths(1);
setMonthView();
}
public void previousMonth(View view)
{
CalendarUtils.selectedDate = CalendarUtils.selectedDate.minusMonths(1);
setMonthView();
}
Weekly View
public class WeekViewActivity extends AppCompatActivity implements CalendarAdapter.OnItemListener {
private TextView monthYearText;
private RecyclerView calendarRecyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_week_view);
initWidgets();
setWeekView();
}
private void initWidgets()
{
calendarRecyclerView = findViewById(R.id.calendarRecyclerView);
monthYearText = findViewById(R.id.monthYearTV);
}
private void setWeekView()
{
monthYearText.setText(monthYearFromDate(CalendarUtils.selectedDate));
ArrayList<LocalDate> days = daysInWeekArray(CalendarUtils.selectedDate);
CalendarAdapter calendarAdapter = new CalendarAdapter(days, this);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 7);
calendarRecyclerView.setLayoutManager(layoutManager);
calendarRecyclerView.setAdapter(calendarAdapter);
}
public void previousWeek(View view)
{
CalendarUtils.selectedDate = CalendarUtils.selectedDate.minusWeeks(1);
setWeekView();
}
public void nextWeek(View view)
{
CalendarUtils.selectedDate = CalendarUtils.selectedDate.plusWeeks(1);
setWeekView();
}
Any suggestions would be greatly appreciated.
My suggestions:
Firstly you didn't initialized CalendarUtils.selectedDate
Cover code with breakpoints for. debugging or with Log.d() messages to find, which variable is null
I get this error when trying to swipe in the ViewPager Activity using the photoView library, I use Glide for the image, and the url are from an Intent(url are array). I also in download data from a firebase database using a model class.
This is the log:
06-27 14:36:33.291 6520-6520/com.realty.drake.kunuk E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.realty.drake.kunuk, PID: 6520
java.lang.StackOverflowError: stack size 8MB
at android.support.v4.view.PagerAdapter.startUpdate(PagerAdapter.java:96)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1116)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:662)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:624)
at android.support.v4.view.ViewPager.dataSetChanged(ViewPager.java:1078)
at android.support.v4.view.ViewPager$PagerObserver.onChanged(ViewPager.java:3089)
at android.support.v4.view.PagerAdapter.notifyDataSetChanged(PagerAdapter.java:284)
at com.realty.drake.kunuk.ViewPagerActivity$SamplePagerAdapter.instantiateItem(ViewPagerActivity.java:45)
at com.realty.drake.kunuk.ViewPagerActivity$SamplePagerAdapter.instantiateItem(ViewPagerActivity.java:34)
at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:1002)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1216)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:662)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:624)
at android.support.v4.view.ViewPager.dataSetChanged(ViewPager.java:1078)
at android.support.v4.view.ViewPager$PagerObserver.onChanged(ViewPager.java:3089)
at android.support.v4.view.PagerAdapter.notifyDataSetChanged(PagerAdapter.java:284)
at com.realty.drake.kunuk.ViewPagerActivity$SamplePagerAdapter.instantiateItem(ViewPagerActivity.java:45)
at com.realty.drake.kunuk.ViewPagerActivity$SamplePagerAdapter.instantiateItem(ViewPagerActivity.java:34)
at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:1002)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1216)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:662)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:624)
at android.support.v4.view.ViewPager.dataSetChanged(ViewPager.java:1078)
at android.support.v4.view.ViewPager$PagerObserver.onChanged(ViewPager.java:3089)
at android.support.v4.view.PagerAdapter.notifyDataSetChanged(PagerAdapter.java:284)
at com.realty.drake.kunuk.ViewPagerActivity$SamplePagerAdapter.instantiateItem(ViewPagerActivity.java:45)
at com.realty.drake.kunuk.ViewPagerActivity$SamplePagerAdapter.instantiateItem(ViewPagerActivity.java:34)
at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:1002)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1216)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:662)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:624)
at android.support.v4.view.ViewPager.dataSetChanged(ViewPager.java:1078)
at android.support.v4.view.ViewPager$PagerObserver.onChanged(ViewPager.java:3089)
at android.support.v4.view.PagerAdapter.notifyDataSetChanged(PagerAdapter.java:284)
at com.realty.drake.kunuk.ViewPagerActivity$SamplePagerAdapter.instantiateItem(ViewPagerActivity.java:45)
at com.realty.drake.kunuk.ViewPagerActivity$SamplePagerAdapter.instantiateItem(ViewPagerActivity.java:34)
at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:1002)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1216)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:662)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:624)
at android.support.v4.view.ViewPager.dataSetChanged(ViewPager.java:1078)
at android.support.v4.view.ViewPager$PagerObserver.onChanged(ViewPager.java:3089)
at android.support.v4.view.PagerAdapter.notifyDataSetChanged(PagerAdapter.java:284)
at com.realty.drake.kunuk.ViewPagerActivity$SamplePagerAdapter.instantiateItem(ViewPagerActivity.java:45)
at com.realty.drake.kunuk.ViewPagerActivity$SamplePagerAdapter.instantiateItem(ViewPagerActivity.java:34)
at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:1002)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1216)
at android.support.v4.vie
06-27 14:36:33.411 6520-6520/com.realty.drake.kunuk E/JavaBinder: !!! FAILED BINDER TRANSACTION !!! (parcel size = 1275500)
06-27 14:36:33.412 6520-6520/com.realty.drake.kunuk E/AndroidRuntime: Error reporting crash
android.os.TransactionTooLargeException: data parcel size 1275500 bytes
at android.os.BinderProxy.transactNative(Native Method)
at android.os.BinderProxy.transact(Binder.java:503)
at android.app.ActivityManagerProxy.handleApplicationCrash(ActivityManagerNative.java:4447)
at com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException(RuntimeInit.java:90)
at com.crashlytics.android.core.CrashlyticsUncaughtExceptionHandler.uncaughtExcep tion(CrashlyticsUncaughtExceptionHandler.java:51)
at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:693)
at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:690)
The ViewPager activity, There I take the url from an intent, parse it to turn it into an array because it is multiple string concatenated. The glide use it to display the image. The first image display and doesn't crash, but when I swipe to the second image, it took a few seconds then crash(only the activity crash not the app), but If I swipe from second to the third image it crash suddenly before even display it.
public class ViewPagerActivity extends AppCompatActivity {
String imageList = null;
String[] propertyImageArray = {};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_pager);
//get imageList url from Intent
imageList = getIntent().getStringExtra("imageList");
propertyImageArray = imageList.split(",");
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(new SamplePagerAdapter());
}
class SamplePagerAdapter extends PagerAdapter {
#Override
public int getCount() {
return propertyImageArray.length;
}
#Override
public View instantiateItem(ViewGroup container, int position) {
//Must call notifyDataSetChanged before adding imageList to View
//otherwise it'll crash
notifyDataSetChanged();
PhotoView photoView = new PhotoView(ViewPagerActivity.this);
GlideApp.with(ViewPagerActivity.this)
.load(propertyImageArray[position])
.fitCenter()
.into(photoView);
// Now just add PhotoView to ViewPager and return it
container.addView(photoView,
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
return photoView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
This is the class that send the intent to ViewPagerActivity,
public class PropertyLotDetail extends AppCompatActivity implements Toolbar.OnMenuItemClickListener {
#Override
protected void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.property_lot_detail);
Toolbar myToolbar = (Toolbar) findViewById(R.id.kunuk_toolbar);
myToolbar.inflateMenu(R.menu.menu_detail);
setSupportActionBar(myToolbar);
myToolbar.setOnMenuItemClickListener(this);
//collect our intent
Intent intent = getIntent();
Property property = intent.getParcelableExtra("Property");
//collect all property values from Parcelable
int price = property.getPrice();
String address = property.getAddress();
final String propertyImage = property.getPropertyImage();
float lotDim = property.getLotDim();
String propertyDesc = property.getPropertyDesc();
String lotTerrainType = property.getLotTerrainType();
String lotTerrainDimExt = property.getLotTerrainDimExt();
String lotTerrainSteepness = property.getLotTerrainSteepness();
[...]
//Bind the data from the Parcelable to the Views
TextView addressDetail = findViewById(R.id.post_address);
addressDetail.setText(String.valueOf(address));
String currencyPrice = NumberFormat //Format the price variable in currency form
.getCurrencyInstance(Locale.US)
.format(price);
TextView priceDetail = findViewById(R.id.post_price);
priceDetail.setText(currencyPrice);
ImageView imageView = findViewById(R.id.post_propertyImage);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),
ViewPagerActivity.class)
.putExtra("imageList", propertyImage)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
}
});
//take one long string containing multiple url and parse it
String propertyImageArray[] = propertyImage.split(",");
//TODO add loading icon for placeholder
// Download directly from StorageReference using Glide
// (See MyAppGlideModule for Loader registration)
GlideApp.with(getApplication())
.load(propertyImageArray[0])
.fitCenter()
.into(imageView);
That's the most relevant information. Please help
I just got rid of the notifyDataChanged() method call. I presume it has been automatically called, I didn't need to do it, and that's why the stack trace leads to an endless recursion. It's just what I think.
public class ViewPagerActivity extends AppCompatActivity {
String imageList = null;
String[] propertyImageArray = {};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_pager);
//get imageList url from Intent
imageList = getIntent().getStringExtra("imageList");
propertyImageArray = imageList.split(",");
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(new SamplePagerAdapter());
}
class SamplePagerAdapter extends PagerAdapter {
#Override
public int getCount() {
return propertyImageArray.length;
}
#Override
public View instantiateItem(ViewGroup container, int position) {
//Must call notifyDataSetChanged before adding imageList to View
//otherwise it'll crash
notifyDataSetChanged();
PhotoView photoView = new PhotoView(ViewPagerActivity.this);
GlideApp.with(ViewPagerActivity.this)
.load(propertyImageArray[position])
.fitCenter()
.into(photoView);
// Now just add PhotoView to ViewPager and return it
container.addView(photoView,
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
return photoView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
Sorry for the bad formatting, don't know how to make striketrough in code
There are 2 different fragment in my project. I want to do inheritance these fragment from abstract class.But I cannot write correct code for FragmentManager to hide or show fragments. How can I do this?
Error : E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.bengisu.bitirme, PID: 2580
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bengisu.bitirme/com.example.bengisu.bitirme.MainActivity}: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2789)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6251)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
Caused by: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class fragment
Caused by: android.view.InflateException: Binary XML file line #0: Error inflating class fragment
Caused by: android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment com.example.bengisu.bitirme.GameBoard: calling Fragment constructor caused an exception
at android.support.v4.app.Fragment.instantiate(Fragment.java:481)
at android.support.v4.app.FragmentContainer.instantiate(FragmentContainer.java:33)
at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:3664)
at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:111)
at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:338)
at android.support.v4.app.BaseFragmentActivityApi14.onCreateView(BaseFragmentActivityApi14.java:39)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:67)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:777)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:858)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:861)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:861)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:861)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
at android.view.LayoutInflater.inflate(LayoutInflater.java:377)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
at com.example.bengisu.bitirme.MainActivity.onCreate(MainActivity.java:30)
at android.app.Activity.performCreate(Activity.java:6666)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2677)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2789)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6251)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
Caused by: java.lang.reflect.InvocationTargetException
E/AndroidRuntime: at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:430)
at android.support.v4.app.Fragment.instantiate(Fragment.java:459)
... 34 more
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.support.v4.app.FragmentManager android.support.v4.app.FragmentActivity.getSupportFragmentManager()' on a null object reference
at com.example.bengisu.bitirme.Board.<init>(Board.java:17)
at com.example.bengisu.bitirme.GameBoard.<init>(GameBoard.java:21)
... 37 more
Application terminated.
My abstract subclass : Board.java
public abstract class Board extends Fragment {
FragmentManager fm=((MainActivity)getActivity()).getSupportFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
public abstract void Hide(Fragment fragment);
public abstract void Show(Fragment fragment);
}
First Fragment : GameBoard.java
public class GameBoard extends Board {
TextView t[]=new TextView[10];
TextView p[]=new TextView[3];
static float maxX,maxY;
Display mdispl;
Rain rain[]=new Rain[10];
Bucket bucket;
ImageView imgB;
ValueAnimator vaB;
int s=0;
public GameBoard getGameBoard(){
GameBoard gameBoard=(GameBoard) fm.findFragmentById(R.id.gameBoard);
return gameBoard;
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_game_board, container, false);
mdispl =getActivity().getWindowManager().getDefaultDisplay();
maxX = mdispl.getWidth();
maxY = mdispl.getHeight();
fm=getActivity().getSupportFragmentManager();
ft=fm.beginTransaction();
t[0]=view.findViewById(R.id.t0);
t[1] = view.findViewById(R.id.t1);
t[2] = view.findViewById(R.id.t2);
t[3] = view.findViewById(R.id.t3);
t[4] = view.findViewById(R.id.t4);
t[5] = view.findViewById(R.id.t5);
t[6] = view.findViewById(R.id.t6);
t[7] = view.findViewById(R.id.t7);
t[8] = view.findViewById(R.id.t8);
t[9] = view.findViewById(R.id.t9);
p[0] = view.findViewById(R.id.p0);
p[1] = view.findViewById(R.id.p1);
p[2] = view.findViewById(R.id.p2);
for (int i=0;i<10;i++){
rain[i]=new Rain(maxX,maxY);
rain[i].Move(t[i],0,0,5000);
}
imgB=view.findViewById(R.id.imageView);
bucket= new Bucket(imgB);
view.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
float initialX=event.getX();
if(initialX>getActivity().getWindowManager().getDefaultDisplay().getWidth()/2){
vaB= bucket.Move(null,imgB.getX(),getActivity().getWindowManager().getDefaultDisplay().getWidth()-imgB.getWidth()+150,1850);
}
else{
vaB=bucket.Move(null,imgB.getX(),-250,1850);
}
return false;
}
});
return view;
}
public void PauseBucket(){
vaB.pause();
}
#Override
public void Hide(Fragment fragment) {
ft.hide(fragment);
ft.commitNow();
}
#Override
public void Show(Fragment fragment) {
ft.show(fragment);
ft.commitNow();
}
}
Second Fragment : ScoreBoard.java
public class ScoreBoard extends Board{
//FragmentManager fm;
//FragmentTransaction ft;
ScoreBoard scoreBoard;
public ScoreBoard getScoreBoard(){
scoreBoard=(ScoreBoard)fm.findFragmentById(R.id.scoreBoard);
return scoreBoard;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
fm=getActivity().getSupportFragmentManager();
ft=fm.beginTransaction();
View view=inflater.inflate(fragment_score_board, container, false);
return view;
}
#Override
public void Hide(Fragment fragment) {
ft.hide(fragment);
ft.commitNow();
}
#Override
public void Show(Fragment fragment) {
ft.show(fragment);
ft.commitNow();
}
}
My MainActivity.java
public class MainActivity extends AppCompatActivity {
TextView time,Gscore,Sscore;
FloatingActionButton repeat,pause,resume;
GameBoard gameBoard;
ScoreBoard scoreBoard;
Bucket bucket;
CountDownTimer timer;
int score=0;
String name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
time = findViewById(R.id.time);
Gscore = findViewById(R.id.score);
Sscore = findViewById(R.id.Sscore);
repeat= findViewById(R.id.repeat);
pause = findViewById(R.id.pause);
resume = findViewById(R.id.resume);
gameBoard=gameBoard.getGameBoard();
scoreBoard=scoreBoard.getScoreBoard();
Game(60000,0);
repeat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
scoreBoard.Hide(scoreBoard);
gameBoard.Show(gameBoard);
Gscore.setVisibility(View.VISIBLE);
//gameBoard.StartAgain();
Game(60000,0);
// flipper.showNext();
bucket.bucket.setX(getWindowManager().getDefaultDisplay().getWidth()/2-100);
}
});
}
public void Game(long m,int s){
//gameFragment.s=s;
timer= new CountDownTimer(m,1000) {
public void onTick(long millisUntilFinished) {
scoreBoard.Hide(scoreBoard);
gameBoard.Show(gameBoard);
score = gameBoard.s;
String timeLeftFormatted = String.format(Locale.getDefault(), "%02d:%02d",
(millisUntilFinished / 1000) / 60,
(millisUntilFinished / 1000) % 60);
time.setText(""+timeLeftFormatted);
Gscore.setText(""+score);
if(millisUntilFinished<=30000){
time.setTextColor(Color.BLACK);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
time.setTextColor(Color.WHITE);
}
},500);
}
else time.setTextColor(Color.BLACK);
}
public void onFinish() {
scoreBoard.Show(scoreBoard);
gameBoard.Hide(gameBoard);
//flipper.showNext();
Gscore.setVisibility(View.INVISIBLE);
Sscore.setText(name+"'s Score : "+Gscore.getText());
}
};
timer.start();
}
}
I don't get what you mean exactly, but I see one problem in this line
FragmentManager fm=((MainActivity)getActivity()).getSupportFragmentManager();
It seems likegetActivity() here returned null so the error said:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.support.v4.app.FragmentManager android.support.v4.app.FragmentActivity.getSupportFragmentManager()' on a null object reference
at com.example.bengisu.bitirme.Board.<init>(Board.java:17)
at com.example.bengisu.bitirme.GameBoard.<init>(GameBoard.java:21)
Maybe you should try to init this variable in onActivityCreated
You have problem in instantiation fragment.
Also trace shown problem, take a look at line 0 in your xml of your MainActivity class
Unable to start activity
ComponentInfo{com.example.bengisu.bitirme/com.example.bengisu.bitirme.MainActivity
}: android.view.InflateException: Binary XML file line #0: Binary XML file
line #0: Error inflating class fragment
Also this is not correct way for instantiation fragment.
Following link should help you in working with framents
https://github.com/codepath/android_guides/wiki/Creating-and-Using-Fragments
In short answer you should create your framgne in following way:
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.frame_layout, new YourFragment());
// or ft.add(R.id.frame_layout, new FooFragment());
ft.commit();
I am developing a recipe book app.
my data structure is as follows:
Reference
- users
-53
-movies
-id1
(-name
-rating
-ingredients(list)
-recipe
-photo)
-id2 (....)
The data is added correctly, but when I use the following code for retrieval, the app stops. My model class is Recipe.
I need to create a grid structure to display all the dishes. I think this code should serve that purpose, but it doesn't. What am I doing wrong?
When a user clicks on the particular dish, the recipe and other details for that dish should be displayed. How can I carry out such selective retrieval in firebase?
package foodelicious.com.foodfinal;
public class MainActivity extends AppCompatActivity {
private FloatingActionButton fab;
ScaleAnimation shrinkAnim;
private RecyclerView mRecyclerView;
private StaggeredGridLayoutManager mLayoutManager;
private TextView tvNoRecipes;
private ImageView DPoster;
private TextView DMovieName,DIngredients,DRecipeTitle,DRecipe;
private RatingBar Drate;
//Getting reference to Firebase Database
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference mDatabaseReference = database.getReference();
private static final String userId = "53";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initializing our Recyclerview
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
tvNoRecipes = (TextView) findViewById(R.id.tv_no_recipes);
DPoster=(ImageView) findViewById(R.id.Dposter);
DIngredients=(TextView) findViewById(R.id.Ding);
//scale animation to shrink floating actionbar
shrinkAnim = new ScaleAnimation(1.15f, 0f, 1.15f, 0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
if (mRecyclerView != null) {
//to enable optimization of recyclerview
mRecyclerView.setHasFixedSize(true);
}
//using staggered grid pattern in recyclerview
mLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(mLayoutManager);
//Say Hello to our new FirebaseUI android Element, i.e., FirebaseRecyclerAdapter
FirebaseRecyclerAdapter<Recipe,RecipeViewHolder> adapter = new FirebaseRecyclerAdapter<Recipe, RecipeViewHolder>(
Recipe.class,
R.layout.recipe_board_item,
RecipeViewHolder.class,
//referencing the node where we want the database to store the data from our Object
mDatabaseReference.child("users").child(userId).child("movies").getRef()
) {
#Override
protected void populateViewHolder(final RecipeViewHolder viewHolder, Recipe model, int position) {
if(tvNoRecipes.getVisibility()== View.VISIBLE){
tvNoRecipes.setVisibility(View.GONE);
}
viewHolder.tvRecipeName.setText(model.getRecipeName());
viewHolder.ratingBar.setRating(model.getRecipeRating());
Picasso.with(MainActivity.this).load(model.getRecipePoster()).into(viewHolder.ivRecipePoster);
viewHolder.ivRecipePoster.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setContentView(R.layout.recipe_details);
}
});
}
};
mRecyclerView.setAdapter(adapter);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.frame_container, new AddRecipeFragment())
.addToBackStack(null)
.commit();
//animation being used to make floating actionbar disappear
shrinkAnim.setDuration(400);
fab.setAnimation(shrinkAnim);
shrinkAnim.start();
shrinkAnim.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
//changing floating actionbar visibility to gone on animation end
fab.setVisibility(View.GONE);
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
}
});
}
#Override
public void onBackPressed() {
super.onBackPressed();
if (fab.getVisibility() == View.GONE)
fab.setVisibility(View.VISIBLE);
}
//ViewHolder for our Firebase UI
public static class RecipeViewHolder extends RecyclerView.ViewHolder{
TextView tvRecipeName;
RatingBar ratingBar;
ImageView ivRecipePoster;
public RecipeViewHolder(View v) {
super(v);
tvRecipeName = (TextView) v.findViewById(R.id.iv_dish_name);
ratingBar = (RatingBar) v.findViewById(R.id.rating_bar);
ivRecipePoster = (ImageView) v.findViewById(R.id.iv_dish_poster);
}
}
}
LOGCAT
10-05 16:43:08.462 30349-30479/foodelicious.com.foodfinal D/FA: Connected to remote service
10-05 16:43:08.463 30349-30479/foodelicious.com.foodfinal V/FA: Processing queued up service tasks: 1
10-05 16:43:13.592 30349-30479/foodelicious.com.foodfinal V/FA: Inactivity, disconnecting from the service
10-05 16:43:21.549 30349-30354/foodelicious.com.foodfinal I/art: Do partial code cache collection, code=29KB, data=29KB
10-05 16:43:21.550 30349-30354/foodelicious.com.foodfinal I/art: After code cache collection, code=29KB, data=29KB
10-05 16:43:21.550 30349-30354/foodelicious.com.foodfinal I/art: Increasing code cache capacity to 128KB
10-05 16:43:21.617 30349-30349/foodelicious.com.foodfinal D/AndroidRuntime: Shutting down VM
10-05 16:43:21.625 30349-30349/foodelicious.com.foodfinal E/AndroidRuntime: FATAL EXCEPTION: main
Process: foodelicious.com.foodfinal, PID: 30349
com.google.firebase.database.DatabaseException: Class foodelicious.com.foodfinal.models.Recipe is missing a constructor with no arguments
at com.google.android.gms.internal.zzbqi$zza.zze(Unknown Source)
at com.google.android.gms.internal.zzbqi$zza.zzaG(Unknown Source)
at com.google.android.gms.internal.zzbqi.zze(Unknown Source)
at com.google.android.gms.internal.zzbqi.zzb(Unknown Source)
at com.google.android.gms.internal.zzbqi.zza(Unknown Source)
at com.google.firebase.database.DataSnapshot.getValue(Unknown Source)
at com.firebase.ui.database.FirebaseRecyclerAdapter.parseSnapshot(FirebaseRecyclerAdapter.java:147)
at com.firebase.ui.database.FirebaseRecyclerAdapter.getItem(FirebaseRecyclerAdapter.java:136)
at com.firebase.ui.database.FirebaseRecyclerAdapter.onBindViewHolder(FirebaseRecyclerAdapter.java:176)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6476)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6509)
at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5452)
at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5718)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5557)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5553)
at android.support.v7.widget.LayoutState.next(LayoutState.java:100)
at android.support.v7.widget.StaggeredGridLayoutManager.fill(StaggeredGridLayoutManager.java:1570)
at android.support.v7.widget.StaggeredGridLayoutManager.onLayoutChildren(StaggeredGridLayoutManager.java:682)
at android.support.v7.widget.StaggeredGridLayoutManager.onLayoutChildren(StaggeredGridLayoutManager.java:604)
at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3693)
at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3410)
at android.support.v7.widget.RecyclerView.consumePendingUpdateOperations(RecyclerView.java:1710)
at android.support.v7.widget.RecyclerView$1.run(RecyclerView.java:346)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:871)
at android.view.Choreographer.doCallbacks(Choreographer.java:683)
at android.view.Choreographer.doFrame(Choreographer.java:616)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:857)
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:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
Error:
com.google.firebase.database.DatabaseException: Class foodelicious.com.foodfinal.models.Recipe is missing a constructor with no arguments at
Solution:
Add default(no-argument) constructor to your class Recipe
public class Recipe ... {
public Recipe() {
//
}
}
When any sort of view is called outside of the OnCreateView method (or OnActivtivityCreated method for that matter, I have tried both), I get a NullPointerException. To communicate between fragments, I used the interface method which, through my research, seems to be the best way to do it. Unfortunately, I suspect that my error comes from the way that the MainActivity finds the Fragments.
To try to debug what I have so far, I used System.out.println() on the object in OnCreateView()/OnActivityCreated() and there is a memory address meaning it exists and is NOT null, yet when I call it outside of the function from MainActivity, it becomes null...?
Can someone shed some light into my situation? Thanks! (BTW, I have taken some useless parts of the code out)
Tab2Home.java
#Override
public void onActivityCreated (Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
spinner = (Spinner)getActivity().findViewById(R.id.tipSpinner);
adapter = ArrayAdapter.createFromResource(getActivity().getBaseContext(), R.array.tipArray, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
serviceRate=(RatingBar) getActivity().findViewById(R.id.serviceBar);
//THE OBJECT BELOW IS WHERE THE NULLPOINTEREXCEPTION IS COMING FROM
billAmount = (EditText)getActivity().findViewById(R.id.billEditText);
System.out.println(billAmount); //Surprisingly, this is not null IN the method.
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
}
public void transferInfo(){
double bill;
if (String.valueOf(billAmount.getText()).isEmpty()) //billAmount is null OUTSIDE of the method.
bill = 0.00;
else
bill = Double.parseDouble(String.valueOf(billAmount.getText()));
odsl.setData( //odsl is the OnDataSetListener object.
bill,
Integer.parseInt(String.valueOf(spinner.getItemAtPosition(3))),
Integer.parseInt(String.valueOf(numPeopleEdit.getText()))
);
}
public interface OnDataSetListener {
public void setData(double bill, int tip, int ppl);
}
#Override
public void onAttach(Context context){
super.onAttach(context);
try {
odsl = (OnDataSetListener) context;
} catch (Exception e){}
}
And the MainActivity.java
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
mViewPager.setCurrentItem(1);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (position == 2){
Tab2Home homefrag = (Tab2Home) mSectionsPagerAdapter.getItem(1);
homefrag.transferInfo();
System.out.println(".transferInfo() has been called");
}
}
#Override
public void onPageSelected(int position) {
if (position == 3){
Tab2Home homefrag = (Tab2Home) mSectionsPagerAdapter.getItem(2);
homefrag.transferInfo();
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
#Override
public void setData(double bill, int tip, int ppl) {
Tab3Summary summaryfrag = (Tab3Summary) mSectionsPagerAdapter.getItem(2);
summaryfrag.updateInfo(bill, tip, ppl);
}
EDIT:
Here is the error message:
05-23 02:28:00.352 31339-31339/com.uottawa.bond.simpletip E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.uottawa.bond.simpletip, PID: 31339
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.uottawa.bond.simpletip.Tab2Home.transferInfo(Tab2Home.java:97)
at com.uottawa.bond.simpletip.MainActivity$1.onPageScrolled(MainActivity.java:64)
at android.support.v4.view.ViewPager.dispatchOnPageScrolled(ViewPager.java:1954)
at android.support.v4.view.ViewPager.onPageScrolled(ViewPager.java:1928)
at android.support.v4.view.ViewPager.pageScrolled(ViewPager.java:1866)
at android.support.v4.view.ViewPager.computeScroll(ViewPager.java:1826)
at android.view.View.updateDisplayListIfDirty(View.java:16037)
at android.view.View.draw(View.java:16834)
at android.view.ViewGroup.drawChild(ViewGroup.java:3764)
at android.support.design.widget.CoordinatorLayout.drawChild(CoordinatorLayout.java:1195)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3550)
at android.view.View.draw(View.java:17071)
at android.view.View.updateDisplayListIfDirty(View.java:16050)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3748)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3728)
at android.view.View.updateDisplayListIfDirty(View.java:16013)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3748)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3728)
at android.view.View.updateDisplayListIfDirty(View.java:16013)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3748)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3728)
at android.view.View.updateDisplayListIfDirty(View.java:16013)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3748)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3728)
at android.view.View.updateDisplayListIfDirty(View.java:16013)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3748)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3728)
at android.view.View.updateDisplayListIfDirty(View.java:16013)
at android.view.ThreadedRenderer.updateViewTreeDisplayList(ThreadedRenderer.java:656)
at android.view.ThreadedRenderer.updateRootDisplayList(ThreadedRenderer.java:662)
at android.view.ThreadedRenderer.draw(ThreadedRenderer.java:770)
at android.view.ViewRootImpl.draw(ViewRootImpl.java:2796)
at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2604)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2211)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1246)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6301)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:871)
at android.view.Choreographer.doCallbacks(Choreographer.java:683)
at android.view.Choreographer.doFrame(Choreographer.java:619)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:857)
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:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Find the solution:
1.override the below method
2.Instead of getActivity().findviewbYId use rootView
#Override
public void onViewCreated(View rootView, Bundle savedInstanceState) {
spinner = (Spinner)rootView.findViewById(R.id.tipSpinner);
adapter = ArrayAdapter.createFromResource(getActivity().getBaseContext(), R.array.tipArray, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
serviceRate=(RatingBar) rootView.findViewById(R.id.serviceBar);
billAmount = (EditText)rootView.findViewById(R.id.billEditText);
System.out.println(billAmount);
}