简体   繁体   English

在运行时更改TextView

[英]Changing TextView at runtime

My code is like this -- I am trying to fetch my facebook profile data such as name , email etc and want to replace it as on my own UI. 我的代码是这样的-我正试图获取我的Facebook个人资料数据,例如姓名,电子邮件等,并希望将其替换为自己的UI。
I am able to fetch the data , now i want to update my UI with a real data .since i am not using onCreate() , i am getting NPE when i called setText(b.getString(key)); 我能够获取数据,现在我想用真实数据更新UI。因为我没有使用onCreate() ,所以我在调用setText(b.getString(key));时得到了NPE setText(b.getString(key)); what should i do , since my state is saved on Bundle b so overrriding onCreate() doesnt seems to an option ?? 我应该怎么做,因为我的状态保存在Bundle b所以过度onCreate()似乎不是一个选择? any help ?? 任何帮助?

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

    }   


}

You have to make sure that no other thread than the UI thread is executing your ProfileInfoAvailable method. 您必须确保除UI线程外,没有其他线程在执行ProfileInfoAvailable方法。 You can make sure of this by using the following code 您可以使用以下代码来确保这一点

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

The onCreate method of an Activity is always run on the UI thread. Activity的onCreate方法始终在UI线程上运行。 If you want to use this, add something like this 如果要使用此功能,请添加如下内容

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

to launch the activity and use something like this 启动活动并使用类似这样的内容

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

to read it in your onCreate method. 在您的onCreate方法中阅读它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM