Android Weird Null Object Reference on Button.setText(mText) - android

I'm stuck with the weirdest error I've ever got since I started programming. I'm setting a text to a button. Nothing complicated there!
I do it this way:
btnButton.setText(cell.getText());
btnButton exists since I've passed some others things to it before setting its text and cell.getText() is not null either since I can log the text in my console.
Still, I get this weird error:
03-31 14:58:35.407 24398-24398/ca.gggolf.agggolf.full E/AndroidRuntime: FATAL EXCEPTION: main
Process: ca.gggolf.agggolf.full, PID: 24398
java.lang.NullPointerException: Attempt to read from field 'int android.view.ViewGroup$LayoutParams.width' on a null object reference
at android.widget.TextView.checkForRelayout(TextView.java:6836)
at android.widget.TextView.setText(TextView.java:4063)
at android.widget.TextView.setText(TextView.java:3921)
at android.widget.TextView.setText(TextView.java:3896)
at ca.gggolf.agggolf.activities.fragments.AutoGridFragment.displayAutoGridBody(AutoGridFragment.java:467)
at ca.gggolf.agggolf.activities.fragments.AutoGridFragment.createAutogridBody(AutoGridFragment.java:206)
at ca.gggolf.agggolf.activities.fragments.AutoGridFragment.onCreate(AutoGridFragment.java:94)
at android.support.v4.app.Fragment.performCreate(Fragment.java:1939)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1029)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
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:5343)
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:905)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)
Can someone help me fix this? It sometimes work but it depends from where in the application that I come from.
Thanks!
EDIT
Here's my whole code when creating the button. I assign it's width and initial text and then if the text should be truncated, I measure to make sure that my button will still fit in the size I gave it otherwise, I change it to textView.
It's when I set it back to normal after that it gives me the error.
Button btnButton = new Button(getActivity());
btnButton.setWidth(width);
btnButton.setText(cell.getText());
if(adjustedAutogrid.getColumn(indexCell).isTruncated()){
btnButton.setText("…");
btnButton.measure(0, 0);
if(btnButton.getMeasuredWidth() > width){
TextView btnText = new TextView(getActivity());
btnText.setWidth(width);
btnText.setText(cell.getText());
cell.getCSS().applyToTextView(btnText);
btnText.setEllipsize(TextUtils.TruncateAt.END);
btnText.setLines(1);
layout.addView(btnText);
break;
}
btnButton.setText(cell.getText());
btnButton.setEllipsize(TextUtils.TruncateAt.END);
btnButton.setLines(1);
}
And for those wondering from where it causes problem, well it's a bit complicated. I receive information through internet (an XML) that I convert to a table that I show. I must set the different cells the appropriate size and content. When I load what we call an AutoGrid coming from the XML, all my AutoGrid works except for one...
Edit 2
Everything works fine if I leave the text to the ellipsize symbol (…). It really is when i try to set the text again that it doesn't work..

I don't know why but it seems that if I set the text later with my button that everything is fine...
btnButton.setWidth(width);
btnButton.setEllipsize(TextUtils.TruncateAt.END);
btnButton.setLines(1);
btnButton.setText(cell.getText()); // this line used to be the first one
If someone has an explanation, please fill free to enlighten me!

Related

android.content.res.Resources$NotFoundException for string onStart()

Problem
I've seen this question posted before, but the answers did not solve my problem, so I'm guessing it may be a different problem.
My code works well when I run it, but if I leave the activity on for a while and come back to it later - it crashes.
The activity contains a fragment, which itself contains a fragment. The crash occurs inside onViewCreated() on getContext().getString(R.string.vote_for)
Code
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
TextView description = rootView.findViewById(R.id.votes_chart_desc);
description.setText(getArguments().getString("voteItemDesc"));
int votesForNum = getArguments().getInt("voteFor");
int voteAgainstNum = getArguments().getInt("voteAgainst");
int voteAbstainNum = getArguments().getInt("voteAbstain");
PieChart chart = rootView.findViewById(R.id.votes_chart);
ArrayList<PieEntry> entries = new ArrayList<>();
# CRASH happens here, inside the if, when evaluating getString().
if (votesForNum > 0) entries.add(new PieEntry(votesForNum, getContext().getString(R.string.vote_for)));
if (voteAgainstNum > 0) entries.add(new PieEntry(voteAgainstNum, getContext().getString(R.string.vote_against)));
if (voteAbstainNum > 0) entries.add(new PieEntry(voteAbstainNum, getContext().getString(R.string.vote_abstain)));
PieDataSet set = new PieDataSet(entries, "");
set.setColors(ColorTemplate.MATERIAL_COLORS);
PieData data = new PieData(set);
chart.setData(data);
chart.invalidate();
}
Stacktrace
FATAL EXCEPTION: main
Process: [myprocess], PID: 11262
java.lang.RuntimeException: Unable to start activity ComponentInfo{...}: android.content.res.Resources$NotFoundException: String resource ID #0x7f0e003b
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2729)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2790)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1505)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:173)
at android.app.ActivityThread.main(ActivityThread.java:6523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:938)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:828)
Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x7f0e003b
at android.content.res.Resources.getText(Resources.java:352)
at android.content.res.Resources.getString(Resources.java:398)
at android.content.Context.getString(Context.java:476)
at [myprocess].Votes.VoteFragment.onViewCreated(VoteFragment.java:65)
...
Things I've tried / questions I've searched
This question seemed similar (resource exists, but error) - Cleaning the project did not help
This is not similar, but similar exception - getString() receives and ID as it should, and the program works until I change to a different app.
Not similar to my issue, OP had their layout removed somehow. My layout exists, and works until you switch apps.
Duplicate of 2, irrelevant.
Duplicate of 2, irrelevant.
Changing the crashing line to rootView.getResources().getString(R.string.vote_for)
Changing the crashing line to getString(R.string.vote_for)
Changing the crashing line to getParentFragment().getActivity().getString(R.string.vote_for)
Debugger info
I put a breakpoint on the problematic line, but the debugger disconnects after I switch between 9 apps, so I cannot come back to the crashing line after switching between apps. If my understanding of the activity lifecycle is correct, the crash happens only onStop(), onResume() resumes as normal.
I've tried resolving this issue on my own, but I failed. I'm out of ideas. Has anyone else encountered something similar? Thank you.
The problem stemmed from the fact that I had several string.xml files, and for some reason the locale changed after the onRestart() function. So as a result, onViewCreated() was referencing a different xml file than I was expecting. The solution was to just change locale in the onResume() function of the parent activity.
It's also good practice to keep the strings.xml files synced and not miss any values. Had I seen the strings in English, I would have been able to identify the problem much quicker.

How to fix the IndexOutOfBoundsException in RecyclerView

I have a bunch of RecyclerViews throughout my application and have been seeing this exception in Fabric for a while now.
Stacktrace:
Fatal Exception: java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid item position 8(offset:8).state:11 android.support.v7.widget.RecyclerView{3914473e VFED.... ........ 0,0-1080,1509 #7f11017a app:id/chatlist_recycler_view}, adapter:com.myapp.application.a.c#134b699f, layout:android.support.v7.widget.LinearLayoutManager#1449aec, context:com.myapp.application.activities.HomeActivity#1fcf5f5e
at android.support.v7.widget.RecyclerView$Recycler.clear(Unknown Source)
at android.support.v7.widget.GapWorker.add(Unknown Source)
at android.support.v7.widget.GapWorker.add(Unknown Source)
at android.support.v7.widget.GapWorker.remove(Unknown Source)
at android.support.v7.widget.GapWorker.add(Unknown Source)
at android.support.v7.widget.GapWorker.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5951)
at java.lang.reflect.Method.invoke(Method.java)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
Looking at this updated stacktrace, it seems like it's an issue with my chatlist_recycler_view.
How should I go about debugging this and fixing it? I don't know what is causing the IndexOutOfBoundsException.
Code from the RecyclerView declaration:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/chatlist_recycler_view"
android:background="#android:color/white"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:isScrollContainer="false"/>
</RelativeLayout>
If you guys need any other code please let me know!
Adapter code can be found here:
https://pastebin.com/HzMkCDh5
Well, IndexOutOfBoundsException exception is a common one but in regards to recyclerview here is what you can change to avoid the exception.
1: when you assign the layout adapter just disable predictive animations
mRecyclerView.setLayoutManager(new LinearLayoutManager(this){
#Override
public boolean supportsPredictiveItemAnimations() {
return false;
}
});
2: you can try to clear the existing recycler pool and then notify the data change in case of large data set.
mRecyclerView.getRecycledViewPool().clear();
mAdapter.notifyDataSetChanged();
3: dont't use notifyItem.....() use notifyDataSetChanged() only
4: if getting data from API later you can try swapping the adapter again
swapAdapter(adapter, true)
5: make sure you are not scrolling recyclerview to some position on startup this may also cause the index related issues if data is inconsistent.
Link: source

Android App crash because of Null Pointer exception on setting onClick listener in Editor class

I have created a Linear Layout onclick of a button which has an edit text. While typing there is a popup window for suggestions that comes up and the app crashes.
Stack trace:
Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.widget.Editor$SuggestionsPopupWindow.initContentView(Editor.java:3714)
at android.widget.Editor$PinnedPopupWindow.(Editor.java:3375)
at android.widget.Editor$SuggestionsPopupWindow.(Editor.java:3660)
at android.widget.Editor.replace(Editor.java:423)
at android.widget.Editor$3.run(Editor.java:2340)
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:6682)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
I found some related answers which stated that this happens on using Android PopupWindow class since the suggestions are using a PopupWindow as well. My code does not use PopupWindow as well.
This crash is happening mostly on Samsung Note 5, and Galaxy S6.
Any help would be appreciated!
It's saying that your button (which you used like buttonName.setOnClickListener()) is not defined. Check your find view by id function, id inside of it etc.
I think it is because you set in XML a click, but don't have in your class. A check has this tag and remove:
android:onClick="save"

empty EditText caused by wrong view?

I'm new to android studio and programming. I create second table to my database and have almost identical onClickListener class first one work perfect but second give me error. EditText .getText().toString() is empty so I can't convert it to dobule. I think this problem may be caused by View but I dont know java that well and I cant find solution.
EDIT: I manage to solve this problem by adding AlertDialog to my second OnClick listener. This is not exactly what I want but it works.
Could you try setting the input type on the edittext as numberDecimal
android:inputType="numberDecimal"
That way, the user will have to input decimal number always if thats what you are expecting the user to enter.
Also, you could do a null check
if(stringWzrost != null && !stringWzrost.trim().equals("")) {
bmiWzrost = Double.valueOf(stringWzrost);
}
Right now I see that its commented out.

getting logcat error as cannot be casted

I want to generate a listview from sqlite database but the
LOGCAT shows error.
What does this below error mean?
09-23 12:01:20.354: E/AndroidRuntime(3682): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.abhishekp.listproduct/com.abhishekp.listproduct.List}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.ListView
Its Happen only because of..two possibilities.
1) If you are using TextView in xml file...
and try to initialize it with.
TextView tv=(ListView)findViewbyId(R.id.textView);
and if it is right then change it with
TextView tv=(TextView)findViewbyId(R.id.textView);
2) May be you are trying to put id of listView instead of text view.
like
TextView tv=(TextView)findViewbyId(R.id.listView);
if it is then should change
TextView tv=(TextView )findViewbyId(R.id.textView );
And if it is all good then try to clean your project and rebuild it...
Thanks!!
From your logcat its clearly showing that you are trying to cast your TextView in ListView. Check you may have declared your TextView i.e.
TextView tv=(ListView)findViewbyId(R.id.textView);
or may be you are referring the id of your ListView in your java file.
TextView tv=(ListView)findViewbyId(R.id.listView); //id defined is of listview
Eclipse tends to mess up your resources every now and then. This leads to some odd behavior such as strings and images being swapped all over your app, and more commonly classCastException(s), which happen when Eclipse switches your Views' ids around.
Just clean your project.It will work fine.

Categories

Resources