Android TextView无法更新

时间:2013-11-25 05:26:06

标签: android textview

我正在开发一款Android应用。请参阅下面的Java代码。您能解释一下为什么textView不会在代码中的特定行更新,而是在其他行更新。我在代码中对它们进行了评论。

我已经更新了代码,见下文。 想法是从服务器获取Facebook个人资料。当profiling_status等于2意味着配置文件没有准备好,所以我只是ping服务器,直到我得到profiling_status!= 2 .. 我尝试了进展对话框,但放弃了因为我将我的活动放在一个帖子中,但后来我无法得到一些信息,因为我应该在nonUIThread中运行它。试过但我失败了,我失去了耐心......所以决定在我ping服务器时我应该打印"加载配置文件。请稍候。"没有乱,没有大惊小怪!只是如上所述,textView没有更新。有趣的是.. System.out.println(" Here");被执行。我目前只在AVD上运行它,因为服务器不在无线网络上,因此我无法使用手机进行测试。

public class SelectionFragment extends Fragment {

    private ProfilePictureView profilePictureView;
    private TextView userNameView;
    private UiLifecycleHelper uiHelper;
    private static final int REAUTH_ACTIVITY_CODE = 100;
    private TextView textView;
    private String username = null;
    Context context;
    JSONObject json = null;
    JSONObject json_facebook = null;
    int time = 0;
    int time_interval = 3000;
    int profiling_status = 2;
    String logincode;
    String usermessage = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        uiHelper = new UiLifecycleHelper(getActivity(), callback);
        uiHelper.onCreate(savedInstanceState);

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REAUTH_ACTIVITY_CODE) {
            uiHelper.onActivityResult(requestCode, resultCode, data);
        }
    }

    private Session.StatusCallback callback = new Session.StatusCallback() {
        @Override
        public void call(final Session session, final SessionState state, final Exception exception) {
            onSessionStateChange(session, state, exception);
        }
    };

    private void deleteProfile() throws JSONException {
        IDThiefHTTPRequest.deleteProfile();
        textView.setTextColor(Color.GRAY);
        textView.setGravity(Gravity.CENTER);
        textView.setText("Press Get profile info button to process your risk of identity theft");

        //Facebook logout
        Session session2 = Session.getActiveSession();
        if (session2 != null) {
            session2.close();
        }
        else {
            session2 = new Session(context);
            Session.setActiveSession(session2);
            session2.close();
        }
    }

    private String readRiskScoreArray(JSONArray json_riskscore) throws NumberFormatException, JSONException{

        //get the risk score with only two digits 
        double risk_score = Double.valueOf(json_riskscore.get(0).toString());
        String risk_score2digits = new DecimalFormat("##.##").format(risk_score);

        String usermessage = "Your risk score is: ";
        usermessage = usermessage + risk_score2digits;
        usermessage = usermessage + " which is ranked as: ";
        usermessage = usermessage + json_riskscore.get(2).toString();

        JSONArray json_reasons = json_riskscore.getJSONArray(1);

        for (int i = 0; i < json_reasons.length(); i++){
            JSONArray json_reason = json_reasons.getJSONArray(i);
            JSONArray json_reasondetails = json_reason.getJSONArray(1);
            usermessage = usermessage + "\n\nReason: ";
            usermessage = usermessage + json_reasondetails.get(0);
            usermessage = usermessage + "\n\nIDThief suggests you to: ";
            usermessage = usermessage + json_reasondetails.get(1);
            usermessage = usermessage + "\n\nFix it through this link:\n";
            usermessage = usermessage + json_reasondetails.get(2);
        }

        return usermessage;
    }


    private void displayProfileInfo() throws JSONException {

      Session session = Session.getActiveSession();
      if (session.isOpened()) {
            System.out.println(session.getAccessToken());
      }
      if (username != null) {
          System.out.println("Login stage: Getting profile info for user:" + username);
          logincode = username + "!" + session.getAccessToken();

          json = IDThiefHTTPRequest.makeLoginHTTPRequest(logincode);
          System.out.println(json.toString(4));
          json_facebook = json.getJSONObject("facebook");
          //profiling_status
          profiling_status = Integer.valueOf(json_facebook.get("profiling_status").toString());

          if (profiling_status == 2) {

              try {
                  while (profiling_status == 2 && time < 100000) {

                     textView.setTextColor(Color.BLACK);
                     textView.setGravity(Gravity.NO_GRAVITY);
                     textView.setText("Loading profile. Please wait.");
                     System.out.println("Here");


                     try {
                            Thread.sleep(time_interval);
                            time += time_interval;
                      } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                      }

                      json = IDThiefHTTPRequest.makeLoginHTTPRequest(logincode);
                      json_facebook = json.getJSONObject("facebook");
                      //profiling_status
                      profiling_status = Integer.valueOf(json_facebook.get("profiling_status").toString());

                 }

                 if (time >= 100000) {
                     System.out.println("Time is out");
                     textView.setText("Server is not responding. Please try again later.");
                 }


               }
               catch (Exception e)
              {
                   e.printStackTrace();
              }
           }
          JSONArray json_riskscore = json_facebook.getJSONArray("risk_score");
          System.out.println(json_riskscore.toString(4));

          usermessage = readRiskScoreArray(json_riskscore);
          textView.setTextColor(Color.BLACK);
          textView.setGravity(Gravity.NO_GRAVITY);
          textView.setText(usermessage);


      }
      else System.out.println("username is null");

    }

    @SuppressLint("NewApi")
    @Override
    public View onCreateView(LayoutInflater inflater, 
            ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.selection, 
                container, false);

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
        StrictMode.setThreadPolicy(policy);

        Button deletebutton = (Button) view.findViewById(R.id.ImageButton2);

        deletebutton.setOnClickListener(new View.OnClickListener()
        {
              public void onClick(View v)
              {
                try {
                    deleteProfile();

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
              }
        });

        Button button = (Button) view.findViewById(R.id.ImageButton1);
        textView = (TextView) view.findViewById(R.id.profiletext);
        textView.setMovementMethod(new ScrollingMovementMethod());
        textView.setMovementMethod(LinkMovementMethod.getInstance());

        button.setOnClickListener(new View.OnClickListener()
        {
          public void onClick(View v)
          {
            try {
                displayProfileInfo();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }  
          }
        });

        // Find the user's profile picture custom view
        profilePictureView = (ProfilePictureView) view.findViewById(R.id.selection_profile_pic);
        profilePictureView.setCropped(true);

        // Find the user's name view
        userNameView = (TextView) view.findViewById(R.id.selection_user_name);

        // Check for an open session
        Session session = Session.getActiveSession();
        if (session != null && session.isOpened()) {
            // Get the user's data
            makeMeRequest(session);
        }

        return view;
    }

    private void makeMeRequest(final Session session) {
        // Make an API call to get user data and define a 
        // new callback to handle the response.
        Request request = Request.newMeRequest(session, 
                new Request.GraphUserCallback() {
            @Override
            public void onCompleted(GraphUser user, Response response) {
                // If the response is successful
                if (session == Session.getActiveSession()) {
                    if (user != null) {
                        // Set the id for the ProfilePictureView
                        // view that in turn displays the profile picture.
                        profilePictureView.setProfileId(user.getId());
                        // Set the Textview's text to the user's name.
                        userNameView.setText(user.getName());
                        username = user.getUsername();
                        //System.out.println("Log in=====================================");
                    }
                }
                if (response.getError() != null) {
                    // Handle errors, will do so later.
                }
            }
        });
        request.executeAsync();
    } 

    private void onSessionStateChange(final Session session, SessionState state, Exception exception) {
        if (session != null && session.isOpened()) {
            // Get the user's data.
            makeMeRequest(session);
        }
        else if (session != null && session.isClosed()) {
            textView.setTextColor(Color.GRAY);
            textView.setGravity(Gravity.CENTER);
            textView.setText("Press Get profile info button to process your risk of identity theft");

        }
    }


    @Override
    public void onResume() {
        super.onResume();
        uiHelper.onResume();
    }

    @Override
    public void onSaveInstanceState(Bundle bundle) {
        super.onSaveInstanceState(bundle);
        uiHelper.onSaveInstanceState(bundle);
    }

    @Override
    public void onPause() {
        super.onPause();
        uiHelper.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        uiHelper.onDestroy();
    }
}

3 个答案:

答案 0 :(得分:0)

我的用户名是一个字符串。通常情况下,使用!username.equals()不要在字符串比较中使用!=。该代码可能无法执行

答案 1 :(得分:0)

if (username != null  || !username.equals("")) { 
//to do
}

答案 2 :(得分:0)

请尝试按照以下方式比较字符串,不要使用==使用equalsIgnoreCase()equals()方法。

 if (profiling_status.equalsIgnoreCase("2")) {
            //would not update here either
            try {
                while (profiling_status.equalsIgnoreCase("2") && time < 100000) {
                    textView.setText("Loading profile. Please wait.");
                     try {
                           Thread.sleep(time_interval);
                           time += time_interval;
                     } catch (InterruptedException e) {
                           e.printStackTrace();
                     }
相关问题