Android: TextView not updating - java

I got one EditText and one TextView, and I want to update my TextView in each Iteration (ConsoleWindow is running in a loop; it gets called from a handler and thus is running on the UIthread).
The Problem is that my TextView only gets updated in the first round, and then it keeps the first entry for the rest of the runtime (although the dataString is a different one in each round):
private void ConsoleWindow(String dataString) {
LinearLayout layout = new LinearLayout(getApplicationContext());
if (first2) { //first2 is true when application is launched
// ONLY SET LAYOUT AND EDITTEXT IN FIRST RUN TO SAVE CAPACITY
// LINEAR LAYOUT
setContentView(layout);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setBackgroundColor(Color.parseColor("#000000")); // black
// EDITTEXT
EditText et = new EditText(getApplicationContext());
et.setHint("Enter Command");
layout.addView(et);
first2 = false;
}
// TEXTVIEW
TextView tv = new TextView(getApplicationContext());
tv.setText(dataString); // KEEPS THE SAME UNTIL THE 1ST ROUND
layout.addView(tv);
}
I already tried tv.invalidate() and tv.postInvalidate(), but that didn't have an effect. Could someone help me please?

Put tv a global variable.
private TextView tv;
After this, In your "onCreate()" method:
tv = new TextView(getApplicationContext());
And then:
private void ConsoleWindow(String dataString) {
LinearLayout layout = new LinearLayout(getApplicationContext());
if (first2) { //first2 is true when application is launched
// ONLY SET LAYOUT AND EDITTEXT IN FIRST RUN TO SAVE CAPACITY
// LINEAR LAYOUT
setContentView(layout);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setBackgroundColor(Color.parseColor("#000000")); // black
// EDITTEXT
EditText et = new EditText(getApplicationContext());
et.setHint("Enter Command");
layout.addView(et);
first2 = false;
}
// TEXTVIEW
tv.setText(dataString); // KEEPS THE SAME UNTIL THE 1ST ROUND
layout.addView(tv);
}
Please verify too, if dataString has some text, with something like this
Log.d(TAG , "dataString: " + dataString + "with first time? " + first2.toString());
Try to pass to the setContentView(layout); outside the if statement.Because I can't understand well Why you need this.
LinearLayout layout = new LinearLayout(getApplicationContext());
setContentView(layout);

When first2 is false, you are simply creating a new LinearLayout layout and then without inflating the layout, you are directly adding TextView tv to layout. That's why Textview is not visible.
private void ConsoleWindow(String dataString) {
LinearLayout layout;
TextView tv;
EditText et;
if (first2) {
layout = new LinearLayout(getApplicationContext());
setContentView(layout);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setBackgroundColor(Color.parseColor("#000000"));
// EDITTEXT
et = new EditText(getApplicationContext());
et.setHint("Enter Command");
layout.addView(et);
tv = new TextView(getApplicationContext());
layout.addView(tv);
first2 = false;
}
if(tv != null) {
tv.setText(dataString);
}
}

Related

Null Pointer Exception - Setting the text of a TextView inside a programmatically created layout [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am trying to set the text of a TextView. However, I am receiving the following error whenever I click a button that should add text to the TextView:
NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference" from the logcat.
Currently, the init() function programmatically creates/aligns the TextView inside a linearlayout. Next, I instantiate the TextView Whole1. Then I set the OnClickListener for the buttons that can modify the TextView. The specific line that the error mentions is inside setWholeOnClickListener():
Whole1.setText(button.getText());
I've found What is a NullPointerException, and how do I fix it? as a reference, but haven't had much luck resolving this issue. What did I miss?
The following is my Java file:
public class MainActivity extends AppCompatActivity {
TextView Whole1;
private boolean isNull = true;
private int[] wholeButtons = {R.id.wholeButton1, R.id.wholeButton2, R.id.wholeButton3, R.id.wholeButton4, R.id.wholeButton5, R.id.wholeButton6, R.id.wholeButton7, R.id.wholeButton8, R.id.wholeButton9, R.id.wholeButton0};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
Whole1 = (TextView) findViewById(R.id.Whole1);
setWholeOnClickListener();
}
private void setWholeOnClickListener() {
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Button button = (Button) v;
if (isNull) {
Whole1.setText(button.getText());
isNull = false;
} else {
Whole1.append(button.getText());
}
}
};
for (int id : wholeButtons) {
findViewById(id).setOnClickListener(listener);
}
}
/* Initializes the first view for input */
private void init() {
LinearLayout Result = (LinearLayout) findViewById(R.id.Result);
RelativeLayout Mixed = new RelativeLayout(this);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.MATCH_PARENT);
Mixed.setLayoutParams(params);
TextView Whole1 = new TextView(this);
TextView Fraction1 = new TextView(this);
TextView Num1 = new TextView(this);
TextView Den1 = new TextView(this);
/* Scale is a screen dependent value, used for filling the screen */
final float scale = getResources().getDisplayMetrics().density;
int pixels = (int) (2 * scale + 0.5f);
/* Fraction bar 1 */
params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, pixels);
params.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
params.addRule(RelativeLayout.RIGHT_OF, Whole1.getId());
Fraction1.setBackgroundColor(Color.BLACK);
Fraction1.setText("________"); // Placeholder
Fraction1.setLayoutParams(params);
Mixed.addView(Fraction1);
/* Numerator 1 */
params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
params.addRule(RelativeLayout.ABOVE, Fraction1.getId());
Num1.setText("3");
Num1.setGravity(Gravity.CENTER);
Num1.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25);
Num1.setLayoutParams(params);
Mixed.addView(Num1);
/* Denominator 1 */
params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
params.addRule(RelativeLayout.BELOW, Fraction1.getId());
Den1.setText("4");
Den1.setGravity(Gravity.CENTER);
Den1.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25);
Den1.setLayoutParams(params);
Mixed.addView(Den1);
/* Whole 1 */
params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.MATCH_PARENT);
params.addRule(RelativeLayout.LEFT_OF, Num1.getId());
params.addRule(RelativeLayout.CENTER_VERTICAL);
Whole1.setGravity(Gravity.CENTER);
Whole1.setTextSize(TypedValue.COMPLEX_UNIT_SP, 40);
Whole1.setLayoutParams(params);
Mixed.addView(Whole1);
Result.addView(Mixed);
Result.invalidate();
}
}
Whole1 = (TextView) findViewById(R.id.Whole1);
finds a TextView with the id R.id.Whole1 in the activity's layout.
You created a TextView programmatically, assigned it to your Whole1 variable, but then overwrote the variable with the new assignment Whole1 = (TextView) findViewById(R.id.Whole1);.
After that it's probably null because you dont have a TextView with that id in the layout XML that you inflated.

NullPointer while using dynamic view in android

I have created a dynamic view which repeats for a specific times. The view has 2 textViews and 2 radio buttons with default values. I want to change the Text values from program but getting nullpointer exception, Here is my code:
LayoutInflater inflater = (LayoutInflater)context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout scrollViewLinearlayout = (LinearLayout)findViewById(R.id.parent); // The layout inside scroll view
//int count=50;
for(int i = 0; i < Studentlist.length; i++){
String data = Studentlist[i];
String RollNum = data.split("--")[0];
String Name = data.split("--")[1];
LinearLayout layout2 = new LinearLayout(context);
layout2.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
View item = inflater.inflate(R.layout.item_layout, null, false);
layout2.addView(item);
layout2.setId(i);
TextView trollnum = (TextView)findViewById(R.id.RollNum);
trollnum.setText(RollNum);
TextView tname = (TextView)findViewById(R.id.Name);
tname.setText(Name);
scrollViewLinearlayout.addView(layout2);
Log.d("Id is: ", trollnum.getText().toString());
I am getting nullpointer at 'trollnum.setText(RollNum);'
How do i change the text in the View?
You are trying to find the view in the activity's layout where it doesn't exist instead of finding it in the layout you just inflated.
Replace
TextView trollnum = (TextView)findViewById(R.id.RollNum);
TextView tname = (TextView)findViewById(R.id.Name);
With
TextView trollnum = (TextView) item.findViewById(R.id.RollNum);
TextView tname = (TextView) item.findViewById(R.id.Name);

Android How to change data of Textview by clicking on button

First of all, the app looks like this.
How to make - if I click on Add, on its column the textview is updated with value + 1?
I'm creating TextView and Button in a Loop;
for(int i = 0;i < playercountint; i++)
{
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT,(100/playercountint)));
layout.setGravity(Gravity.CENTER_HORIZONTAL);
TextView tt = new TextView(this);
tt.setText("0");
tt.setTextSize(14);
tt.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
tt.setGravity(Gravity.CENTER_HORIZONTAL);
Button btadd = new Button(this);
btadd.setText("Add");
btadd.setId(2);
btadd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
????? what here?
}
});
}
What should be written in onClick function , so only TextView value which is in buttons column is changed.
There is one outer LinearLayout which is horizontally oriented, and those which are created within a loop is vertical Linear Layouts.
Maybe i should create a template for 1 loop iteration?
First make your textview final and them set it's value in onClick
for(int i = 0;i < playercountint; i++)
{
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT,(100/playercountint)));
layout.setGravity(Gravity.CENTER_HORIZONTAL);
final TextView tt = new TextView(this);
tt.setText("0");
tt.setTextSize(14);
tt.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
tt.setGravity(Gravity.CENTER_HORIZONTAL);
Button btadd = new Button(this);
btadd.setText("Add");
btadd.setId(2);
btadd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
tt.setText(String.valueOf(Integer.parseInt(tt.getText())+1));
}
});
}
You can write one function that returns linearlayout:
public View getPlayerView(){
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT,(100/playercountint)));
layout.setGravity(Gravity.CENTER_HORIZONTAL);
final TextView tt = new TextView(this);
tt.setText("0");
tt.setTextSize(14);
tt.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
tt.setGravity(Gravity.CENTER_HORIZONTAL);
Button btadd = new Button(this);
btadd.setText("Add");
btadd.setId(2);
btadd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
tt.setText(String.valueOf(Integer.parseInt(tt.getText())+1));
}
});
layout.add(tt);
layout.add(btadd);
return layout;
}
Call this function in a loop.
tt.setText("something");
tt.invalidate();
my bad I didn't even notice it was a for loop uh you need to hold a reference to the text view.. make your textview final
tt.setText(Integer.parse(tt.getText().toString()) + 1);
But, I strongly recommend you design UI (layout) in the *.xml file!
See more: http://developer.android.com/guide/topics/ui/declaring-layout.html
You should provide your TextView with an unique id (.setId(...)). Having this, in your onClick method simply use something like this:
final TextView tv = (TextView) findViewById(R.id.your_textview_id);
final String cur_text = tv.getText();
Integer plus_one = Integer.valueOf(cur_text);
plus_one++;
tv.setText(plus_one.toString());
Didn't try it but should work.
static int counter = 0;
btn_Add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter ++;
tv_Display.setText("Your Total is : " + counter);
}
});

Checking and changing TextView text color

I have ScroolView and it's inside Linear layout. In this linear layout i added programmically around 20 TextView. When i press any of those TextView i change it color to RED (at first it was white). When i press again the same TextView i check his color and if it's is RED i again make it white.
What i want to do:
I press for example 1 TextView and make it RED. Then when i press 2 TextView i make this one RED and i want to make 1 TextView WHITE. This functionality should be at all TextView.
So any idea's how to do this ?
You mean to say at a time you need only one textview to be red. You can do this using 2 variables. One is a boolean colored. This indicates that at least one TextView is colored. Another is a TextView variable. Create a TextView variable lastColoredTextView. Let it be null initially. Then whenever the textview is clicked, assign the lastColoredTextView to the clicked TextView. Then whenever you are clicking, just check if colored then change the color of lastColoredTextView to white.
Change class name and it will work fine.
public class Test_stflowActivity extends Activity {
TextView current_red_txt_box = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = null;
LinearLayout lp = new LinearLayout(getApplicationContext());
lp.setOrientation(LinearLayout.VERTICAL);
View.OnClickListener txt_click = new View.OnClickListener() {
#Override
public void onClick(View v) {
current_red_txt_box.setTextColor(Color.WHITE);
TextView tv = (TextView) v;
tv.setTextColor(Color.RED);
current_red_txt_box = tv;
}
};
for (int i = 0; i < 20; i++) {
tv = new TextView(getApplicationContext());
tv.setId(i);
tv.setTextSize(40);
tv.setText("you text");
tv.setTextColor(Color.WHITE);
tv.setOnClickListener(txt_click);
lp.addView(tv);
current_red_txt_box = tv;
}
setContentView(lp);
}
}

Create a new TextView programmatically then display it below another TextView

String[] textArray={"one","two","asdasasdf asdf dsdaa"};
int length=textArray.length;
RelativeLayout layout = new RelativeLayout(this);
RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
for(int i=0;i<length;i++){
TextView tv=new TextView(getApplicationContext());
tv.setText(textArray[i]);
relativeParams.addRule(RelativeLayout.BELOW, tv.getId());
layout.addView(tv, relativeParams);
}
I need to do something like that.. so it would display as
one
two
asdfasdfsomething
on the screen..
If it's not important to use a RelativeLayout, you could use a LinearLayout, and do this:
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
Doing this allows you to avoid the addRule method you've tried. You can simply use addView() to add new TextViews.
Complete code:
String[] textArray = {"One", "Two", "Three", "Four"};
LinearLayout linearLayout = new LinearLayout(this);
setContentView(linearLayout);
linearLayout.setOrientation(LinearLayout.VERTICAL);
for( int i = 0; i < textArray.length; i++ )
{
TextView textView = new TextView(this);
textView.setText(textArray[i]);
linearLayout.addView(textView);
}
Try this code:
final String[] str = {"one","two","three","asdfgf"};
final RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
final TextView[] tv = new TextView[10];
for (int i=0; i<str.length; i++)
{
tv[i] = new TextView(this);
RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams
((int)LayoutParams.WRAP_CONTENT,(int)LayoutParams.WRAP_CONTENT);
params.leftMargin = 50;
params.topMargin = i*50;
tv[i].setText(str[i]);
tv[i].setTextSize((float) 20);
tv[i].setPadding(20, 50, 20, 50);
tv[i].setLayoutParams(params);
rl.addView(tv[i]);
}
public View recentView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Create a relative layout and add a button
relativeLayout = new RelativeLayout(this);
btn = new Button(this);
btn.setId((int)System.currentTimeMillis());
recentView = btn;
btn.setText("Click me");
relativeLayout.addView(btn);
setContentView(relativeLayout);
btn.setOnClickListener(new View.OnClickListener() {
#Overr ide
public void onClick(View view) {
//Create a textView, set a random ID and position it below the most recently added view
textView = new TextView(ActivityName.this);
textView.setId((int)System.currentTimeMillis());
layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.BELOW, recentView.getId());
textView.setText("Time: "+System.currentTimeMillis());
relativeLayout.addView(textView, layoutParams);
recentView = textView;
}
});
}
This can be modified to display each element of a String array in different TextViews.
You're not assigning any id to the text view, but you're using tv.getId() to pass it to the addRule method as a parameter. Try to set a unique id via tv.setId(int).
You could also use the LinearLayout with vertical orientation, that might be easier actually. I prefer LinearLayout over RelativeLayouts if not necessary otherwise.

Categories

Resources