Android OnClickListener throws NullPointerException - android

A table is being created such that:
TableLayout layout = new TableLayout(this);
layout.setLayoutParams(new TableLayout.LayoutParams(4,5));
layout.setPadding(1, 1, 1, 1);
for(int i=0; i<7; i++) {
TableRow tr = new TableRow(this);
for(int j=0; j<6; j++) {
Button b = new Button(this);
b.setText("0");
b.setOnClickListener(buttonListener);
tr.addView(b);
}
layout.addView(tr);
}
super.setContentView(layout);
The OnClickListener buttonListener is:
View.OnClickListener buttonListener = new View.OnClickListener() {
public void onClick(View v) {
Button thisButton = (Button) findViewById(((Button)v).getId());
//thisButton.setText(Integer.toString(Integer.parseInt((String) thisButton.getText()) + 1));
thisButton.getText();
}
};
The call to thisButton.getText() throws a NullPointerException, and I'm not sure why. Can anyone help me out?

TableLayout layout = new TableLayout(this);
layout.setLayoutParams(new TableLayout.LayoutParams(4,5));
layout.setPadding(1, 1, 1, 1);
for(int i=0; i<7; i++) {
TableRow tr = new TableRow(this);
for(int j=0; j<6; j++) {
Button b = new Button(this);
b.setText("0");
b.setOnClickListener(buttonListener);
tr.addView(b);
}
layout.addView(tr);
}
setContentView(layout);
}
View.OnClickListener buttonListener = new View.OnClickListener() {
public void onClick(View v) {
Button btn1 = (Button)v;
//thisButton.setText(Integer.toString(Integer.parseInt((String) thisButton.getText()) + 1));
String name = btn1.getText().toString();
}
};
I have tested this will work.
When you create view dynamically you don't to assgin an id to it.
you work using the object of the view.
I hope it makes sense to all the people who are curious to set id for dynamic buttons.

One problem in your code.
Have not set id of Button
b.setText("0");
b.setOnClickListener(buttonListener);
b.setId(i);

Assumption:
I can't see anything regarding setting id to button
The below line may causing exception:
Button thisButton = (Button) findViewById(((Button)v).getId());
Why are you doing? Instead you are already passing a view in click action: View v
So you can do straight way like:
String strText = ((Button) v).getText();

It mean your thisButton is probably null, because the statement before that was not successful.
Button thisButton = (Button) findViewById(((Button)v).getId());
does not look right. Usually the paramenter inside findViewById() should be a resource id.
such as
Button thisButton = (Button) findViewById(R.id.button);
R.id.button is defined by your layout xml.

You may simply get the text from the passed view, instead of recreating a button.
public void onClick(View v) {
if(v instanceof Button)
String text = ((Button) v).getText();
}

Related

Android issue with programatically created buttons

Well im trying to get the text on each button, it displays the text correctly on each but when i try to print it, it shows the same text. The text of optionD
private void displayQuestion() {
final ArrayList<String> options = new ArrayList<>();
for (int i = 0; i < questions.size(); i++){
Questions diaplayQuestion = questions.get(i);
question.setText(diaplayQuestion.getQuestion());
options.add(0, diaplayQuestion.getOptionA());
options.add(1, diaplayQuestion.getOptionB());
options.add(2, diaplayQuestion.getOptionC());
options.add(3, diaplayQuestion.getOptionD());
correctOption = diaplayQuestion.getCorrectOption();
}
for (int i = 0; i < options.size(); i++) {
btn = new Button(GameplayActivity.this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(10, 10, 10, 0);
btn.setLayoutParams(params);
btn.setText(options.get(i));
btn.setId(i);
linearLayout.addView(btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
System.out.println(view.getId());
}
});
}
}
If you want to store some information inside View use tags. From official docs:
Unlike IDs, tags are not used to identify views. Tags are essentially an extra piece of information that can be associated with a view. They are most often used as a convenience to store data related to views in the views themselves rather than by putting them in a separate structure.
So in your case it'll be like this:
btn = new Button(GameplayActivity.this);
...
btn.setTag(options.get(i)); // I assume that value is String
...
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
System.out.println((String) view.getTag());
}
});

Table with Radiobuttons in Android

I am looking for something similar in android where I can add radiobuttons to each cells in Table and get their position. Does anyone has worked on it before, if you can share the sample code would be helpful. Thanks
The following pseudocode should get you started:
//create a radio group
RadioGroup rg = new RadioGroup(context);
RadioGroup.LayoutParams rgParams = new RadioGroup.LayoutParams(
RadioGroup.LayoutParams.WRAP_CONTENT,
RadioGroup.LayoutParams.WRAP_CONTENT);
rg.setLayoutParams(rgParams);
//add the radio group to the row.
rowView.addView(rg);
//add radio buttons
for (i = 0; i < length; i++) {
RadioButton btn = new RadioButton(context);
btn.setText(description[i]);
//or save an object which will hold all information you need
btn.setTag(rowNumber);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, v.getTag());
}
});
if (<some condition>) {
btn.setChecked(true);
}
rg.addView(btn);
}

setText on TextViews created using a for loop - android

I have created a set of TextViews programmatically using a for loop. This what i have tried.
for(int i=1; i<5; i++){
valueTV = new TextView(AddMyVehicle.this);
linearLayout.addView(valueTV);
vehicleModelReturned = myVehicleData.getString("VehicleModel"+x, "");
valueTV.setText(vehicleModelReturned);
valueTV.setGravity(Gravity.CENTER_HORIZONTAL);
valueTV.setTextSize(TypedValue.COMPLEX_UNIT_SP,22);
valueTV.setTextColor(Color.parseColor("#333333"));
i++;
}
this.valueTV.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
valueTV.setText("Hello");
}
});
I need to change the text of clicked TextView to "Hello". How can i achieve this?
You have to add a listener to all your TextView created.
And be careful, you incremented i twice : one in the first line of the for and another one in the end of the for.
for (int i = 1; i < 5; i++)
{
final TextView valueTV = new TextView(AddMyVehicle.this);
linearLayout.addView(valueTV);
vehicleModelReturned = myVehicleData.getString("VehicleModel" + x, "");
valueTV.setText(vehicleModelReturned);
valueTV.setGravity(Gravity.CENTER_HORIZONTAL);
valueTV.setTextSize(TypedValue.COMPLEX_UNIT_SP, 22);
valueTV.setTextColor(Color.parseColor("#333333"));
valueTV.setId("test");
valueTV.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
TextView tv = (TextView) v;
tv.setText("Hello");
}
});
}
First, set the OnClickListener to all the TextViews you create, not just the last one. That is, move the setOnClickListener() inside the for loop.
Second, in onClick(), change the text of the clicked view and not again the last one you created. The View v param is the view that was clicked. You can cast it to TextView.

Dynamic Buttons and OnClickListener

Say I have buttons that are created dynamically:
for(int j = 0; j < spirits.length;
j++){
Button imgBtn = new Button(v.getContext());
imgBtn.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
imgBtn.setMinimumWidth(100);
imgBtn.setMinimumHeight(100);
imgBtn.setId(j+1);
imgBtn.setTag(spirits[j]);
imgBtn.setText(spirits[j]);
imgBtn.setOnClickListener(new SpiritsClickListener());
cabinet_layout.addView(imgBtn);
}
I want to change the text of the button every time it's pressed (On - Off)
How can I reference the buttons within the OnClickListener class?
in your onClickListener, you have a function called onClick(View v){} where v is the View that was clicked. You may use v to get details about the button, including its ID. You can also take this view, and if you know it is a button, cast it to a button.
Button clicked = (Button)v;
You can then use it in your javacode just as you would normally use a button.
Why don't you just call new OnClickListener() inside that loop like this
for(int j = 0; j < spirits.length;j++){
Button imgBtn = new Button(v.getContext());
imgBtn.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
imgBtn.setMinimumWidth(100);
imgBtn.setMinimumHeight(100);
imgBtn.setId(j+1);
imgBtn.setTag(spirits[j]);
imgBtn.setText(spirits[j]);
imgBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//do what you need to do here
}
});
cabinet_layout.addView(imgBtn);
}
Create an OnClickListener for dynamically created buttons as:
// Create Listener for Button
private OnClickListener SpiritsClickListener = new OnClickListener()
{
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
Button btn = (Button) view;
String btnText = btn.getText();
if(btnText.equalsIgnoreCase("On")){
btn.setText("Off");
}else{
btn.setText("On");
}
}
};
add this Listener to dynamically created buttons as:
imgBtn.setOnClickListener(SpiritsClickListener);

How to interact With each button

I have created an array of buttons..now i want to interact with each button..so that when i click a particular button it will show the text of that button on my text view..so please suggest me for that.. i am sending my code where i have created an array of button..
public boolean initDay()
{
LinearLayout layoutVertical = (LinearLayout) findViewById(R.id.liVLayout);
LinearLayout rowLayout=null;
LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT,1);
for (int i = 0; i<6; i++)
{
rowLayout = new LinearLayout(this);
rowLayout.setWeightSum(7);
layoutVertical.addView(rowLayout,param);
for(int j=0;j<7;j++)
{
pBtnDay[i][j]=new Button(this);
rowLayout.addView(pBtnDay[i][j],param);
pBtnDay[i][j].setClickable(true);
}
}
return true;
}
setOnClickListener() for every object in loop:
pBtnDay[i][j].setOnClickListener(new View.OnClickListener{});
Nothing special. Hope this helps.
pBtnDay[i][j].setOnClickListener(new OnClickListener(){
public void onClick(View v){
v.getText();//it contains button level
}
}
you can interact with each button using this code :
for(int j=0;j<7;j++)
{
pBtnDay[i][j]=new Button(this);
rowLayout.addView(pBtnDay[i][j],param);
pBtnDay[i][j].setClickable(true);
//add a listener for each button
pBtnDay[i][j].setOnClickListener(new OnClickListener(){
Toast.makeText(YourActivity.this, "text of button is "+pBtnDay[i][j].getText(),4000).show();
});
}

Categories

Resources