Second TextView shows NullPointerException - android

I'm trying to make a custom ListView item which contains one image and two textviews. They are supposed to line up horizontally (showing up side by side). However, the second TextView always comes out as null and causing the setText method to crash. I'm not sure why it is null even though I already set it so any help would be great. I am 100% sure the crash is NullpointerException as the logcat says so.
Sorry in advance if I'm doing not normal in my code as I just started out with Android development.
Here's my xml for the ListView item:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:layout_width="250dp"
android:layout_height="250dp"
android:id="#+id/category"
android:paddingBottom="5dp"
android:paddingLeft="10dp"
android:paddingTop="5dp"
android:paddingRight="10dp"/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="match_parent">
<TextView
android:id="#+id/message"
android:layout_width="10dp"
android:layout_height="wrap_content"
android:textSize="19sp"
android:textColor="#000000"
android:textAlignment="center"
android:gravity="left|center_horizontal"/>
<TextView
android:id="#+id/datetext"
android:layout_width="40dp"
android:layout_height="wrap_content"
android:layout_marginRight="30dp"
android:layout_toRightOf="#+id/message"
android:textSize="19sp"
android:textColor="#000000"
android:textAlignment="center"
android:gravity="center_vertical|right"/>
</RelativeLayout>
</LinearLayout>
And here's my getView method in my BaseAdapter class:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = inflater.inflate(R.layout.custom_list_item, null);
}
TextView txtAlert = (TextView) view.findViewById(R.id.message);
// This is showing up as NULL
TextView txtDate = (TextView) view.findViewById(R.id.datetext);
ImageView imgCategory = (ImageView) view.findViewById(R.id.category);
// alert is a String
txtAlert.setText(alert);
// date is a String; crashes here
txtDate.setText(date);
return view;
}
Thanks!
EDIT: Here's the stack trace from the logcat if people are still looking at this post. ALSO, it is interesting to note any other TextView objects I add on will result in null as well. I have also tried cleaning and rebuilding the project multiple times and alas this doesn't work either.
08-31 05:32:19.695 24080-24080/com.ryan.myapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.ryan.myapp.activity.NotificationsActivity$DataAdapter.getView(NotificationsActivity.java:305)
at android.widget.AbsListView.obtainView(AbsListView.java:2604)
at android.widget.ListView.measureHeightOfChildren(ListView.java:1253)
at android.widget.ListView.onMeasure(ListView.java:1165)
at android.view.View.measure(View.java:16515)
at android.widget.RelativeLayout.measureChild(RelativeLayout.java:666)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:477)
at android.view.View.measure(View.java:16515)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5055)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:16515)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5055)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1435)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:720)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:592)
at android.view.View.measure(View.java:16515)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5055)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2561)
at android.view.View.measure(View.java:16515)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2194)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1339)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1550)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1236)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5160)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:791)
at android.view.Choreographer.doCallbacks(Choreographer.java:591)
at android.view.Choreographer.doFrame(Choreographer.java:561)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:777)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5365)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)

the only thing i can think of is that you are not using actually this xml, can you check that? if you have multiple layout folders(for diferent dimensions) check there also

Try to replace :
view = inflater.inflate(R.layout.custom_list_item, null);
by
view = inflater.inflate(R.layout.custom_list_item, parent, false);
And there is no need to do
View view = convertView;
Next step > view holder pattern :)

So everyone thanks for the help! Turns out gmetax from the comments section was right. For some reason it had a different id name from what I gave it. It showed the id's name as date even though I set it to datetext. If anyone could give me an explanation why this happened that would be great so this doesn't happen later in the future. Thanks!

Related

NullPointerException error while adding fragment

I am having problem with implementing barcodefragmentlibv2 into my project. As a name says and from previous experience I know that I can add it into fragment. However, I am still getting NullPointerException error when I am trying to get this fragment to work with my app.
This is a part of a code responsible for barcode fragment:
import android.support.v4.app.Fragment;
//...
public class CameraFragment extends Fragment implements IScanResultHandler {
BarcodeFragment fragment;
public static CameraFragment newInstance() {
CameraFragment fragment = new CameraFragment();
return fragment;
}
public CameraFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.include_qrfragment, container, false);
fragment = (BarcodeFragment)getActivity().getSupportFragmentManager().findFragmentById(R.id.sample);
fragment.setScanResultHandler(this);
return view;
}
//...
}
Error appears in line:
fragment.setScanResultHandler(this);
I've also tried replacing
getActivity().getSupportFragmentManager().findFragmentById(R.id.sample);
to
getFragmentManager().findFragmentById(R.id.sample);
but the result is this same.
Below are layout files:
fragment_camera
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" tools:context=".CameraFragment">
<include
android:layout_width="match_parent"
android:layout_height="match_parent"
layout="#layout/include_qrfragment" />
<TextView
android:id="#+id/status_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center_horizontal"
android:layout_margin="15dp"
android:background="#99FFFFFF"
android:gravity="center"
android:padding="10dp"
android:text="#string/msg_default_status"
android:textAppearance="?android:attr/textAppearanceMedium" />
<View
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
include_qrfragment
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/sample"
android:name="com.abhi.barcode.frag.libv2.BarcodeFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
At the beginning I've mentioned that from my own experience that this is possible. The truth is that I've built app utilizing this feature some time ago using eclipse and now I am using Android Studio - maybe there is a problem?
EDIT 1:
This is the whole error's stack trace:
06-22 23:05:56.804 30578-30578/myapp.com.test E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at myapp.com.test.CameraFragment.onCreateView(CameraFragment.java:34)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1789)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:955)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:458)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3683)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)
The problem seems to lie in this line:
fragment = (BarcodeFragment)getActivity().getSupportFragmentManager().findFragmentById(R.id.sample);
Your fragment is not yet appended to the activity as getActivity() is null at this point.
Perhaps you should move that particular code to onActivityCreated
You should only inflate the layout at the CreateView, like this:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.your_layout, null);
}
The rest of your code, you should put it in the onActivityCreated as #waqaslam said.
You are getting a null pointer because there is no layout inflated yet.
I have read your responses, and now I am assuming you have tried or moved code of getActivity().getSupportFragmentManager().findFragmentById into onActivityCreated.
The only suspect I see without loading up your project is the GUI ID itself. You named it sample or R.id.sample, which is a suspect in some projects. It is possible that you have another UI element having the same name/ID. If so, that UI cannot be converted to a fragment. My suggestion is to change the name of the ID (with unique name), and use it with findFragmentById().

TextView not Found

This is driving me absolutely crazy and Im not sure what is going on.
I have an xml layout with a TextView within a clickable RelativeLayout.
<RelativeLayout
android:id="#+id/bg_section"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_marginTop="10dp"
android:background="#color/almost_black"
android:clickable="true"
android:onClick="goToBG"
android:padding="10dp" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="Go To B.G."
android:textColor="#color/white"
android:textSize="20sp" />
<ImageView
android:id="#+id/bg_arrow"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="-10dp"
android:src="#drawable/arrow_icon" />
<TextView
android:id="#+id/current_bg_count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toLeftOf="#id/bg_arrow"
android:text="3"
android:textColor="#color/holo_blue"
android:textSize="22sp" />
</RelativeLayout>
Now in my code I try to update the textview "current_bg_count"
private void updateBGCount(){
try{
RelativeLayout bgSection = (RelativeLayout) findViewById(R.id.bg_section);
TextView bgCountTV = (TextView) bgSection.getChildAt(2);
bgCountTV.setText(tempBG.size());
}
catch(Exception e){
e.printStackTrace();
Logger.d(TAG, "exception in updateBGCount");
}
}
This gives a ResourceNotFountException on the line where I setText although the RelativeLayout is found without a problem. Even when I try finding it just by id like this:
TextView bgCountTV = (TextView) findViewById(R.id.current_bg_count)
bgCountTV.setText(tempBG.size());
it gives the same error.
All the other views in the layout are found easily and updated just fine. Only this one TextView is giving me the problem. Does anyone have any idea what the problem is?
You need to convert your size of the ArrayList to a String at this line
setText(tempBG.size())
Since tempBG.size() returns an int then setText() is looking for a resource with the id of whatever that returns. You are using this setText(ResId int) method which is used for if you have a string resource that you want to use to set the text.
So change it to
setText(String.valueOf(tempBG.size()));
Try setting your tempBG.size() to string like this
bgCountTV.setText(""+tempBG.size());
This should work
Are you using eclipse? Check there is no errors and warning in your project. Sometimes there are errors in xml that let you compile, but doesn't work properly.
the Problem is with this code
bgCountTV.setText(tempBG.size());
tempBG.size() this code is returning an int value which it is assuming as string Resource id something like R.string.VARIABLE_NAME coz it have a corresponding int value which TextView is assuming as id
What you can do
bgCountTV.setText(tempBG.size()+"");
OR
bgCountTV.setText(String.ValueOf(tempBG.size()));
OR
bgCountTV.setText(tempBG.size().toString());

Android: why is my linearlayout crashing when switching at runtime?

when user presses a button i would like to switch to the 'details' layout which is like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layoutDetails"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="16dp"
android:textColor="#ff0000"
android:text="Category" />
<TextView android:id="#+id/tv_category"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16dp"
android:layout_marginLeft="10dp" />
</LinearLayout>
and this is how i am trying to switch it:
switch(item.getItemId())
{
case ID_DETAILS:
// show new layout to for details
LinearLayout detailsLayout = (LinearLayout) findViewById(R.id.layoutDetails);
LayoutInflater detailsvi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View detailsv = detailsvi.inflate(R.layout.activity_details, null);
// IT CRASHES ON THIS LINE
detailsLayout.addView(detailsv,new LinearLayout.LayoutParams(detailsLayout.getLayoutParams().width, detailsLayout.getLayoutParams().height));
return true;
}
It gives a null pointer exception error!!!
08-09 17:23:47.146: E/AndroidRuntime(1572): FATAL EXCEPTION: main
08-09 17:23:47.146: E/AndroidRuntime(1572): java.lang.NullPointerException
Here is how you solve this:
1) put a breakpoint on the crashline and run in debug mode. You can immediately see if detailsLayout is null or not. If not do step 2 Also check if detailsv is null.
2) details
Object o1 = etailsLayout.getLayoutParams(); // check if this is null.
It has to be one or the other.
Update: Since its detailsLayout is in fact null. It must be that either
1) setContentView was not called prior to requsting detailsLayout, or
2) setContentView was set to a layout that did not define detailsLayout, or
3) setContentView was called correctly but detailsLayout is not correctly id in that layout file.
It must be one of these three.

NullPointerException When Switching between views

Some users are getting this error.
I use a viewgroup to continuously display a banner add.
I then use child views for the program and switch back and forth between views as the user clicks a button.
I can cause a crash by switching back and forth between child views 6 to 10 times.
Here is the layout for the viewgroup:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:myapp="http://schemas.android.com/apk/res/com.company.programname"
xmlns:app="http://schemas.android.com/apk/res/com.adwhirl"
android:orientation="vertical"
android:background="#color/darkslategrey"
android:id="#+id/LinearLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.adwhirl.AdWhirlLayout
android:id="#+id/adwhirl_layout"
android:gravity="center"
android:layout_width="fill_parent"
android:layout_height="52dp"
/>
</LinearLayout>
Here is the code creating the ViewGroup:
setContentView(R.layout.viewgrouplayout);
llLinLay=(LinearLayout)findViewById(R.id.LinearLayout01);
liInflater=(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Here is the main child layout with irrelevent pieces cut out:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="#+id/MainLayout"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="#+id/MainShowAllDesiredButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/AnotherButton"
android:layout_toRightOf="#id/AButton"
android:textSize="15sp"
android:text="Show All Desired"
android:onClick="MainDesired"
/>
<ListView
android:id="#+id/ItemTypeList"
android:background="#color/aqua"
android:cacheColorHint="#color/aqua"
android:fastScrollEnabled="true"
android:layout_width="fill_parent"
android:layout_height="160dip"
android:layout_below="#id/SomeItem"
/>
</RelativeLayout>
Here is an example of the code creating a view:
vAllDesired=liInflater.inflate(R.layout.alldesiredlayout,null);
vAllDesired.setId(7);
llLinLay.addView(vAllDesired);
final ListView lvAllDesired = (ListView)findViewById(R.id.AllDesiredList);
laAllDesiredAdapter = new AllDesiredListAdapter(this, alAllDesired);
lvAllCoinsDesired.setAdapter(laAllDesiredAdapter);
ViewGroup.LayoutParams AllDesiredParams = lvAllCoinsDesired.getLayoutParams();
AllDesiredParams.height = AllCoinsDesiredHeight;
lvAllCoinsDesired.setLayoutParams(AllDesiredParams);
FillAllDesiredArray();
Here is an example of the code used to switch between views:
bReturnToMainScreen = (Button) findViewById(R.id.DesiredReturnToMainScreenButton);
bReturnToMainScreen.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View V) {
llLinLay.removeView(vAllDesired);
MainWindow();
}
});
Here is the trace from Android Developer website. The line number in the program is not always the same.
java.lang.NullPointerException
at android.webkit.WebView.requestFocus(WebView.java:6113)
at android.view.ViewGroup.onRequestFocusInDescendants(ViewGroup.java:1073)
at android.view.ViewGroup.requestFocus(ViewGroup.java:1029)
at android.view.ViewGroup.onRequestFocusInDescendants(ViewGroup.java:1073)
at android.view.ViewGroup.requestFocus(ViewGroup.java:1029)
at android.view.ViewGroup.onRequestFocusInDescendants(ViewGroup.java:1073)
at android.view.ViewGroup.requestFocus(ViewGroup.java:1029)
at android.view.ViewGroup.onRequestFocusInDescendants(ViewGroup.java:1073)
at android.view.ViewGroup.requestFocus(ViewGroup.java:1029)
at android.view.ViewGroup.onRequestFocusInDescendants(ViewGroup.java:1073)
at android.view.ViewGroup.requestFocus(ViewGroup.java:1029)
at android.view.ViewGroup.onRequestFocusInDescendants(ViewGroup.java:1073)
at android.view.ViewGroup.requestFocus(ViewGroup.java:1032)
at android.view.View.requestFocus(View.java:3559)
at android.view.ViewRoot.clearChildFocus(ViewRoot.java:1586)
at android.view.ViewGroup.clearChildFocus(ViewGroup.java:508)
at android.view.ViewGroup.clearChildFocus(ViewGroup.java:508)
at android.view.ViewGroup.clearChildFocus(ViewGroup.java:508)
at android.view.ViewGroup.clearChildFocus(ViewGroup.java:508)
at android.view.ViewGroup.removeViewInternal(ViewGroup.java:2207)
at android.view.ViewGroup.removeViewInternal(ViewGroup.java:2181)
at android.view.ViewGroup.removeView(ViewGroup.java:2129)
at com.jimbobga.mycoinsus.ProgramName$8.onClick(ProgramName.java:488)
at android.view.View.performClick(View.java:2411)
at android.view.View$PerformClick.run(View.java:8819)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)
Just curious, when you're making your calls to findViewById, are they in the OnCreate method or directly where you're inflating the row in the adapter? As it relates to your example here, the findViewById method is only guaranteed to work in the OnCreate method or where the particular row is inflated, so its possible that calling it elsewhere could cause unexpected behavior.
Look at this line:
at com.jimbobga.mycoinsus.ProgramName$8.onClick(ProgramName.java:488)
If this is happening after orientation has changed and views have not been assigned then you have a problem.
I'm experiencing the same issue.
Take a look at this response: Issues With Adwhirl(Admob+Inmobi+..)
Eric from AdMob staff says that it's a problem with the Android framework.
Did you try to surround your OnClick() code with a: try/catch Throwable Exception?

TextView inside a LinearLayout, crash with a long string

Using Android, here is part of a layout xml file:
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:textColor="#191919">
<TextView android:id="#+id/someTextField"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textStyle="bold" />
<TextView android:id="#+id/anotherTextField"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
I am adding this view (at runtime) to a ViewAnimator like this:
ViewAnimator viewAnimator = (ViewAnimator)findViewById(R.id.viewAnimator);
View newView = View.inflate(this, R.layout.new_view, null);
viewAnimator.addView(newView);
viewAnimator.showNext();
String newValue = "new value for the text field";
findViewById(R.id.deal_view).setVisibility(View.VISIBLE);
TextView someTextField = (TextView)findViewById(R.id.someTextField);
someTextField.setText(newValue);
This seems to be working fine, but when newValue is long enough to take more than 1 line of text in the layout, I am getting a crash:
09-06 21:36:48.208: ERROR/AndroidRuntime(6561): Uncaught handler: thread main exiting due to uncaught exception
09-06 21:36:48.248: ERROR/AndroidRuntime(6561): java.lang.StackOverflowError
09-06 21:36:48.248: ERROR/AndroidRuntime(6561): at android.view.ViewGroup.drawChild(ViewGroup.java:1486)
09-06 21:36:48.248: ERROR/AndroidRuntime(6561): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1228)
(many more lines like this)
Is this enough information to see what I might be doing wrong? It works perfectly fine when newValue is short enough for one line. I've thought about trying a TableLayout but it seems like this is exactly what a LinearLayout is good for.
Thanks for the help in the comments. I ended up taking the advice here (dropping ViewAnimator directly and using ViewFlipper). Better app, but still the same problem. I dropped one level of LinearLayout containers and it started working fine.
I'm assuming bhatt4982 is right, UI depth was too great.
bhatt4982, post your comment as an answer to get credit for this.

Categories

Resources