从另一个类访问 TextView [英] Accessing TextView from another class

查看:34
本文介绍了从另一个类访问 TextView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的主要启动类正在加载 main.xml,但我想弄清楚如何从另一个从数据库加载信息的类访问 TextView.我想将该信息发布到 TextView.

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.

到目前为止,我还没有在 Google 上找到任何有用的示例.

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

这是我正在做数据库工作的班级:

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

推荐答案

如果我是你,我会将你所有的 UI 更新保留在你的主要 Activity 类中.您只需让您的 DBWork 类返回您想要显示到您的 Activity 的文本.所以像:

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()); 
    }
}

然后是你的数据库类:

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

请注意,您在 onCreate 期间执行的任何数据库操作都应尽可能快,因为它们在 UI 线程中运行.如果您要执行长时间运行的数据库查询,那么您应该使用 AsyncTask 或创建一个新的 Thread 并使用 Handler 来更新 UI.

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.

这篇关于从另一个类访问 TextView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆