NullPointerException on getTextView in Android - android

so I have this getter function in a Class called ItemEnergyGreen:
public TextView getTextView(FrameLayout fl) {
textView = (TextView) fl.findViewById(R.id.textview_energyOrange_quantity);
return textView;
}
And I want now to call this methode from another Class:
//Item Energy Green
itemEnergyGreenFrameLayout = (FrameLayout) inflater.inflate(R.layout.item_energy_green_layout, null, false);
itemEnergyGreenQuantityTextView = itemEnergyGreen.getTextView(itemEnergyGreenFrameLayout);
btn_ItemEnergyGreen = (ImageButton) itemEnergyGreenFrameLayout.findViewById(R.id.btn_energyGreenItem_use);
btn_ItemEnergyGreen.setOnClickListener(this);
The function call is in Line 2, I am passing the frameLayout to the getter Function but textView in my ItemEnergyGreen class is always NULL.
The error occurs when i want to call setText on my view:
public void itemEnergyGreenUpdateNumber() {
int quantity = itemEnergyGreen.getQuantity();
String qstring = String.valueOf(quantity);
itemEnergyGreenQuantityTextView.setText(qstring);
}
This is the XML-FrameLayout that is get inflated:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ItemEnergyGreenFrameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageButton
android:id="#+id/btn_energyGreenItem_use"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:src="#drawable/item_energydrink_green" >
</ImageButton>
<TextView
android:id="#+id/textview_energyGreen_quantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:background="#F00"
android:clickable="false"
android:padding="2dp"
android:textColor="#FFF"
android:textStyle="bold" >
</TextView>
</FrameLayout>
Why is that?
ps. At the point where the getter function is called, the itemEnergyGreen Object is already initialized.
Thank you for your answers, and sorry if that is a dump question but i´m going crazy about this.

textView in my ItemEnergyGreen class is always NULL.
findViewById looks for a view in the current view hierarchy. Probably TextView is not a child of FrameLayout. So initialization fails leading to NullPointerException.
The other reason could be that you referenced wrong id.
Edit:
Id referenced in wrong
<TextView
android:id="#+id/textview_energyGreen_quantity"
Change this
textView = (TextView) fl.findViewById(R.id.textview_energyOrange_quantity);
to
textView = (TextView) fl.findViewById(R.id.textview_energyGreen_quantity);

Try this
private View mView;
mView =inflater.inflate(R.layout.item_energy_green_layout, null, false);
itemEnergyGreenQuantityTextView = itemEnergyGreen.getTextView(mView);

Related

Android FindViewById is only working for a child layout (listview row) and not for TextViews in the parent layout

I am guessing my problem is with inflating layouts. I have 2 layout files:
activity_mail.xlm:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/results"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/profilesCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:textSize="18sp" />
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
... and listitem_device.xlm:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/device_label"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"/>
<TextView
android:id="#+id/device_service"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1.5"/>
</LinearLayout>
in my main_activity java file, I have:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
....
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder viewHolder;
if (view == null) {
view = mInflator.inflate(R.layout.listitem_device, null);
viewHolder = new ViewHolder();
viewHolder.deviceAddress = (TextView) view.findViewById(R.id.device_label); // from listitem_device.xml
viewHolder.profilesCount = (TextView) view.findViewById(R.id.profilesCount); // from activity_main.xml
The problem is the subsequent code:
viewHolder.profilesCount.setText("HELLO");
generates the error "Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference".
How do I fix this?
I don't see anywhere that you have even have a view with id "profilesCount".You only have device label and device service as ids in the layout file that you are using to inflate the rows of the list view.Better use Recycler view also, it provides more flexibility.
Also, you can't access something from activity_mail.xml in the getView() function of your adapter because by using "view" in getfunction, as that corrspond to only the row of the list view and since that id is not present in the xml file associated with the row of list view, you are getting "viewholders.profileCount" as null and hence the Nullpointer exception.
If you wanna use a TextView or any view in your adapter, better create an interface and implement that interface in your activity to use as a call back and then set the textview field of your activity.xml file, thats the best way as it would keep your code cleaner.Other way is to pass the reference of the activity to your adapter and then find the text view or whatever that you wanna use from actvity_mail.xml file, but its not recommended and is a very bad way as it may require additional memory.

Get View by ID from attributes in Custom View Class

I want to get a view from his ID, from the attribute in the xml. I have tried with getParent() but it's return null.
XML
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ntwldg="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:background="#drawable/background_settings"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/revealView"
android:gravity="center"
android:text="TEST"
android:background="#android:color/darker_gray"
android:visibility="invisible"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<com.dot.networkloading.NetworkLoading
android:id="#+id/network_loading"
ntwldg:text="Youtube"
ntwldg:image="#drawable/ic_youtube"
ntwldg:imageBackground="#drawable/ic_youtube"
ntwldg:revealView="#id/revealView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
The attribute revealView is referencing the View above.
Code - NetworkLoading (init())
title = (TextView) findViewById(R.id.title);
image = (ImageView) findViewById(R.id.image);
imageBackground = (ImageView) findViewById(R.id.imageBackground);
finishView = findViewById(R.id.revealView);
String text = attributes.getString(R.styleable.network_loading_text);
imageId = attributes.getResourceId(R.styleable.network_loading_image, 0);
imageBackgroundId = attributes.getResourceId(R.styleable.network_loading_imageBackground, 0);
finishView = ((View) getParent()).findViewById(attributes.getResourceId(R.styleable.network_loading_revealView, R.id.revealView));
It seems that you're trying to find your revealView too early. In the constructor, the View will not have yet been added to the layout it's in, so getParent() will return null. Keep the resource ID for the revealView as a field, get its value in the constructor, and then find the View in the onAttachedToWindow() method.
In the code you've posted, remove the last line - the last finishView = ... line - and instead save the resource ID to your field.
revealViewId = attributes.getResourceId(R.styleable.NetworkLoading_revealView, R.id.revealView);
Then find the View in the onAttachedToWindow() method instead.
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
finishView = ((View) getParent()).findViewById(revealViewId);
...
}

Can't get my TextView to update in a fragment

I have tried everything I can possibly think of, I have tried many solutions in Stack as well. None seem to resolve my issue. I am trying to pass a string that I passed from an earlier intent (parsed JSON data). Everytime I call set text I get a Null Pointer Exception, I have tried using a method to set the text as well as just setting it. Any assistance would be greatly appreciated.
This is the fragment I am trying to update.
public class HomeFragment extends Fragment{
TextView tv;
public HomeFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
LayoutInflater lf = getActivity().getLayoutInflater();
View rootView = lf.inflate(R.layout.fragment_home, container, false);
tv = (TextView) rootView.findViewById(R.id.accountName);
tv.setText("test");
return rootView;
}
}
I just put a regular string in to test. Here is the XML.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/lblCompany"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="71dp" />
</RelativeLayout>
Thanks In advance for absolutely any help.
This is the id set on your TextView in xml:
android:id="#+id/lblCompany"
This is the id you are searching for in onCreateView:
tv = (TextView) rootView.findViewById(R.id.accountName);
The ids need to match for you to update the text in that particular TextView. Try
tv = (TextView) rootView.findViewById(R.id.lblCompany);
instead.

Robolectric shadow activity.findViewById returns null

Robolectric shadow activity.findViewById returns a null.
This is fairly simple exercise. All the tuts are similar to this, so should be simple. Wondering if anyone else is experiencing this. Code is below.
#Test
public void shouldFindViewsById(){
activity = Robolectric.buildActivity(DeckardActivity.class).create().visible().get();
assertThat(activity).isNotNull();
TextView textView = (TextView) activity.findViewById(R.id.textView);
assertThat(textView).isNotNull();
Button button = (Button) activity.findViewById(R.id.button);
assertThat(button).isNotNull();
EditText editText = (EditText) activity.findViewById(R.id.editText);
assertThat(editText).isNotNull();
}
I'm expecting you use the https://github.com/robolectric/deckard-gradle example based on your DeckardActivity?
The original layout only contains a view with id R.id.text
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Hello Espresso!"
/>
</LinearLayout>
check that you import the correct example R class import com.example.R; and try just following test snippet:
activity = Robolectric.buildActivity(DeckardActivity.class).create().visible().get();
assertThat(activity).isNotNull();
TextView textView = (TextView) activity.findViewById(R.id.text);
assertThat(textView).isNotNull();
if you like here is an extended example for robolectric tests https://github.com/nenick/android-gradle-template

how to get component given as reference in custom view?

Hi I am making a custom view and giving other component id as a reference in it like this
<com.example.timerview.CustomView
android:id="#+id/custom_view"
android:layout_width="100dip"
android:layout_height="100dip"
mtv:associatedTextView="#+id/text_view"
/>
<TextView
android:id="#+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
now I want to use this TextView in CustomView.java so I am doing this in constructor
int tId = a.getResourceId(R.styleable.CustomView_associatedTextView, 0);
TextView tText = (TextView) findViewById(tId);
but I found tText is null please advise me where I am wrong or How can I do such thing. Please help me.
Your TextView is not a child of your custom view, which is why findViewById cannot find it.
Call findViewById from the root view, after the custom view has been attached:
protected void onAttachedToWindow() {
super.onAttachedToWindow();
int tId = a.getResourceId(R.styleable.CustomView_associatedTextView, 0);
TextView tText = (TextView) getRootView().findViewById(tId);
}

Categories

Resources