This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have a navigation drawer app with couple fragments. One of them utilizes recyclerviewadapter/recyclerviewholder to display items. Switching between fragments works well but AFTER switching, clicking on an item with listener causes nullpointerexception. Now, I tested it without the listener and it works fine. I'm guessing that the listener isn't refreshed? when fragment is swiping? Can someone help me out please? Been searching for days and yet I can't fix it.
Process: com.mikepenz.materialdrawer.app.debug, PID: 30803
java.lang.NullPointerException: Attempt to invoke interface method
'void
com.mikepenz.materialdrawer.app.RecyclerViewAdapter$OnItemClickListener.onItemClick(java.lang.String)'
on a null object reference
at
com.mikepenz.materialdrawer.app.RecyclerViewAdapter$1.onClick(RecyclerViewAdapter.java:43)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
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: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)
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewHolders> {
private List<ItemObject> itemList;
private Context context;
private OnItemClickListener listener;
public RecyclerViewAdapter(Context context, List<ItemObject> itemList) {
this.itemList = itemList;
this.context = context;
}
#Override
public RecyclerViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view_list, null);
RecyclerViewHolders rcv = new RecyclerViewHolders(layoutView, context);
return rcv;
}
#Override
public void onBindViewHolder(RecyclerViewHolders holder, final int position) {
holder.countryName.setText(itemList.get(position).getName());
// holder.countryPhoto.setImageResource(itemList.get(position).getPhoto());
holder.countryName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// listener.onItemClick(itemList.get(position).getName());
Log.d("HELLO ",itemList.get(position).getName());
if (position ==1)
{
listener.onItemClick("GA");
}
}
});
}
public interface OnItemClickListener{
void onItemClick(String textName);
}
public void setOnItemClickListener(OnItemClickListener listener){
this.listener = listener;
}
#Override
public int getItemCount() {
Log.e("itemlist size ", this.itemList.size() + "");
return this.itemList.size();
}
}
replace your following code
listener.onItemClick("GA");
with
if(listener!=null){
listener.onItemClick("GA");
}
it may be work for you, may be your listener null when you try to set onItemClick
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 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);
}
};
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?
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I tried few of solved problems on this site about this instance of problems, but, seems like mine is specific, because it doesn't shows for instance of uninitialized object but on method that isn't even called.
error log
java.lang.NullPointerException: Attempt to invoke virtual method 'void rs.ridjis.glosar.rjecnik.RjecnikCursorAdapter.changeCursor(android.database.Cursor)' on a null object reference
at rs.ridjis.glosar.activities.MainActivity.changeCursor(MainActivity.java:75)
at rs.ridjis.glosar.activities.MainActivity.onOptionsItemSelected(MainActivity.java:114)
at android.app.Activity.onMenuItemSelected(Activity.java:2885)
at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:361)
at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:147)
at android.support.v7.internal.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:100)
at android.support.v7.internal.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:100)
at android.support.v7.internal.app.ToolbarActionBar$2.onMenuItemClick(ToolbarActionBar.java:73)
at android.support.v7.widget.Toolbar$1.onMenuItemClick(Toolbar.java:180)
at android.support.v7.widget.ActionMenuView$MenuBuilderCallback.onMenuItemSelected(ActionMenuView.java:761)
at android.support.v7.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:811)
at android.support.v7.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:153)
at android.support.v7.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:958)
at android.support.v7.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:948)
at android.support.v7.widget.ActionMenuView.invokeItem(ActionMenuView.java:619)
at android.support.v7.internal.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:139)
at android.view.View.performClick(View.java:4789)
at android.view.View$PerformClick.run(View.java:19881)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5294)
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:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
MainActivity.java
public class MainActivity extends AppCompatActivity implements Communicator {
public Toolbar toolbar;
private RjecnikCursorAdapter adapter;
private FragmentManager fragmentManager;
private WordsListFragment wordsListFragment;
private RjecnikDB dbRjecnik;
private SQLiteDatabase db;
private Cursor cursor;
private final String QUERY_SELECTALL = "SELECT * FROM " + RjecnikDB.TABLE;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fragmentManager = getFragmentManager();
wordsListFragment = new WordsListFragment();
final FragmentTransaction ft = fragmentManager.beginTransaction();
ft.add(R.id.fragment_container, wordsListFragment);
ft.commit();
}
///// Implementation interface methods /////
public void changeCursor() {
db = dbRjecnik.getWritableDatabase();
cursor = db.rawQuery(QUERY_SELECTALL, null);
adapter.changeCursor(cursor);
db.close();
Toast.makeText(this, "Lista ažurirana", Toast.LENGTH_SHORT).show();
}
public Cursor initCursor() {
dbRjecnik = RjecnikDB.getInstance(getApplicationContext());
db = dbRjecnik.getWritableDatabase();
cursor = db.rawQuery(QUERY_SELECTALL, null);
return cursor;
}
public void deleteOnLongClick(int id) {
db = dbRjecnik.getWritableDatabase();
db.delete(RjecnikDB.TABLE, RjecnikDB.COLUMN_ID + " = ?", new String[] { Integer.toString(id) } );
db.close();
}
// END OF IMPLEMENTATION //
#Override
protected void onRestart() {
super.onRestart();
changeCursor();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.search_bar) {
return true;
} else if (id == R.id.refresh) {
changeCursor();
}
return super.onOptionsItemSelected(item);
}
As you can see from error log, problem is where shows changeCursor(), even if it's not called, onOptionItemSelected.
What is best way to fix this? It's neither working when I call cursor = initCursor() before actionBar initialization.
You never initialize adapter before you use it. That's why it is null and you get a NullPointerException when you call
adapter.changeCursor(cursor);
I have created Dialog Fragment with custom layout and want to set text for some textboxes. But when trying to get view in my adapter image click I'm getting null pointer exception.
I would like to know is there any best way to implement it?
Thanks in advance.
Below is my code:
public class AlertDialogFragment extends DialogFragment
{
private View dialogView;
private static IDialogButtonsClicks buttonsClicks;
private AlertDialog.Builder alertDialog;
public static AlertDialogFragment newInstance(int title, int icon, int positive, int negative, int view, int message, IDialogButtonsClicks clicks)
{
AlertDialogFragment dialogFragment = new AlertDialogFragment();
Bundle args = new Bundle();
args.putInt("title", title);
args.putInt("icon", icon);
args.putInt("pos", positive);
args.putInt("neg", negative);
args.putInt("view", view);
args.putInt("message", message);
buttonsClicks = clicks;
dialogFragment.setArguments(args);
return dialogFragment;
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
alertDialog = new AlertDialog.Builder(getActivity());
int dView = getArguments().getInt("view");
int mess = getArguments().getInt("message");
if (dView != -1)
{
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
dialogView = layoutInflater.inflate(dView, null);
alertDialog.setView(dialogView);
}
if (mess != -1)
{
alertDialog.setMessage(mess);
}
alertDialog.setTitle(getArguments().getInt("title"));
alertDialog.setIcon(getArguments().getInt("icon"));
alertDialog.setPositiveButton(getArguments().getInt("pos"), new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
buttonsClicks.OnPositiveButtonClick(dialogView);
}
});
alertDialog.setNegativeButton(getArguments().getInt("neg"), new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
buttonsClicks.OnNegativeButtonClick();
}
});
return alertDialog.create();
}
public View getDialogView()
{
return dialogView;
}
#Nullable
#Override
public View getView()
{
return super.getView();
}
}
holder.imgCatEdit.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
AlertDialogFragment editCatDialog = AlertDialogFragment.newInstance(R.string.add_category_title, R.drawable.ic_edit, R.string.edit_cat_button_save, R.string.edit_cat_button_cancel, R.layout.edit_category, -1, new IDialogButtonsClicks()
{
#Override
public void OnPositiveButtonClick(View view)
{
}
#Override
public void OnNegativeButtonClick()
{
}
});
editCatDialog.show(((MyBusinessMainActivity)baseContext).getSupportFragmentManager(), "EditCatDialog");
View dialogView = editCatDialog.getView();//It seems here I'm getting null
EditText ed_edit_cat_name = (EditText)dialogView.findViewById(R.id.ed_edit_cat_name);
EditText ed_edit_cat_descr = (EditText)dialogView.findViewById(R.id.ed_edit_cat_descr);
ed_edit_cat_name.setText(cat_name);
ed_edit_cat_descr.setText(cat_descr);
}
});
11-23 12:40:49.708 19702-19702/am.nkr.mybusiness E/AndroidRuntime: FATAL EXCEPTION: main
Process: am.nkr.mybusiness, PID: 19702
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at am.nkr.mybusiness.CategoriesAdapter$2.onClick(CategoriesAdapter.java:165)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
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: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)
It is because when you do editCatDialog.getView(); the view have not been yet initializied (onCreateDialog() was not called).
The best way would be to add listeners in dialog in onViewCreated method. Then passing those events to your main fragment (e.g. via buttonClicks variable).
If you want to make it in a quick and hacky way you could write getSupportFragmentManager().executePendingTransaction() after show method
Yeah, you got that error because when you call ed_edit_cat_name.setText(cat_name);, your DialogFragment callback onCreateView is not finished! To overcome this problem, I think you can declare some variables to hold your cat_name and cat_des in your DialogFragment as below:
public class AlertDialogFragment extends DialogFragment
{
private String catName;// getter - setter
private String catDes;//getter-setter
// TODO: find your view and set cat name, description in onCreateView callback.
}
Then, you can set your cat name, cat des when you create new instance of DialogFragment.