android.view.View.findViewById(int) on a null object reference (Android Lint) - android

I have a problem. I run Lint in android studio and it repaired some parts of my app, but after this app cant start. It writes:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.cewe.martin.cewetracking/com.cewe.martin.cewetracking.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
and I can't find, where is the problem. I can't do Undo, because there are some changed files so i tried to remove parts, which are not typical for me, but it still won't start. Here is onCreate method of MainActivity:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
if (savedInstanceState == null) {
Log.d("START","DO IFU");
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new ScanFragment()).commit();
Log.d("START","ZA GETSUPP");
navigationView.setCheckedItem(R.id.nav_scan);
}
}
You can see Log.d. The first one "DO IFU" shows, the second one no, so I think, that it could be in ScanFragment(). Code here:
public class ScanFragment extends Fragment {
private final EditText rucneKod = (EditText) getView().findViewById(R.id.numberInput);
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_scan, container, false);
Button skenovaciTlacitko = view.findViewById(R.id.button2);
skenovaciTlacitko.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
zapnoutSkener();
}
});
Button rucne = view.findViewById(R.id.button3);
View.OnFocusChangeListener ofcListener = new MyFocusChangeListener();
rucneKod.setOnFocusChangeListener(ofcListener);
final InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
rucne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (rucneKod.getText().length() != 0) {
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
odeslat(rucneKod.getText().toString());
} else {
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
Snackbar snackbar = Snackbar.make(view, R.string.pozadovanKod, Snackbar.LENGTH_LONG);
View sbView = snackbar.getView();
TextView textView = sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
}
}
});
return view;
}
Can somebody see the problematic code? Thanks

private final EditText rucneKod = (EditText)
getView().findViewById(R.id.numberInput);
is causing NPE. Put it inside OnCreateView and repace getView() with view

getView() return the view returned by onCreateView(LayoutInflater,
ViewGroup, Bundle))
Doing this : private final EditText rucneKod = (EditText) getView().findViewById(R.id.numberInput);
it calls getView before onCreateView function, it will be null wich is normal,
Try moving the instantiation inside onCreateView function
Hope this helps

I think the problem is here:
private final EditText rucneKod = (EditText) getView().findViewById(R.id.numberInput);
You should call findViewById inside onCreateView, right after inflating the fragment's layout.
getView() is null when the fragment is constructed, and the stored properties are initialized before onCreateView is called.

Related

Android - setOnClickListern in nav_header_menu

I would add event in nav_header_menu.
I added login and register section then when user click I would show the relative layout page:
https://ibb.co/wwmFzSk
I added fragment_layout_user.xml and ActivityLoginUser class with code:
public class ActivityLoginUser extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_login_user);
ActionBar ab = getSupportActionBar();
ab.setDisplayHomeAsUpEnabled(true);
}}
How can I implement this event in drawer menu?
You can follow below code to access the view of header.
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
View headerview = navigationView.getHeaderView(0);
TextView login= (TextView) headerview.findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Your code here
}
});
I solved it also with #SumitSingh suggestion. I paste here the correct way to solve that.
We need to add this code in the activity class where we added navigation view.
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
View headerview = navigationView.getHeaderView(0);
TextView login= (TextView) headerview.findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Your code here
}
});
Replace // Your code here with:
Intent loginUserIntent = new Intent(getContext(), ActivityLoginUser.class);
/* Start the new activity */
startActivity(loginUserIntent);
If you get error for getContext() please replace it with MainActivity.this
It works for me.

NullPointerException occurs when i tried to change button's state [duplicate]

This question already has answers here:
findViewByID returns null
(33 answers)
Closed 3 years ago.
I'm making app that has 3 fragment and 1 activity.
And I want
if Button at fragment named 'FragmentOper" is clicked,
two buttons in Activity named 'FragmentMain' is disabled.
I have been searched on the internet and found i simple way.
FragmentMain.java
public class FragmentMain extends AppCompatActivity {
public static Button BtnInit, btnOper, btnGraph;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
btnInit = (Button) findViewById(R.id.button1);
btnOper = (Button) findViewById(R.id.button2);
btnGraph = (Button) findViewById(R.id.button3);
setContentView(R.layout.activity_fragment); // added
FragmentMain.context = FragmentMain.this; // added
}
// added to stack Overflow codes
public void changeFragment(View view){
int id = view.getId();
Fragment fragment = null;
switch (id){
case R.id.button1:
fragment = new FragmentInit();
break;
case R.id.button2:
fragment = new FragmentOper();
break;
case R.id.button3:
fragment = new FragmentGraph();
break;
}
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment, fragment);
fragmentTransaction.commit();
}
public void changeState(boolean state){
FragmentMain.btnGraph.setEnabled(state);
FragmentMain.btnInit.setEnabled(state);
}
}
FragmentOper.java
public class FragmentOper extends Fragment{
public Button mStartBtn;
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View myView = inflater.inflate(R.layout.fragment_oper, container, false);
mStartBtn = (Button) myView.findViewById(R.id.startBtn);
mStartBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View myView) {
if (isTimerRunning) // STOP
{
mStartBtn.setText("START");
isTimerRunning = false;
timerHandler.removeCallbacks(timerRunnable);
((FragmentMain)getActivity()).changeState(true);
} else {
mStartBtn.setText("PAUSE"); // Working
startTimer();
((FragmentMain)getActivity()).changeState(false);
}
}
});
return myView;
}
But There is java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setEnabled(boolean)' on a null object reference error in changeState in 'FragmentMain'
When this app is started, I pressed btnINIT and btnGRAPH and it is worked.
And before I add ((FragmentMain)getActivity()).changeState(true); in onclicklistener, it works fine.
So i don't understand why there is an NullPointerException.
I have never declared Buttons in any other place.
How can it fixed?
you are missing the
setContentView(R.layout.activity_main);
in your Activity and setContentView needs to be declared before the buttons are

Communicating between Fragment and Activity

I have a fragment with multiple toggle buttons. On click of a particular button in my Activity, I'd like to upload the status of all these toggle buttons to the server. I see there is one way of doing it as explained in the below link, where we create a listener interface and on every click of each toggle button, we update some tag/integer in the activity corresponding to each toggle button.
https://developer.android.com/training/basics/fragments/communicating.html
But I would like to know if there is any way to know the checked/unchecked status of all toggle buttons in the fragment from the activity without implementing the interface methods for each time a toggle button is clicked. Hope I'm clear.
Here's a working example of how to achieve that. The activity:
public class MainActivity extends AppCompatActivity {
ToggleFragment toggleFragment;
Button updateStatusButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
updateStatusButton = (Button) findViewById(R.id.updateStatusButton);
toggleFragment = ToggleFragment.newInstance();
getSupportFragmentManager().beginTransaction()
.replace(R.id.main_frame, toggleFragment, "ToggleFragment")
.commit();
updateStatusButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean buttonsChecked = toggleFragment.areToggleButtonsChecked();
Toast.makeText(MainActivity.this, String.format("Toggle buttons checked: %s", buttonsChecked), Toast.LENGTH_LONG).show();
}
});
}
}
And the Fragment:
public class ToggleFragment extends Fragment {
ToggleButton toggleButton1;
ToggleButton toggleButton2;
ToggleButton toggleButton3;
public static ToggleFragment newInstance() {
Bundle args = new Bundle();
ToggleFragment fragment = new ToggleFragment();
fragment.setArguments(args);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.toggle_fragment, container, false);
toggleButton1 = (ToggleButton) view.findViewById(R.id.toggleButton1);
toggleButton2 = (ToggleButton) view.findViewById(R.id.toggleButton2);
toggleButton3 = (ToggleButton) view.findViewById(R.id.toggleButton3);
return view;
}
public boolean areToggleButtonsChecked() {
return toggleButton1.isChecked()
&& toggleButton2.isChecked()
&& toggleButton3.isChecked();
}
}
Honestly, the best way that you could accomplish this is with a ViewModel from the Android Architecture Components library. The ViewModel can have an ObservableField or LiveData value that each of the Fragments can observe, and always have the correct information. This would also make it easier to be lifecycle-aware.

Using navigation drawer and toolbar in fragment

I am developing an android app and I want to use a toolbar and a navigation drawer inside a fragment. I created an inner class named Supportclass and then use the method named setUptoolbar in the onCreateView method but I got an abnormal error.
What do you think i should do? Thank you in advance and sorry for my broken English. :)
Fragment code:
public class FragmentVRList extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_main,container,false);
View cardView = inflater.inflate(R.layout.card_vr,container,false);
Generator generator = new Generator();
RecyclerView recyclerView = (RecyclerView)rootView.findViewById(R.id.recycle);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
AdapterVRList adapter = new AdapterVRList(getActivity(), Generator.getData());
recyclerView.setAdapter(adapter);
recyclerView.setNestedScrollingEnabled(false);
SupportClass supportClass = new SupportClass();
supportClass.setUptoolbar(getActivity(),rootView);
final TeacherNet teacher = new TeacherNet(getActivity());
int Length = Generator.getData().size();
final JSONObject object = new JSONObject();
for (int position = 1;position<Length;position++){
switch (position){
case 1:
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
object.put("vrcode","1");
teacher.SelectContent(object);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
case 2:
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
object.put("vrcode","2");
teacher.SelectContent(object);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
case 3:
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
object.put("vrcode","3");
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
return rootView;
}
private class SupportClass extends AppCompatActivity{
public void setUptoolbar(Activity activity, View view){
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawerLayout = (DrawerLayout) view.findViewById(R.id.drawer);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(activity,drawerLayout,toolbar,0,0);
toggle.syncState();
drawerLayout.addDrawerListener(toggle);
}
}
}
This is the error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
You are all the way wrong with your approach. You can do it without defining a new class which extends activity. You always have reference to underlying activity via getActivity (). Even if you want to keep a reference just use MainActivity a = (MainActivity) getActivity () assuming that your fragment is attached to MainActivity. Then operate on a. You are getting that error because you are using
SupportClass supportClass = new SupportClass();
Activities are started using Context.startActivity(Intent intent). It seems that you don't intend to start new activity. You just want to change properties of underlying activity. So as I said above use
MainActivity a = (MainActivity) getActivity () and play with a like a.setSupportActionBar ().
you are using the wrong hierarchy. Correct way is:
Activity -> contains your toolbar, drawer and fragment holder (e.g.
frame layout or viewpager)
Now if you want to open the drawer from some action in fragment you have to add abstract event listener in fragment which will be implemented by activity.
see this quick link on github for more : http://guides.codepath.com/android/fragment-navigation-drawer

Onclick in fragment, FATAL EXCEPTION. Shared preferences to a fragment

Basic info
I am using the Settings Activity and navigation menu : and i have button to display the data (which is the number) from the settings to a textview. It's a sms app
Problem
I have the textview in context_main (The first screen when you start the app) But i would really like to have the textview in my fragment and when i press the button "the onlick" will display the value from settings.
The Button is in the fragment. and when i click the button it works^^ for the context_main se below code.
public void displayData(View view){
SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(this);
String restoredText = prefs.getString("example_text", "");
radertst.setText(restoredText);
}
But when i press a button to send a sms and i linked it with the textfield for where the number is but then i get this.
09-16 20:47:03.501 5389-5389/c.timno.smsgsm20 E/AndroidRuntime: FATAL EXCEPTION: main
Process: c.timno.smsgsm20, PID: 5389
java.lang.NullPointerException
at c.timno.smsgsm20.FirstFragment$1$override.onClick(FirstFragment.java:102)
at c.timno.smsgsm20.FirstFragment$1$override.access$dispatch(FirstFragment.java)
at c.timno.smsgsm20.FirstFragment$1.onClick(FirstFragment.java:0)
at android.view.View.performClick(View.java:4443)
at android.view.View$PerformClick.run(View.java:18475)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:788)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:604)
at dalvik.system.NativeStart.main(Native Method)
This my
MainActivity java class
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
TextView tstnr;
TextView radertst;
EditText nantxt;
Button sendSMSaon;
EditText aonTxt;
TextView nrladd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
tstnr = (TextView) findViewById(R.id.nummertestsp);
radertst = (TextView) findViewById(R.id.raderanumtxt);
nantxt =(EditText) findViewById(R.id.nummer);
sendSMSaon = (Button)findViewById(R.id.skickaaon);
aonTxt = (EditText)findViewById(R.id.aon);
nrladd = (TextView)findViewById(R.id.numretladd);
}
//This is where the call for the value in the setttings are.
//Här är så att man kan lägga in values från inställningar till mainactivity.
public void displayData(View view){
SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(this);
String name = prefs.getString("example_text", "");
radertst.setText(name + " ");
}
//downbelow is where the onresume so the value boots up with the app.
//nedanför är för att appen ska ladda koden i settings direkt när man startar
#Override
protected void onResume() {
super.onResume();
SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(this);
String name = prefs.getString("example_text", "");
radertst.setText(name + " ");}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
android.app.FragmentManager fragmentManager = getFragmentManager();
if (id == R.id.nav_first_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new FirstFragment())
.commit();
// Handle the camera action
} else if (id == R.id.nav_second_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new SecondFragment())
.commit();
} else if (id == R.id.nav_third_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new ThirdFragment())
.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
The fragment java file
public class FirstFragment extends Fragment {
private View view ;
public FirstFragment(){
}
Button sendSMS;
Button sendSMSaon;
Button sendSMSaoff;
Button sendSMSrela1;
Button sendSMSrela2;
EditText msgTxt;
EditText numTxt;
EditText aonTxt;
EditText aoffTxt;
EditText rela1txt;
EditText rela2txt;
Button taframnummer;
TextView nyanumtxt;
TextView ifirt;
TextView tstnr;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.first_layout, container, false);
nyanumtxt = (TextView)view.findViewById(R.id.raderanumtxt);
sendSMS = (Button)view.findViewById(R.id.skicka);
sendSMSaon = (Button)view.findViewById(R.id.skickaaon);
sendSMSaoff = (Button)view.findViewById(R.id.skickaaoff);
sendSMSrela1 = (Button)view.findViewById(R.id.skickarela1);
sendSMSrela2 = (Button)view.findViewById(R.id.skickarela2);
msgTxt = (EditText)view.findViewById(R.id.Textmeddelande);
numTxt = (EditText)view.findViewById(R.id.nummer);
aonTxt = (EditText)view.findViewById(R.id.aon);
aoffTxt = (EditText)view.findViewById(R.id.aoff);
rela1txt = (EditText)view.findViewById(R.id.rela1txt);
rela2txt = (EditText)view.findViewById(R.id.relä2txt);
taframnummer = (Button) view.findViewById(R.id.taframnummer);
tstnr = (TextView) view.findViewById(R.id.numretladd);
msgTxt.setVisibility(View.INVISIBLE);
aonTxt.setVisibility(View.INVISIBLE);
aoffTxt.setVisibility(View.INVISIBLE);
rela1txt.setVisibility(View.INVISIBLE);
rela2txt.setVisibility(View.INVISIBLE);
//testnedan
LayoutInflater lf = getActivity().getLayoutInflater();
view = lf.inflate(R.layout.first_layout, container, false);
//ovantest
sendSMSaoff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mymsgaoff = aoffTxt.getText().toString();
String theNumber = numTxt.getText().toString();
sendMsg(theNumber, mymsgaoff);
}
}
);
sendSMSaon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mymsgaon = aonTxt.getText().toString();
String theNumber = nyanumtxt.getText().toString();
sendMsg(theNumber, mymsgaon);
}
}
);
sendSMS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String myMsg = msgTxt.getText().toString();
String theNumber = numTxt.getText().toString();
sendMsg(theNumber, myMsg);
}
}
);
sendSMSrela1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String myMsgrela1 = rela1txt.getText().toString();
String theNumber = numTxt.getText().toString();
sendMsg(theNumber, myMsgrela1);
}
}
);
sendSMSrela2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mymsgrela2 = rela2txt.getText().toString();
String theNumber = numTxt.getText().toString();
sendMsg(theNumber, mymsgrela2);
}
}
);
return view;
}
private void sendMsg(String theNumber, String myMsg)
{
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(theNumber, null, myMsg, null, null);
}
}
if you look at
sendSMSaoff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mymsgaoff = aoffTxt.getText().toString();
String theNumber = numTxt.getText().toString();
sendMsg(theNumber, mymsgaoff);
}
The numTxt is where i want the value to be loaded and it's in the first layout xml not context_main. So for some reason it wont be loaded there. Imgur image
If I'm understanding you correctly, R.id.raderanumtxt is in the MainActivity's layout file and not FirstFragment's.
That means that it won't be found in the onCreateView() method of FirstFragment the way you're accessing it. The view object there is the layout you just loaded:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.first_layout, container, false);
nyanumtxt = (TextView)view.findViewById(R.id.raderanumtxt); // <- this assignment won't work
...
}
You're also inflating R.layout.first_layout twice, which is unnecessary.
To get access to a View in the Activity, you can do something like this:
View view = getActivity().findViewById(R.id.viewid);
EDIT:
Without seeing your layouts, I can't be sure, but try and replace:
nyanumtxt = (TextView)view.findViewById(R.id.raderanumtxt);
... with:
nyanumtxt = (TextView) getActivity().findViewById(R.id.raderanumtxt);
That way you're looking for R.id.raderanumtxt in the entire Activity layout. This will only work if the Activity is available and the layout has already been added, so to be safer I'd move this assignment to onViewCreated() instead of onCreateView().

Categories

Resources