Setting textview text in code - java

Can someone tell me where I am going wrong?
I'm trying to change my textview called MyText to something else, but when I try I get the error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
at android.app.Activity.findViewById(Activity.java:2071)
public class MainScreen extends Activity {
TextView texting = (TextView) findViewById(R.id.MyText);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
texting.setText("Test");
};
}

This is how your code should look like:
public class MainScreen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
// If you're not using this view anywhere, you don't have to declare it globally. Use only a local variables
TextView texting = (TextView) findViewById(R.id.MyText);
texting.setText("Test");
};
}
You should ALWAYS initialize your views after you have your root layout. In this case, right after you did setContentView(R.layout.activity_main_screen); This scenario applies to Activites.
In case you use a fragment you should do this right after you inflated your root layout in the onCreateView method. Something like:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = (LinearLayout) inflater.inflate(R.layout.my_fragment, container, false);
// THIS is where you start initializing your views
return view;
}

The TextView is not available until after setContentView is called. So, findViewById will return null when MainScreen is instantiated. The solution is to move the findViewById call to the onCreate method as follows:
public class MainScreen extends Activity {
TextView texting;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
texting = (TextView) findViewById(R.id.MyText);
texting.setText("Test");
}
}

Do the following:
public class MainScreen extends Activity {
TextView texting;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
texting = = (TextView) findViewById(R.id.MyText);
texting.setText("Test");
};
}
You have to initialize your TextView object inside your onCreate method.

Related

findViewById method outside the onCreate method?

lately, I was working on a very small training project.
But there is one error in my code:
public class MainActivity extends AppCompatActivity {
TextView textView = (TextView) findViewById(R.id.textview);
#override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView.setText("Welcome");
}
}
but when I tried to cut the textview global variable and paste it inside the onCreate method, the error has gone. Why is this error occur although I already have inflated the textView in a global variable ?!
You need to call findViewById(...) after calling setContentView(...).
Fetching the view before inflating the layout isn’t possible since there is no view.
findViewById() should only be used after setContentView() in onCreate.
That's where your entire layout get inflated. Only then you can access views using findViewById().
This is what you want:
public class MainActivity extends AppCompatActivity {
TextView textView;
#override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textview);
textView.setText("Welcome");
}
}

References in code moved from Activity to Fragment no longer resolve

I'm quite new working with Android/Java, so please bear with me.
I moved code from LoginActivity > onCreate into a fragment I created FragmentLogin to method onCreate where many classes no longer resolve, such as findViewById. I'm assuming that somewhere I didn't pass the context of the container Activity properly.
Or some other newbie mistake...
Here is LoginActivity.java [relevant parts copied]
public class LoginActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initialize Fragments //
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
setContentView(R.layout.fragment_login);
}
}
and FragmentLogin.java:
public class FragmentLogin extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_login, container, false);
final ValidationManager Check = new ValidationManager();
final SessionManager Session = new SessionManager(this);
final EditText textEmail = (EditText) findViewById(R.id.login_email);
final EditText textPassword = (EditText) findViewById(R.id.login_pass);
final Button buttonLogIn = (Button) findViewById(R.id.button_login);
final Button buttonSignup = (Button) findViewById(R.id.button_signup);
// Listen for FORGOTTEN PASSWORD click event, open ForgottenPassword Fragment //
final Button forgottenPassword = (Button) findViewById(R.id.button_lost_pass);
forgottenPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContentView(R.layout.fragment_forgotten_password);
}
});
... more code ...
}
}
The variables/methods that were working when the second block of code was residing in the onCreate method of the Activity but no longer resolve after I moved the code to onCreateView of the FragmentLogin fragment class:
findViewById, setContentView
Basically, this is a login form where the default fragment should be login, and a button on that page (Button forgottenPassword) would open another fragment (FragmentForgottenPassword).
Can anyone tell me what I'm doing wrong?
In your activity layout xml file, add something similar to this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<fragment android:name="your.package.FragmentLogin"
android:id="#+id/fragment_login"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
</LinearLayout>
In your LoginActivity: remove the fragment manager stuff. You don't need it yet.
public class LoginActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_login);
}
}
In your FragmentLogin, move the return statement to the end and use the inflated view to find your views by id:
public class FragmentLogin extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final view view = inflater.inflate(R.layout.fragment_login, container, false);
final ValidationManager Check = new ValidationManager();
final SessionManager Session = new SessionManager(this);
final EditText textEmail = (EditText) view.findViewById(R.id.login_email);
final EditText textPassword = (EditText) view.findViewById(R.id.login_pass);
final Button buttonLogIn = (Button) view.findViewById(R.id.button_login);
final Button buttonSignup = (Button) view.findViewById(R.id.button_signup);
// Listen for FORGOTTEN PASSWORD click event, open ForgottenPassword Fragment //
final Button forgottenPassword = (Button) view.findViewById(R.id.button_lost_pass);
forgottenPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContentView(R.layout.fragment_forgotten_password);
}
});
... more code ...
return view;
}
}
You should get subviews from layout while it's being inflated. The layout usually inflated in OnCreateView method.
View layout = inflater.inflate( R.layout.fragment_login, null );
final EditText textEmail = (EditText) layout.findViewById(R.id.login_email);
final EditText textPassword = (EditText) layout.findViewById(R.id.login_pass);
...
return layout;
I am guessing you want to the fragment to be shown within the activity. Try this:
public class LoginActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//put the setContentView() before the fragment initialization also, I noticed your activity layout is the same as your fragment layout,this should not be so, hence I changed that
setContentView(R.layout.activity_login);
// Initialize Fragments //
//you did not initialize the fragments completely, it should be like
//this
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction().replace(R.id.fragment_container, new FragmentLogin()).commit();
}}
then in the Login fragment, it should be like this:
public class FragmentLogin extends Fragment {#Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_login, container, false);
final ValidationManager Check = new ValidationManager();
final SessionManager Session = new SessionManager(this);
final EditText textEmail = (EditText) view.findViewById(R.id.login_email);
final EditText textPassword = (EditText) view.findViewById(R.id.login_pass);
final Button buttonLogIn = (Button) view.findViewById(R.id.button_login);
final Button buttonSignup = (Button) view.findViewById(R.id.button_signup);
// Listen for FORGOTTEN PASSWORD click event, open ForgottenPassword Fragment //
final Button forgottenPassword = (Button) view.findViewById(R.id.button_lost_pass);
forgottenPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//you cant call setContentView in a fragment
}
});
... more code ...
}}
I am not totally sure I caught all your mistakes but I think you should read these: one and two; they are online tutorials on fragments, you can also browse for more. I think it is a good starting point. All the best

Getting Id of a Textview in a fragment OnCreate() method

I am trying to get the Id of a text view in a fragment's onCreate() method. It returns null everytime.
I want to display my contacts in a fragment. For that at the end of FetchContact() method I assign the contact list to TextView.
Since my code is returning null when I find the TextView my application gives NullPointerException.
Anyone who could tell me how to get the Id of TextView of a Fragment in onCreate() method.
I tried making an object of activity class to get the TextView, still the code returned null. No luck.
public class ContactsFragment extends Fragment {
public TextView outputtext;
Context context;
class ActivityObj extends Activity{
public TextView text;
Context objContext;
#Override
public void onCreate(Bundle savedInstanceState) {
text =(TextView)findViewById(R.id.textContact);
objContext = getApplicationContext();
super.onCreate(savedInstanceState);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
ActivityObj obj = new ActivityObj();
super.onCreate(savedInstanceState);
outputtext =(TextView) getView().findViewById(R.id.textContact);
// outputtext= obj.text;
context=getActivity().getApplicationContext();
//fetchContacts();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.contacts_layout, container, false);
return rootView;
}
find the TextView my application gives NullPointerException.
Because in Fragment lifecycle onCreate method called before onCreateView method.
override onViewCreated which call after onCreateView method and use use first parameter of onViewCreated method for accessing views from Fragment layout:
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
TextView text =(TextView)view.findViewById(R.id.textContact);
/// your code here....
}
use
rootView.findViewById(R.id....) in your oncreateView there is where you should do the UI related work
You should use like this on onActivityCreated method
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
TextView tv = (TextView) getActivity().findViewById(R.id.textView1);
}
}
Or use callbacks
You cannot initialize any view using findViewById before onCreateView method calls.
So you must have to wait for the callback to run. And there are two ways to get it. And it will work on onActivityCreated because it called after onCreateView
As described by ρяσѕρєя K using the View param came from onViewCreated.
You can call getView() in any callback(delegate) which call after
onCreateView()
Like
TextView tv = (TextView) getView().findViewById(R.id.tv_id);

Fragment not calling onClick

I've got a Fragment implementing onClickListener. What I have is a custom dialer which must show on the edittext the introduced number. But it doesn't show anything.
This is the Fragment:
PhoneView.java
public class PhoneView extends Fragment implements OnTabChangeListener, OnClickListener {
...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mRoot = inflater.inflate(R.layout.phone_view, null);
mTabHost = (TabHost) mRoot.findViewById(android.R.id.tabhost);
setupTabs();
return mRoot;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
...
ImageButton button1 = (ImageButton) getView().findViewById(R.id.one);
EditText numTxt = (EditText) getView().findViewById(R.id.digits);
...
button1.setOnClickListener(this); //UPDATED - ADDED
...
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.one:
numTxt.setText(numTxt.getText()+"1");
break;
...
you have to call View.setOnClickListener(OnClickListener) of the view you want to react on the click event
In your Activity class, you need to define your Phoneview as you ClickListener to the button or another "view"
Suppose in your activity class, u have a button named deleteButton, and if u want to register a listener for this button... This is how you would do it.
private Button deleteButton= null;
deleteButton.setOnClickListener(PhoneView);

Cannot Switch my Visibility on a TextView through an OnClick event

I have 2 textviews on my android app with ids : textView1 , textView2 . Among others on my main layout OnClickListener I am trying to make these 2 textViews INVISIBLE with this :
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View activity = findViewById(R.id.mainlayout);
activity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
textView1.setVisibility(View.INVISIBLE);
textView2.setVisibility(View.INVISIBLE);
}});
}
I get ... cannot be resolved messages .
Thank you guyz all in advance for your immediate responses.
You need to initialize textviews
TextView textView1,textView2;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
textView1 = (TextView) findViewById(R.id.textView1);
textView2 = (TextView) findViewById(R.id.textView2);
View activity = (View)findViewById(R.id.mainlayout);
Try this:
findViewById(R.id.textView1).setVisibility(View.INVISIBLE);
findViewById(R.id.textView2).setVisibility(View.INVISIBLE);
R.id.textView1 & R.id.textView2 should correspond to the android:id fields of the TextViews you want to make invisible in R.layout.activity_main
If you're still not getting the expected behavior, make sure you're not confusing View.GONE and View.INVISIBLE

Categories