Setting text in TextView throws a null pointer exception - java

I am just starting out android programming, and I ran into this error while trying to set the text in a TextView. I have researched other people's problems, but I have seemed to take care of the trouble issues that were pointed out by their answers.
Here is my XML Code:
<RelativeLayout 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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.everythingmath.MainActivity$PlaceholderFragment" >
<GridLayout
android:id="#+id/problemLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:columnCount="5"
android:rowCount="1" >
<TextView
android:id="#+id/firstNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="First Number"
android:textSize="20sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" + "
android:textSize="30sp" />
<TextView
android:id="#+id/secondNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Second Number"
android:textSize="20sp" />
<EditText
android:id="#+id/numTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:hint="Text Goes Here"
android:textSize="20sp"/>
</GridLayout>
</RelativeLayout>
Here is my pertinent Java:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
int firstNumber = createRandomNumber(10);
int secondNumber = createRandomNumber(10);
TextView firstNumText = (TextView)findViewById(R.id.firstNumber);
TextView secondNumText = (TextView)findViewById(R.id.secondNumber);
firstNumText.setText(Integer.toString(firstNumber));
secondNumText.setText(Integer.toString(secondNumber));
}
It is the lines in which I try to set the text that throw the error. The random number generator works fine also.

Localize PlaceholderFragment class inside MainActivity class.
Change public View onCreateView method into
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
int firstNumber = createRandomNumber(10);
int secondNumber = createRandomNumber(10);
TextView firstNumText = (TextView)findViewById(R.id.firstNumber);
TextView secondNumText = (TextView)findViewById(R.id.secondNumber);
firstNumText.setText(Integer.toString(firstNumber));
secondNumText.setText(Integer.toString(secondNumber));
return rootView;
}
You will probably need to move createRandomNumber method to PlaceholderFragment class. And in case you have changed Fragment's name from fragment_main to something else, change it also in this line
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Your current code doesn't work because inside
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
[..]
}
you can only find by ID view (findViewById) which was declared inside activity_main layout. And your TextView views are probably declared inside fragment_main layout.

Related

java.lang.NullPointerException:'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
findViewById returns null in fragment
(2 answers)
Null pointer Exception - findViewById()
(12 answers)
Closed 3 years ago.
I have a problem, I have a button that is in a layout without activity (without class), the layout is called item_list_products. That button is there, but I want to use the .setOnClickListener event in my HomeFragment. Is there a way to solve that? since that is why it gives me the error.
Mi codigo: HomeFragment.class
public class HomeFragment extends Fragment {
private HomeViewModel homeViewModel;
Button bttn_comprar;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
homeViewModel =
ViewModelProviders.of(this).get(HomeViewModel.class);
View root = inflater.inflate(R.layout.fragment_home, container, false);
bttn_comprar = (Button) root.findViewById(R.id.comprarBttn);
//This is where I get the error, since the button is in a different layout.
bttn_comprar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
Mi codigo de layout: item_list_productos
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/idImagen"
android:layout_width="wrap_content"
android:src="#mipmap/ic_launcher"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:layout_marginRight="10dp"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/nombreId"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:text="Nombre producto"
android:layout_marginBottom="5dp"
android:textSize="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/precioId"
android:text="Precio"
android:textSize="20dp"
android:textColor="#000000"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/comprarBttn"
android:layout_width="230dp"
android:layout_height="35dp"
android:textColor="#FFFFFF"
android:background="#248761"
android:text="Comprar"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
You're trying to call onClicklisterner on a view which is not a child view of your fragment layout
public class HomeFragment extends Fragment {
private HomeViewModel homeViewModel;
Button bttn_comprar;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
homeViewModel = ViewModelProviders.of(this).get(HomeViewModel.class);
View root = inflater.inflate(R.layout.item_list_productos, container, false);
bttn_comprar = (Button) root.findViewById(R.id.comprarBttn);
bttn_comprar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
Change your fragment layout to item_list_productos.xml or add your button comprarBttn to your fragment_home.xml layout.

java.lang.IllegalStateException: HorizontalScrollView can host only one direct child

I want to realize the Gallery using HorizontalScrollView. But it throws java.lang.illegalStateException. The logcat hint that the HorizontalScrollView can host only one direct child. I only set one direct child - LinearLayout to it. I searched from the Internet, but haven't solved the problem. Hope anyone can help me. Belows are the code.
xml
<HorizontalScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:scrollbars="none"
>
<LinearLayout
android:id="#+id/gallery_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
</LinearLayout>
</HorizontalScrollView>
item xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingTop="10dp"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:paddingBottom="20dp"
>
<ImageView
android:id="#+id/trend_item_imageview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="8dp"
android:src="#drawable/gallery0"
/>
<TextView
android:id="#+id/trend_item_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="权利的游戏"
android:textSize="16sp"
/>
</LinearLayout>
Fragment
public class DiscoverFragment extends Fragment {
private int[] imageResources = {R.drawable.gallery0, R.drawable.gallery1, R.drawable.gallery2,
R.drawable.gallery3, R.drawable.gallery4, R.drawable.gallery5};
private String[] imageDescriptions = {"权利的游戏", "风吹的风景", "插画背景", "美食君", "吃", "你好四月"};
private List<TrendItem> trendItemList;
private LinearLayout galleryLayout;
public DiscoverFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_discover, container, false);
ButterKnife.bind(this, view);
galleryLayout = ButterKnife.findById(view, R.id.gallery_layout);
initData();
setView();
return view;
}
private void initData(){
trendItemList = new ArrayList<>();
for (int i = 0; i < imageResources.length; i++){
TrendItem trendItem = new TrendItem();
trendItem.setImageResource(imageResources[i]);
trendItem.setText(imageDescriptions[i]);
trendItemList.add(trendItem);
}
}
private void setView(){
for (int i = 0; i < trendItemList.size(); i++){
LayoutInflater inflater = LayoutInflater.from(getContext());
View view = inflater.inflate(R.layout.trend_item, galleryLayout, false);
ImageView trendItemImageView = ButterKnife.findById(view, R.id.trend_item_imageview);
TextView trendItemTextView = ButterKnife.findById(view, R.id.trend_item_textview);
trendItemImageView.setImageResource(trendItemList.get(i).getImageResource());
trendItemTextView.setText(trendItemList.get(i).getText());
galleryLayout.addView(view);
}
}
}
Meaning, you have to add the ImageView, TextView to the Linearlayout. when you add the imageview you are adding it to the HorizontalScrollview which also has a LinearLayout in it their by adding 2 child elements to the HorizontalScrollView which you cannot do.
<HorizontalScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:scrollbars="none">
<LinearLayout
android:id="#+id/gallery_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/trend_item_imageview"
android:layout_width="your_size"
android:layout_height="your_size"
android:src="#drawable/gallery0"/>
<TextView
android:id="#+id/trend_item_textview"
android:layout_width="your_size"
android:layout_height="your_size"
android:text="权利的游戏"
android:textSize="16sp"/>
</LinearLayout>
</HorizontalScrollView>

setText in another layout

So I'm having a little bit of trouble trying to change the text of a TextView in another layout. My MainActivity.java sets the content view as activity_main.xml, which <include>s app_bar_main.xml, which <include>s content_main.xml, where my main app layout is displayed (it's a Navigation Drawer Activity in Android Studio).
Part of my code in MainActivity.java is shown below:
String user, organisation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Default code to include navigation drawer here
if (savedInstanceState == null) {
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
user = bundle.getString("user");
organisation = bundle.getString("organisation");
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View hamburgerMenu = inflater.inflate(R.layout.nav_header_main, null);
TextView navUsername = (TextView) hamburgerMenu.findViewById(R.id.nav_username),
navOrgGroup = (TextView) hamburgerMenu.findViewById(R.id.orgGroup);
navUsername.setText(user);
navOrgGroup.setText(organisation);
}
}
}
And my nav_header_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="#dimen/nav_header_height"
android:background="#drawable/side_nav_bar"
android:gravity="bottom"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="#dimen/nav_header_vertical_spacing"
android:contentDescription="#string/user"
android:src="#android:drawable/sym_def_app_icon" />
<TextView
android:id="#+id/nav_username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="#dimen/nav_header_vertical_spacing"
android:text="#string/user"
android:textAppearance="#style/TextAppearance.AppCompat.Body1" />
<TextView
android:id="#+id/orgGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/email" />
</LinearLayout>
But for some reason the TextViews in nav_header_main.xml never changes. It remains as the default values set in the XML file. Why is this so? Thanks in advance!
Since my comment helped solve:
In my code I'm using somewhat of a different strategy to change the TextView in the navigation drawer. View v = navigationView.getHeaderView(0); TextView emailTextView = (TextView) v.findViewById(R.id.emailTextView);
As for the explanation, you might take a look at this question. It'd be redundant that I copy the text here.
your hamburgerMenu has inflated but not add to any viewGroup to show it

Get textView value from fragment to MainActivity

I am using fragments. I have an textview in fragment and I want to get value in main activity.
This is my fragment layout
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/GridLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="30dp"
android:layout_marginEnd="50dp"
android:layout_marginStart="55dp"
android:layout_marginTop="10dp"
android:columnCount="20"
android:orientation="horizontal"
android:rowCount="16"
tools:context="com.lipi.worldofelements.MainFragment">
<Space
android:layout_width="25dp"
android:layout_height="35dp"
android:layout_column="2"
android:layout_row="2"
android:background="#color/colorButtonNobelGasses" />
<LinearLayout
android:layout_width="505dp"
android:layout_height="165dp"
android:layout_column="4"
android:layout_columnSpan="13"
android:layout_margin="5dp"
android:layout_row="2"
android:layout_rowSpan="5"
android:orientation="horizontal"
>
<RelativeLayout
android:id="#+id/btnElement"
android:layout_width="165dp"
android:layout_height="match_parent"
android:background="#color/colorButtonNonmetals"
android:clickable="true"
>
<TextView
android:id="#+id/txtElemSym"
style="#style/AppTheme"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="25dp"
android:clickable="true"
android:gravity="center"
android:linksClickable="true"
android:onClick="btnClikcedToast"
android:text="#string/H"
android:textColor="#ffff"
android:textSize="#dimen/buttonXL"
/>
I am loading fragment with this function inside my MainActivity.java:
//Set the fragment activity
MainFragment fragment = new MainFragment();
FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
This my fragment class
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
databaseHelper = new ElementDatabaseAdapter(getActivity());
txtElemSym = (TextView) rootView.findViewById(R.id.txtElemSym);
return rootView;
When I click the textview(txtElemSym) main activity runs "btnClikcedToast" function inside my MainActivity .
public void btnClikcedToast(View view) {
txtSymbol = (TextView) findViewById(R.id.txtElemSym);
String ElemSymbol = (String) txtSymbol.getText();
Bundle b;
Intent i = new Intent(this, SingleElementData.class);
b = ActivityOptions.makeScaleUpAnimation(view, 0, 0, view.getWidth(), view.getHeight()).toBundle();
i.putExtra("symbol", ElemSymbol);
startActivity(i, b);
}
I want to get textvalue in this function. I got an error "NullPointerException" after I run this.
How can I do this?

Android: Putting constraint on one value of the Seekbar compare to Other one

I have two SeekBars in my Activity but now I want to put constraint that difference of value of SeekBar greater than and equal to one. How can I do that? Here is my xml file:
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Rs. 0L"
android:id="#+id/min_budget"
/>
<SeekBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/budget_min_seekbar"
/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="No Limit"
android:id="#+id/max_budget"
/>
<SeekBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/budget_max_seekbar"
/>
</LinearLayout>
and corresponding Java file looks like this:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_budget_filter, container, false);
SeekBar max_budget_sbar = (SeekBar) rootView.findViewById(R.id.budget_max_seekbar);
TextView max_budget_tv = (TextView) rootView.findViewById(R.id.max_budget);
SeekBar min_budget_sbar = (SeekBar) rootView.findViewById(R.id.budget_min_seekbar);
TextView min_budget_tv = (TextView) rootView.findViewById(R.id.min_budget);
AndroidSeekBar set_max= new AndroidSeekBar(max_budget_sbar, max_budget_tv,1);
AndroidSeekBar set_min= new AndroidSeekBar(min_budget_sbar, min_budget_tv,1);
return rootView;
}
AndroidSeekBar class sets the value of texviews according to position of SeekBar and has this code:
.....
public AndroidSeekBar(SeekBar id1, TextView textid,int type){
/** Called when the activity is first created. */
PRICEbar = id1; // make seekbar object
SeekValue = textid;
int progress = PRICEbar.getProgress();
PRICEbar.setTag(String.valueOf(type));
PRICEbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
int type=Integer.parseInt(seekBar.getTag().toString());
if(type==1){
if(progress>95){
SeekValue.setText("No Limit");
}
else{
float value = (float)(progress*2/10);
SeekValue.setText("Rs. "+ String.valueOf(progress) + " L");
}
}
}
....
}

Categories