第一次加载页面时,操作栏中的android用户名不显示

时间:2014-09-26 08:17:49

标签: android android-actionbar oncreate

您好我是Android的新手,我在将操作系统(通过使用网络服务检索)放入操作栏时遇到了一些问题。

问题是用户名没有显示,显示为' null'当我第一次进入我要显示用户名的页面时。它仅在第二次加载页面时显示(即只有在我转到另一页然后返回到我想要的页面时才显示它显示用户名。)

我希望即使第一次加载页面时也会在操作栏中显示用户名,但我不知道问题是什么。

有人可以帮我解决这个问题吗? 非常感谢你提前。

这是我的代码:

在'菜单'中,我添加了一个项目,其中包含 android:actionViewClass =" android.widget.TextView"

<item 
    android:id="@+id/viewusername"
    android:orderInCategory="1"
    android:title="@+id/viewusername"
    android:showAsAction="always"
    android:actionViewClass="android.widget.TextView"/>

要将用户名放在操作栏中,我使用了 onPrepareOptionsMenu 方法:

@Override
    public boolean onPrepareOptionsMenu(Menu menu) 
    {

        MenuItem menuItem = menu.findItem(R.id.viewusername);
        TextView showusername1 = (TextView) menuItem.getActionView();
        showusername1.setText(String.valueOf(username) );

        return super.onPrepareOptionsMenu(menu);
    }

这是我用来从Web服务检索用户名的方法(我使用过EventHandler):

@Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

        setContentView(R.layout.fragment_dashboard);
        Button incident = (Button) findViewById(R.id.CreateNewIncidentButton);
        SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
        Editor editor = pref.edit();
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            name = extras.getString("ID");
        }

        incident.setOnClickListener(new View.OnClickListener() {
         public void onClick(View v) {          

        // Switching to Register screen         
         Intent i = new Intent(getApplicationContext(), CreateIncident.class);          
         startActivity(i);          
         }          
         });            
         Button request = (Button) findViewById(R.id.CreateNewRequestButton);           
         request.setOnClickListener(new View.OnClickListener() {            
         public void onClick(View v) {

         // Switching to Create new request screen          
         Intent i = new Intent(getApplicationContext(), CreateRequest.class);       
         startActivity(i);          
         }          
         });            
         Button queue = (Button) findViewById(R.id.ViewMyTicketsButton);            
         queue.setOnClickListener(new View.OnClickListener() {          
         public void onClick(View v) {

         // Switching to Register screen        
         Intent i = new Intent(getApplicationContext(), ViewMyTickets.class);       
         startActivity(i);
         }      
         });




         getUsersName();
        }

        public void getUsersName() {        
                    methodName ="getUsersCombo";
             VectorString getUsersCombo = new VectorString(); //creates a new instance of VectorString
             String[] usersCom = { "combo_name"}; //array of values 

                 for (String s : usersCom) { //adds strings to getTicketInfo            
                 getUsersCombo.add(s);

                 }

        EventHandlerDashboard handler2 = new EventHandlerDashboard(this);   
        USD_WebService usdw2 = new USD_WebService(handler2,"http://dsl-116040f.datacom.co.nz:8080/axis/services/USD_R11_WebService?WSDL",60);

        SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
        Editor editor = pref.edit();
        int usersSid = pref.getInt("sid",0);
        String username = pref.getString("username","");

        try {

         //adds all the values to the web service call
         usdw2.doSelectAsync(usersSid, "cnt", "userid="+"'"+username+"'", -1, getUsersCombo);

        } catch (Exception e) {     

         e.printStackTrace();                       
        }                       
        }


        public void receiveResults(String result7){
            try {
                DocumentBuilderFactory dbf =
                    DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                InputSource is = new InputSource();
                is.setCharacterStream(new StringReader(result7));

                Document doc = db.parse(is);
                NodeList nodes = doc.getElementsByTagName("UDSObject");

                // iterate the employees
                for (int i = 0; i < nodes.getLength(); i++) {
                   Element element = (Element) nodes.item(i);

                   NodeList name = element.getElementsByTagName("AttrName");
                   Element line = (Element) name.item(0);
                   System.out.println("ID: " + getCharacterDataFromElement(line));

                   NodeList title = element.getElementsByTagName("AttrValue");
                   line = (Element) title.item(0);
                   System.out.println("ID Value: " + getCharacterDataFromElement(line));
                   userID = getCharacterDataFromElement(line);
             username= "Welcome, "+userID;

                }
            }
            catch (Exception e) {
                e.printStackTrace();
            }

        System.out.println("users comboname"+result7);

        }
        public static String getCharacterDataFromElement(Element e) {
            Node child = e.getFirstChild();
            if (child instanceof CharacterData) {
               CharacterData cd = (CharacterData) child;
               return cd.getData();
            }
            return "?";
        }

注意:当在布局的TextView中使用此方法时,此方法可以正常工作,但当我尝试在操作栏中使用它时,它会出现问题。

更新: 它现在有效:

@Override
    public boolean onPrepareOptionsMenu(Menu menu) 
    {

        MenuItem menuItem = menu.findItem(R.id.viewusername);
        TextView showusername1 = (TextView) menuItem.getActionView();
        showusername1.setText(usersname==null?"":String.valueOf(usersname) );

        return super.onPrepareOptionsMenu(menu);

    }

         getUsersName();
        }

        public void getUsersName() {        
                    methodName ="getUsersCombo";
             VectorString getUsersCombo = new VectorString(); //creates a new instance of VectorString
             String[] usersCom = { "combo_name"}; //array of values 

                 for (String s : usersCom) { //adds strings to getTicketInfo            
                 getUsersCombo.add(s);

                 }

        EventHandlerDashboard handler2 = new EventHandlerDashboard(this);   
        USD_WebService usdw2 = new USD_WebService(handler2,"http://dsl-116040f.datacom.co.nz:8080/axis/services/USD_R11_WebService?WSDL",60);

        SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
        Editor editor = pref.edit();
        int usersSid = pref.getInt("sid",0);
         username = pref.getString("username","");


        try {

         //adds all the values to the web service call
         usdw2.doSelectAsync(usersSid, "cnt", "userid="+"'"+username+"'", -1, getUsersCombo);

        } catch (Exception e) {     

         e.printStackTrace();                       
        }                       

        }






        public void receiveResults(String result7){
            try {
                DocumentBuilderFactory dbf =
                    DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                InputSource is = new InputSource();
                is.setCharacterStream(new StringReader(result7));

                Document doc = db.parse(is);
                NodeList nodes = doc.getElementsByTagName("UDSObject");

                // iterate the employees
                for (int i = 0; i < nodes.getLength(); i++) {
                   Element element = (Element) nodes.item(i);

                   NodeList name = element.getElementsByTagName("AttrName");
                   Element line = (Element) name.item(0);
                   System.out.println("ID: " + getCharacterDataFromElement(line));

                   NodeList title = element.getElementsByTagName("AttrValue");
                   line = (Element) title.item(0);
                   System.out.println("ID Value: " + getCharacterDataFromElement(line));
                   userID = getCharacterDataFromElement(line);
                   usersname = "Welcome, "+userID;

                }
            }
            catch (Exception e) {
                e.printStackTrace();
            }

        System.out.println("users comboname"+result7);

        invalidateOptionsMenu(); // This works on Android 3.x devices only


        }
        public static String getCharacterDataFromElement(Element e) {
            Node child = e.getFirstChild();
            if (child instanceof CharacterData) {
               CharacterData cd = (CharacterData) child;
               return cd.getData();
            }
            return "?";
        }

2 个答案:

答案 0 :(得分:0)

在您检索用户名后致电invalidateOptionsMenu()以强制拨打onPrepareOptionsMenu()

此外,当您正在调用String username = pref.getString("username","");时,您正在创建一个本地变量。在你的onPrepareOptionsMenu上,你似乎正在使用一个字段。删除&#34;字符串&#34;来自您的声明,因此您使用您的字段而不是您的变量。

我已经看到您的用户名已加载到getUsersName();。因此可以肯定地说,在此行之后,字段username将填充真实的用户名。调用invalidateOptionsMenu();强制活动再次创建optionsMenu。这将再次调用onPrepareOptionsMenu(),并使用用户名填充TextView。

答案 1 :(得分:0)

我认为这可能是因为您正在对Web服务器进行异步调用以检索数据。这意味着,当在异步线程中处理该调用时,应用程序的生命周期继续,并且onPrepareOptionsMenu变量在填充username变量之前被调用。因此,在调用onPrepareOptionsMenu时,username仍为""

您可以尝试通过AsyncTask创建异步线程。 AsyncTask允许您在其onPostExecute方法从Web服务器返回数据后,在UI线程上执行某些操作。

您可以使用onPostExecute修改操作栏。只要数据不从Web服务器返回,您就可以在操作栏上显示某种加载器。如果是,则'onPostExecute'将更新acrion栏。这还允许您捕获从Web服务器获取数据时可能遇到的任何故障(低/无互联网连接,断开连接的服务器以及不是什么),并建议您的用户“此刻无法检索其用户名”。您可以通过捕获网络异常或/并在请求上放置计时器来完成此操作。

以下是一些指导您完成此操作的链接:

AsyncTask explained

AsyncTask example (Vogella)