在运行时更改TextView

时间:2011-06-20 11:11:21

标签: java android

我的代码是这样的 - 我正在尝试获取 facebook 个人资料数据 例如名称,电子邮件等并希望将其替换为 在我自己的UI上 我能够获取数据,现在我想更新我的UI 有真实数据。因为我没有使用onCreate(),我得到了NPE 当我打电话给setText(b.getString(key));时 我应该怎么做,因为我的状态保存在Bundle b 所以overrriding onCreate()似乎没有选择? 任何帮助?

package com.android.soapbox;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.android.soapbox.SoapboxApplication.ProfileEventListener;

public class ProfileInfoListner extends Activity  implements ProfileEventListener
{
public TextView mFirstNameTextBox  ;
public TextView mLastNameTextBox  ;


public void ProfileInfoAvailable(Bundle b)
{
 Log.e("Facebook-Example", "Login_sucess"); 
//Go though all the info in the bundle and display

try
{

    for (String key : b.keySet()) 
    {

        if(key.compareTo(SoapboxApplication.FIRST_NAME) == 0)
        {
            Log.e("Facebook-Example", "Log-Printed");   
            //Assuming mFirstNameTextBox points to the textbox on PRofile screen



      if(mFirstNameTextBox!=null)
      {

              Log.e("Facebook-Example", "nnF");
              // NPE
          mFirstNameTextBox.setText(b.getString(key));
      }


        }

}
}
catch(NullPointerException c)
{
    Log.e("ERROR","NPE2"+c.fillInStackTrace());
}

    }   


}

1 个答案:

答案 0 :(得分:0)

您必须确保除了UI线程之外没有其他线程正在执行您的ProfileInfoAvailable方法。您可以使用以下代码确保这一点

runOnUiThread(new Runnable() {
    public void run() {
        mFirstNameTextBox.setText(b.getString(key));
    }
}

活动的onCreate方法始终在UI线程上运行。如果你想使用它,添加这样的东西

Intent i = new Intent(CurrentIntent.this, NewIntentToLaunch.class);
i.putExtra("name", userName);
...add more data
startActivity(i);

启动活动并使用类似的内容

public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  Bundle extras = this.getIntent().getExtras();
  if (extras != null && extras.containsKey("name")) {
      String userName = this.getIntent().getExtras().getString("name");
  }
}

在你的onCreate方法中读取它。