Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
799 views
in Technique[技术] by (71.8m points)

android - findViewById() not working in a not MainActivity class

I have a text view in my Lyout and I would like to set some text to this textview. This should be made in a class which is not a MainActivity class.

The problem is that I got a null pointer exception.

Here is my code:

public class UserInformations extends Activity{

TextView emailTextView;
LocalDatabase localdatabase= new LocalDatabase(this);


    public void getUserInformation()
    {
    emailTextView = (TextView) findViewById(R.id.EmailTextView);
    String email = localdatabase.getUserEmail();
    emailTextView.setText(email);
    }
}

When I am doing this in the Main Activity class, it works, but it doesn't work not in another class.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Calling findViewById() on the Activity object will only work if the current Activity layout is set by setContentView. If you add a layout through some other means, then you need the View object of the layout and call findViewById() on it.

View v = inflater.inflate(id_number_of_layout); # such as R.layout.activity_main
View innerView = v.findViewById(id_number_of_view_inside_v);

If the layout is supposed to be the main layout of the activity, then do this:

public class MyActivity extends Activity{
  TextView emailTextView; 

  @Override
  public void onCreate(Bundle savedInstanceState){
     super.onCreate(savedInstanceState);
     setContentView(id_number_of_layout);
     emailTextView = (TextView) findViewById(R.id.EmailTextView);
     // ... whatever other set up you need to do ...
  }

  public void getUserInformation() {
     // .... regular code ... 
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...