Jacob Celestine Jacob Celestine - 28 days ago 9
Java Question

Implementing Spinner Inside Fragmnet

First of all, I'm new to android programming, so I am really sorry if this is some noob mistake. I implemented the same file as an activity and it worked. But when I put it into a fragment, it doesn't. I couldn't get a decent tutorial about fragments so what I've implemented comes mostly from theory and sample projects.The error log says, "java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference".

I checked stackoverflow for the same and found the answers where always about wrong ids. But in my case, the id points correctly, I believe. It would be great if someone can help me with this. Oh and also, if you could, please tell me if I've written the code in the appropriate functions. Just to clarify, the function public void equalClicked(View v) is the calculation part that should take place when the button has been clicked. I've been working on this for like almost 2 days now. -_-

Here's my PhotosFragment.java file:

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;

public class PhotosFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters
EditText age,weight,height;
TextView answer,answer2,answer3;
String selected,a,b,c;
RadioGroup gr;
RadioButton r;
double ans1,ans2,ans3;

// TODO: Rename and change types of parameters

private OnFragmentInteractionListener mListener;

public PhotosFragment() {
// Required empty public constructor
}

// TODO: Rename and change types and number of parameters
public static PhotosFragment newInstance() {
PhotosFragment fragment = new PhotosFragment();
return 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
Spinner myspinner=(Spinner) getView().findViewById(R.id.fragment_photos_spinner);
ArrayAdapter<String> myAdapter =new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,getResources().getStringArray(R.array.act));
myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
myspinner.setAdapter(myAdapter);
age= (EditText) getView().findViewById (R.id.fragment_photos_age);
weight= (EditText) getView().findViewById (R.id.fragment_photos_weight);
height= (EditText) getView().findViewById (R.id.fragment_photos_height);
answer= (TextView) getView().findViewById (R.id.fragment_photos_answer);
answer2= (TextView) getView().findViewById (R.id.fragment_photos_answer2);
answer3= (TextView) getView().findViewById (R.id.fragment_photos_answer3);
gr=(RadioGroup) getView().findViewById(R.id.fragment_photos_rgroup);
myspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
@Override
public void onItemSelected (AdapterView<?> parent,View view,int position,long id ){
selected=(String)parent.getItemAtPosition(position);
}
@Override
public void onNothingSelected (AdapterView<?> parent){

}
});
return inflater.inflate(R.layout.fragment_photos, container, false);
}

// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}

@Override
public void onAttach(Context context) {
super.onAttach(context);
}

@Override
public void onDetach() {
super.onDetach();
mListener = null;
}

public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}

public void equalClicked(View v){
double input1= Double.parseDouble(age.getText().toString());
double input2= Double.parseDouble(weight.getText().toString());
double input3= Double.parseDouble(height.getText().toString());
int rid=gr.getCheckedRadioButtonId();
r=(RadioButton) getView().findViewById(rid);
String s=r.getText().toString();
if(s.contentEquals("Male")) {
ans1=((10 * input2) + (6.25 * input3) - (5 * input1) + 5 );
}
else
{
ans1=((10 * input2) + (6.25 * input3) - (5 * input1) - 161 );
}
if(selected.contentEquals("Little to No exercise")){
ans1=ans1 * 1.2;
ans2=ans1 + 1000;
ans3=ans1 - 1000;
a=Double.toString(ans1);
b=Double.toString(ans2);
c=Double.toString(ans3);
answer.setText(a + "cal");
answer2.setText(b + "cal to increase 1 kg in a week");
answer3.setText(c + "cal to decrease 1 kg in a week");

}
else if(selected.contentEquals("Light exercise (1–3 days per week)")){
ans1=ans1 * 1.375;
ans2=ans1 + 1000;
ans3=ans1 - 1000;
a=Double.toString(ans1);
b=Double.toString(ans2);
c=Double.toString(ans3);
answer.setText(a + "cal");
answer2.setText(b + "cal to increase 1 kg in a week");
answer3.setText(c + "cal to decrease 1 kg in a week");
}
else if(selected.contentEquals("Moderate exercise (3–5 days per week)")){
ans1=ans1 * 1.55;
ans2=ans1 + 1000;
ans3=ans1 - 1000;
a=Double.toString(ans1);
b=Double.toString(ans2);
c=Double.toString(ans3);
answer.setText(a + "cal");
answer2.setText(b + "cal to increase 1 kg in a week");
answer3.setText(c + "cal to decrease 1 kg in a week");
}
else if(selected.contentEquals("Heavy exercise (6–7 days per week)")){
ans1=ans1 * 1.725;
ans2=ans1 + 1000;
ans3=ans1 - 1000;
a=Double.toString(ans1);
b=Double.toString(ans2);
c=Double.toString(ans3);
answer.setText(a + "cal");
answer2.setText(b + "cal to increase 1 kg in a week");
answer3.setText(c + "cal to decrease 1 kg in a week");
}
else{
ans1=ans1 * 1.9;
ans2=ans1 + 1000;
ans3=ans1 - 1000;
a=Double.toString(ans1);
b=Double.toString(ans2);
c=Double.toString(ans3);
answer.setText(a + "cal");
answer2.setText(b + "cal to increase 1 kg in a week");
answer3.setText(c + "cal to decrease 1 kg in a week");
}

}
}


Here's it's corresponding xml file:

<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:alpha="0.3"
android:src="@drawable/ic_photo_library_black_24dp" />


<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
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:orientation="vertical"
tools:context=".PhotosFragment">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/lbl_age"
android:textAppearance="?android:attr/textAppearanceLarge"/>
<EditText
android:id="@+id/fragment_photos_age"
android:inputType="number"
android:layout_width="178dp"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/lbl_gender"
android:textAppearance="?android:attr/textAppearanceLarge"/>
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/fragment_photos_rgroup"
android:orientation="horizontal">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/lbl_female"
android:id="@+id/fragment_photos_female"
android:layout_gravity="center_horizontal" />

<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/lbl_male"
android:id="@+id/fragment_photos_male" />

</RadioGroup>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/lbl_weight"
android:textAppearance="?android:attr/textAppearanceLarge"/>

<EditText
android:id="@+id/fragment_photos_weight"
android:inputType="number"
android:layout_width="171dp"
android:layout_height="wrap_content" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/lbl_height"
android:textAppearance="?android:attr/textAppearanceLarge"/>

<EditText
android:id="@+id/fragment_photos_height"
android:inputType="number"
android:layout_width="176dp"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/lbl_daily_activity"
android:textAppearance="?android:attr/textAppearanceLarge"/>

<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/fragment_photos_spinner"
android:layout_gravity="center_horizontal" />

<Button
android:text="@string/btn_calculate"
android:onClick="equalClicked"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/fragment_photos_answer"
android:layout_width="400dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"/>
<TextView
android:id="@+id/fragment_photos_answer2"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"/>
<TextView
android:id="@+id/fragment_photos_answer3"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"/>

</LinearLayout>
</ScrollView>


Here's a log of my error:
Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference

Here's the strings.xml file:

<!-- Calorie -->
<string name="title_calorie">Calorie</string>
<string name="lbl_age">Age</string>
<string name="lbl_gender">Gender</string>
<string name="lbl_female">Female</string>
<string name="lbl_male">Male</string>
<string name="lbl_weight">Weight (in kg)</string>
<string name="lbl_height">Height (in cm)</string>
<string name="lbl_daily_activity">Daily Activity</string>
<string name="btn_calculate">Calculate</string>
<string-array name="act">
<item>Little to No exercise</item>
<item>Light exercise (1–3 days per week)</item>
<item>Moderate exercise (3–5 days per week)</item>
<item>Heavy exercise (6–7 days per week)</item>
<item>Very Heavy exercise (twice per day, extra heavy workouts)</item>
</string-array>

Answer

You have to inflate the View in Fragments before you can search for ids on it. e.g.

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.yourLayoutId, container, false);
    Spinner myspinner=(Spinner) v.findViewById(R.id.fragment_photos_spinner);

    return v;
}