Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update Android TextView

I have an simple android app that I want to write on the display the value of a single field, that belongs to a different class.

Using the simple text view I can write the initial value of the field but I don't know how to update the text on the display whenever the field has changed value.

Btw, it is my first android app so im still lost

Here is my activity code:

public class findIT extends Activity {
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    PositionHolder ph = new PositionHolder();
    TextView tv = new TextView(this);
    setContentView(tv);
    //this.updateText();
    tv.setText("You are at "  + ph.getPosition());
  }
}
like image 372
tropicana Avatar asked Mar 29 '11 18:03

tropicana


2 Answers

You need to create a TextView in an xml layout as following:

<TextView 
android:id="@id/textView01"
android:text="Enter your initial text "
android:layout_width="wrap content"
android:layout_height="wrap content"
></TextView>

Then write the following in your class after setContentView() function:

TextView textView = (TextView) findViewById(R.id.textView01);
textView.setText("Enter whatever you Like!");
like image 101
Mo24290 Avatar answered Oct 19 '22 06:10

Mo24290


Chris.... Here is a most basic way to develop an app. Divide up the problem into three pieces. The presentation or view. The algorithm or model. The Controller that responds to user and system events. This creates a "separation of concerns" such that the Controller owns the view and the model. You create the view using xml as in main.xml. You create a separate class to do the work say MyModel.java and of course there is the Controller or the Activity class say MyActivity.java. So the data comes from the model goes to the Controller that updates the view.

So your question is how to get the data from the model and update the view. Naturally this will take place in the controller, your Activity. The simplest way to do this is to put a button in the activity and when the user hits the button, call model.getLatestData() and update the view. This is PULLing data. The next way is for the Controller to check for an update say every minute. This is POLLING for data. The next way is for the Controller to register an interest in changes to the model and sit around waiting for the model to signal a change and then update the view. This is asynchronous PUSHING of data from the model to the controller and could be done with the OBSERVER pattern.

I know this makes no sense to you when you are struggling with trying to just get the code to work, but hopefully I have planted the seed of an idea in your head that will bother you and make sense sometime in the future.

JAL

like image 44
JAL Avatar answered Oct 19 '22 05:10

JAL