Accessing TextView from another class

26,868

Solution 1

If I were you I'd keep all your UI updates within your main Activity class. You just get your DBWork class to return the text you want displayed to your Activity. So something like:

public class Main extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView tv = (TextView) view.findViewById(R.id.TextView01);
        DBWork db = new DBWork("192.168.2.14:8080/DH/DPost";, "test_db");
        tv.setText(db.getText()); 
    }
}

Then your db class:

public class DBWork{
    ...
    public String getText(){
        //do stuff
        return "";
    }
}

Please note that any database operations you perform during onCreate should be as quick as possible as they are running in the UI thread. If you are going to perform long running database queries then you should use an AsyncTask or create a new Thread and use a Handler to update the UI.

Solution 2

You should use LayoutInflater :

        LayoutInflater inflater = getLayoutInflater();
        View myView = inflater.inflate(R.layout.main, null);
        TextView myTextView = (TextView) findViewById(R.id.myTextViewInXml);

Solution 3

You can pass the references to all your controls after you created your class instance. I personally pass the whole class that has all controls as public variables.

Share:
26,868
Jenny
Author by

Jenny

Updated on December 13, 2020

Comments

  • Jenny
    Jenny over 3 years

    I've got my main startup class loading main.xml but I'm trying to figure out how to access the TextView from another class which is loading information from a database. I would like to publish that information to the TextView.

    So far I've not found any helpful examples on Google.

    EDIT: This is my class that is doing the Database work:

    import android.widget.TextView;import android.view.View; 
    public class DBWork{
        private View view;
    ...
    TextView tv = (TextView) view.findViewById(R.id.TextView01);
    tv.setText("TEXT ME")
    

    Yet, everytime I do that I get a nullpointerexception