-1

So I created a Navigation Drawer Activity and some fragments. On one fragment I have a textView in which I need to show the date like dd.MM.yyyy I managed to do this on a different app using:

//show date
    TextView datumprikaz = (TextView)findViewById(R.id.datumprikaz);
    Date danas = new Date();

    SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
    String novDatum = sdf.format(danas);

    datumprikaz.setText(novDatum);
 //End of show date

But when I use it now in my MainActivity.java it shows the error:

Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

This is the error log, MainActivity.java and my fragment.xml (ignore the big code, the date part is one line) :

https://gist.github.com/anonymous/f19acb835b43111f576bef2791c4a28e

Ivan
  • 816
  • 2
  • 9
  • 14

3 Answers3

0
TextView datumprikaz = (TextView)findViewById(R.id.datumprikaz);

your TextView datumprikaz not is same layout that you setContentView

that's why variable datumprikaz is null

Ganesh Pokale
  • 1,538
  • 1
  • 14
  • 28
0

The reason is that your text view isn't initialized properly and that's why you get a NullPointerException. If your code is in a fragment class you should get the TextView like this:

TextView datumprikaz = (TextView)getView().findViewById(R.id.datumprikaz); 

Hope it works.

Ispas Claudiu
  • 1,890
  • 2
  • 28
  • 54
0

I figured it out ! I just needed to add the code to that fragment (TvrdjavaFragment in my case). This is the code:

public class TvrdjavaFragment extends Fragment {


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


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_tvrdjava, container, false);
    // Inflate the layout for this fragment
    //show date
    TextView datumprikaz = (TextView) view.findViewById(R.id.datumprikaz);
    Date danas = new Date();

    SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
    String novDatum = sdf.format(danas);

    datumprikaz.setText(novDatum);
    //End of show date
    return view;
}

I added the show date (look at comment tags)

Ivan
  • 816
  • 2
  • 9
  • 14