Attempt to get Length of null Array of file.Length() - java

Please Help I am newbie and I am getting am getting this error?
while I start the App, I request for Storage Permission but after that the app crashes and gives me this error :- Attempt to get Length of null Array. Please Help.
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.techx.storysaver/com.techx.storysaver.MainActivity}: java.lang.NullPointerException: Attempt to get length of null array
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6126)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.NullPointerException: Attempt to get length of null array
at com.techx.storysaver.ImageAdapter.getCount(ImageAdapter.java:40)
at android.widget.GridView.setAdapter(GridView.java:206)
at com.techx.storysaver.ImageFragment.onCreateView(ImageFragment.java:53)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2189)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1299)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:757)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2355)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2146)
at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2098)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2008)
at android.support.v4.app.FragmentController.execPendingActions(FragmentController.java:388)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:607)
at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:178)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1249)
at android.app.Activity.performStart(Activity.java:6696)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2628)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6126) 
at java.lang.reflect.Method.invoke(Native Method)
 
This is my ImageAdapter
public class ImageAdapter extends BaseAdapter {
private Context context;
String path = Environment.getExternalStorageDirectory().toString()+"/Pictures/";
File f = new File(path);
File file[] = f.listFiles();
public ImageAdapter(Context c)
{
context = c;
}
#Override
public int getCount() {
return file.length; //Line 40, Here i am gettin Error
}
#Override
public Object getItem(int position) {
return file[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(context);
Glide
.with( context )
.load( file[position] )
.into( imageView );
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(360,480));
return imageView;
}
}
Here is my Image Fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.image_fragment, container, false);
GridView gridView = (GridView)rootView.findViewById(R.id.grid_view);
gridView.setAdapter(new ImageAdapter(getActivity())); //Line 50, Here Also i am getting Error
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(getActivity(),FullImageActivity.class);
i.putExtra("id",position);
startActivity(i);
}
});
return rootView;
}

String path = Environment.getExternalStorageDirectory().toString()+"/Pictures/";
File f = new File(path);
File file[] = f.listFiles();
The file[] is null, therefore this statement return file.length; or any other involving that variable will fail. Also do use exception handling to handle files existence in your. Like FileNotFound for example.
Also try this String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String pic_path = String.format("%s/%s",path,specific_path);
Use this instead to get a handle to the file.
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
then if(storageDir.exists()){File file[] = storageDir.listFiles();}
Syntax for calling getExternalFilesDir, it depends on a context.
getActivity().getExternalFilesDir() in Fragment
context.getExternalFilesDir() in classes, where you pass Context
as parameter
YourActivity.this.getExternalFilesDir(); when
called in inner class of Activity

Related

App crashes with IndexOutOfBoundsException when deleting firebase child with removeValue()

I am making an android app based on firebase Realtime database. I am reading the data in a RecyclerView. There are three items in my RecyclerView.
Text view = Name
Text view = Number
Button = Delete
When I delete some child from my RecyclerView three things can happen:
Sometimes it deletes the targeted child normally
Sometimes it deletes some other child (often which is below the targeted child.)
Sometimes my app crashes.
This is the code for my adapter:
public class holder extends RecyclerView.ViewHolder {
public Button btnDelete;
public TextView tvName;
public TextView tvRoll;
public holder(#NonNull View itemView) {
super(itemView);
btnDelete=(Button) itemView.findViewById(R.id.idDelete);
tvName=(TextView) itemView.findViewById(R.id.idName);
tvRoll=(TextView) itemView.findViewById(R.id.idRoll);
}
}
This is the code to show items in recycler view and code for delete button:
options = new FirebaseRecyclerOptions.Builder<basic>()
.setQuery(myRef, basic.class)
.build();
adapter = new FirebaseRecyclerAdapter<basic, holder>(options) {
#SuppressLint("SetTextI18n")
#Override
protected void onBindViewHolder(#NonNull holder holder, final int i, #NonNull final basic basic) {
holder.tvName.setText(basic.getFb01name());
holder.tvRoll.setText(basic.getFb04roll());
holder.btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myRef.child(getRef(i).getKey()).removeValue();
}
});
}
#NonNull
#Override
public holder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.items, parent, false);
return new holder(v);
}
};
//------------------------------
adapter.startListening();
Userlist.setAdapter(adapter);
//-----------------------------------
I cannot guess where is the problem.
Please also provide a practical solution.
This is the crash report:
2020-11-30 23:27:45.968 10796-10796/com.my App Name E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.my App Name, PID: 10796
java.lang.IndexOutOfBoundsException: Index: 4, Size: 4
at java.util.ArrayList.get(ArrayList.java:437)
at com.firebase.ui.common.BaseObservableSnapshotArray.getSnapshot(BaseObservableSnapshotArray.java:70)
at com.firebase.ui.database.FirebaseRecyclerAdapter.getRef(FirebaseRecyclerAdapter.java:112)
at com.my App Name.ViewActivity$1$1.onClick(ViewActivity.java:72)
at android.view.View.performClick(View.java:7448)
at android.view.View.performClickInternal(View.java:7425)
at android.view.View.access$3600(View.java:810)
at android.view.View$PerformClick.run(View.java:28305)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
2020-11-30 23:27:46.701 1467-10685/com.google.android.googlequicksearchbox E/sb.v.u.LiteSuggestSourc: On-device lite suggest model loading error.
2020-11-30 23:27:46.818 1467-1774/com.google.android.googlequicksearchbox E/MDD: DownloadProgressMonitor: Can't find file group for uri: android://com.google.android.googlequicksearchbox/files/sharedminusonemodule/shared/SharedMinusOneData.pb.tmp
It seems that when you access Firebase getRef(i) within the button onClick callback, it can reference a wrong position i causing IndexOutOfBoundsException
So, we'll get the key outside of the callback as below:
options = new FirebaseRecyclerOptions.Builder<basic>()
.setQuery(myRef, basic.class)
.build();
adapter = new FirebaseRecyclerAdapter<basic, holder>(options) {
#SuppressLint("SetTextI18n")
#Override
protected void onBindViewHolder(#NonNull holder holder, final int i, #NonNull final basic basic) {
holder.tvName.setText(basic.getFb01name());
holder.tvRoll.setText(basic.getFb04roll());
String refKey = getRef(i).getKey(); // <<<<<< Here is the change
holder.btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myRef.child(refKey)).removeValue();
}
});
}
#NonNull
#Override
public holder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.items, parent, false);
return new holder(v);
}
};

TextView inside Fragment in ViewPager is null on orientation change

I have a MainActivity inside I create ViewPager withFragments. I am using savedInstanceState to store values to set TextView after orientation changed. I also want to change value e.g. using button in MainActivity. Button works properly, but if I change the orientation then Button cannot set TextView in Fragment because TextView is now null.
MyFragment
public class MyFragment extends Fragment {
private TextView textView;
private String info;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.item_weather, container, false);
textView = view.findViewById(R.id.text_view);
Bundle bundle = getArguments();
info = bundle.getString("info");
setInfo(info);
return view;
}
public void setInfo(String info) {
this.info = info;
textView.setText(info); //here is the error
}
}
In MainActivity.java in OnCreate
myFragment = new MyFragment();
viewPager = findViewById(R.id.viewpager);
viewPager.setOffscreenPageLimit(10);
List<Fragment> fragments = new ArrayList<>();
fragments.add(myFragment);
pagerAdapter = new MyPageAdapter(getSupportFragmentManager(), fragments);
viewPager.setAdapter(pagerAdapter);
MyPagerAdapter looks like this:
public class MyPageAdapter extends FragmentStatePagerAdapter {
private List<Fragment> fragments;
public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
}
As I said everything works, but after orientation chage if I use Button I got an error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
Any ideas how to solve this?
edit:
full error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.app.myapp, PID: 15400
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.app.myapp.fragments.myFragment.setInfo(myFragment.java:53)
at com.example.app.myapp.MainActivity.onOptionsItemSelected(MainActivity.java:195)
at android.app.Activity.onMenuItemSelected(Activity.java:3543)
at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:407)
at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:195)
at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:108)
at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:108)
at android.support.v7.app.ToolbarActionBar$2.onMenuItemClick(ToolbarActionBar.java:63)
at android.support.v7.widget.Toolbar$1.onMenuItemClick(Toolbar.java:203)
at android.support.v7.widget.ActionMenuView$MenuBuilderCallback.onMenuItemSelected(ActionMenuView.java:780)
at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:171)
at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:973)
at android.support.v7.view.menu.MenuPopup.onItemClick(MenuPopup.java:127)
at android.widget.AdapterView.performItemClick(AdapterView.java:318)
at android.widget.AbsListView.performItemClick(AbsListView.java:1159)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3136)
at android.widget.AbsListView$3.run(AbsListView.java:4052)
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)
Into the fragment try to initialize the textView in the on the onViewCreated method:
#Override
public View onViewCreated(view: View, savedInstanceState: Bundle) {
// Your initialization code here
}
Solution:
Ok, EpicPandaForce thanks for hints.
To solve this i used in MainActivity
#Override
protected void onResume() {
super.onResume();
viewPager.setAdapter(pagerAdapter);
}
#Override
protected void onPause() {
super.onPause();
viewPager.setAdapter(null);
}

Update Image from Spinner selection

I'm stuck at this point:
I have a RecyclerView with a list of CardViews.
When a button is pressed, the addItem(); method is called, which obviously adds an item.
Here's how:
String text = hwtext.getText().toString();
mList.add(new HomeWork_Item(the.image.I.want, text));
mAdapter.notifyItemInserted(mList.size());
Which works, great!
Now, I have added a Spinner. The spinner contains a few Subjects. If, let's say, the subject history is selected, I'd like to change the.image.I.want from the addItem(); method to another one in the drawable.
I tried using glide but this didn't work:
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String SpinnerText = parent.getItemAtPosition(position).toString();
Toast.makeText(getContext(), SpinnerText, Toast.LENGTH_SHORT).show();
if (SpinnerText.equals("History")) {
Glide.with(getActivity()).load(R.drawable.history).into(R.id.theImageView);
}
}
Notice: The Item would be added only when a button is pressed which calls the method to add it. After selecting a Subject it should just prepare the Image to use when the Item will be added.
Thanks!
Crash Logcat:
2019-03-08 14:59:10.328 9808-9808/com.reogen.ssr E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.reogen.ssr, PID: 9808
java.lang.NullPointerException: Argument must not be null
at com.bumptech.glide.util.Preconditions.checkNotNull(Preconditions.java:31)
at com.bumptech.glide.util.Preconditions.checkNotNull(Preconditions.java:25)
at com.bumptech.glide.RequestBuilder.into(RequestBuilder.java:685)
at com.reogen.ssr.Fragments.Homework.onItemSelected(Homework.java:170)
at android.widget.AdapterView.fireOnSelected(AdapterView.java:1331)
at android.widget.AdapterView.dispatchOnItemSelected(AdapterView.java:1320)
at android.widget.AdapterView.-wrap1(Unknown Source:0)
at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:1282)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6938)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Create an ImageView as
ImageView historyImage = findViewById(R.id.historyImage);
Then in your glide you do this :
Glide.with(view.getContext()).load(R.drawable.history).into(historyImage);
You are passing an int into the into and you should pass the ImageView directly.
Edit
Change your code to this one
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_homework, container, false);
insert = rootView.findViewById(R.id.insert_text);
hwtext = rootView.findViewById(R.id.hwinput);
SubjectImage = rootView.findViewById(id.HWImage);
spinner = rootView.findViewById(R.id.spinner);
buildView(rootView);
return rootView;
}
public void buildView(View rootView) {
mRecyclerView = rootView.findViewById(R.id.RecycleHW);
mRecyclerView.setHasFixedSize(true);
mManager = new LinearLayoutManager(getActivity());
mAdapter = new HomeWorkAdapter(mList);
mRecyclerView.setLayoutManager(mManager);
mRecyclerView.setAdapter(mAdapter);
}

Android view is null object reference inside fragment

i'm having a hard time with some code. I am using sliding tabs with 2 fragment. Inside one of my fragment i'm trying to get a LinearLayout and add some stuff in it but everytime i try to do getView().findViewByID() I got null object reference
I'm calling the function after the onCreateView() I tried making a variable of type View and putting the View that i inflate in the onCreateView in it but i keeps getting the same error. I also tried putting a if() before to check if view isnt null , but even with this , I get null object reference. Can someone help me ?
public class listAlarmFragment extends Fragment{
public View view = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup vg, Bundle bundle){
View v = inflater.inflate(R.layout.list_alarm,vg,false);
view = v;
return v;
}
public void showAlarm(Cursor c){
if(view != null) { //even with that check, I got a null pointer exception
LinearLayout baseList = (LinearLayout) view.findViewById(R.id.baseList); // NullPointerException: Attempt to invoke virtual method on a null object reference
}
}
}
Replacing view with getView() doesnt change anything.
This is how I'm calling the function from the Main Activity
pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Fragment c = adapter.getItem(0);
((listAlarmFragment)(c)).showAlarm(dbHelper.getAlarm()); // where I call the function
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
I'm opening this fragment at the beggining when my app open. It crashs when im trying to switch to another fragment.
here is the stack trace :
04-02 18:41:54.615 31584-31584/al.demo.alarmmanagerdemo E/AndroidRuntime: FATAL EXCEPTION: main
Process: al.demo.alarmmanagerdemo, PID: 31584
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at al.demo.alarmmanagerdemo.fragment.listAlarmFragment.showAlarm(listAlarmFragment.java:83)
at al.demo.alarmmanagerdemo.MainActivity$1.onPageSelected(MainActivity.java:54)
at android.support.v4.view.ViewPager.dispatchOnPageSelected(ViewPager.java:1971)
at android.support.v4.view.ViewPager.scrollToItem(ViewPager.java:689)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:673)
at android.support.v4.view.ViewPager.onTouchEvent(ViewPager.java:2288)
at android.view.View.dispatchTouchEvent(View.java:10779)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2858)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2534)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2864)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2549)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2864)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2549)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2864)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2549)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2864)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2549)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2864)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2549)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2864)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2549)
at com.android.internal.policy.DecorView.superDispatchTouchEvent(DecorView.java:605)
at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1895)
at android.app.Activity.dispatchTouchEvent(Activity.java:3241)
at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:67)
at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:67)
at com.android.internal.policy.DecorView.dispatchTouchEvent(DecorView.java:567)
at android.view.View.dispatchPointerEvent(View.java:11008)
at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:5155)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:5007)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4532)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4585)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4551)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4684)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4559)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4741)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4532)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4585)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4551)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4559)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4532)
at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:7092)
at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:7024)
at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:6985)
at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:7202)
at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:185)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:323)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:6776)
04-02 18:41:54.615 31584-31584/al.demo.alarmmanagerdemo E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1510)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1400)
I would do something like this,
public class listAlarmFragment extends Fragment{
//public View view = null; // no need
private LinearLayout baseList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup vg, Bundle bundle){
View v = inflater.inflate(R.layout.list_alarm,vg,false);
baseList = (LinearLayout) v.findViewById(R.id.baseList);
//view = v; no need
return v;
}
public void showAlarm(Cursor c){
if(baseList!=null){
//do something with your baseList
}
}
}
Also check R.id.baseList exists in the layout xml R.layout.list_alarm.
and it should be LinearLayout with
id=#+id/baseList

Conductor - Controller Pager Adapter | Out of memory crash

I recently made an app with a ViewPager and my child fragments weren't being destroyed properly causing out of memory exception. I fixed it by using this https://github.com/adamsp/FragmentStatePagerIssueExample/blob/master/app/src/main/java/com/example/fragmentstatepagerissueexample/app/FixedFragmentStatePagerAdapter.java
Now I have rebuilt my app to use Controllers instead of fragments and things got messy. The Conductor library has official support of ViewPager via ControllerPagerAdapter, but it seems as broken as the original android one. Here's my code:
I make the adapter in PagerController:
PagerAdapter adapter = new PagerViewAdapter(this, pdfFactory.getPageCount());
PagerViewAdapter:
public class PagerViewAdapter extends ControllerPagerAdapter {
private final int size;
public PagerViewAdapter(Controller controller, int size) {
super(controller, false);
this.size = size;
}
#Override
public int getCount() {
return size;
}
#Override
public Controller getItem(int position) {
return new PagerImageController(position);
}
}
PagerImageController:
public class PagerImageController extends Controller {
#Inject PdfFactory pdfFactory;
private int position;
public PagerImageController() {}
public PagerImageController(int position) {
this.position = position;
setRetainViewMode(RetainViewMode.RELEASE_DETACH);
Log.d("LOG", "PagerImageController: "+position);
}
#NonNull
#Override
protected View onCreateView(#NonNull LayoutInflater inflater, #NonNull ViewGroup container) {
//Dagger 2
((CorePdfApplication) getActivity().getApplication()).getComponent().inject(this);
//Locate and inflate the PhotoView
final View v = inflater.inflate(R.layout.pager_element, container, false);
PhotoView photoView = (PhotoView) v.findViewById(R.id.pager_image);
Observable.just(position)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnNext(integer -> {
photoView.setImageBitmap(pdfFactory.getPage(integer));
})
.subscribe();
return v;
}
}
LOG:
java.lang.IllegalStateException: Fatal Exception thrown on Scheduler.Worker thread.
at rx.android.schedulers.LooperScheduler$ScheduledAction.run(LooperScheduler.java:114)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5696)
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:1028)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
Caused by: java.lang.OutOfMemoryError: Failed to allocate a 20866572 byte allocation with 16777216 free bytes and 18MB until OOM
Any ideas how to fix this one?

Categories